eventmachine-maglev- 0.12.10 → 1.0.0.beta.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (174) hide show
  1. data/.gitignore +7 -0
  2. data/.yardopts +7 -0
  3. data/Gemfile +3 -0
  4. data/README.md +109 -0
  5. data/Rakefile +14 -368
  6. data/docs/DocumentationGuidesIndex.md +27 -0
  7. data/docs/GettingStarted.md +521 -0
  8. data/docs/old/DEFERRABLES +246 -0
  9. data/docs/{KEYBOARD → old/KEYBOARD} +15 -11
  10. data/docs/old/LIGHTWEIGHT_CONCURRENCY +130 -0
  11. data/docs/old/SMTP +4 -0
  12. data/docs/old/SPAWNED_PROCESSES +148 -0
  13. data/eventmachine.gemspec +20 -26
  14. data/examples/guides/getting_started/01_eventmachine_echo_server.rb +18 -0
  15. data/examples/guides/getting_started/02_eventmachine_echo_server_that_recognizes_exit_command.rb +22 -0
  16. data/examples/guides/getting_started/03_simple_chat_server.rb +149 -0
  17. data/examples/guides/getting_started/04_simple_chat_server_step_one.rb +27 -0
  18. data/examples/guides/getting_started/05_simple_chat_server_step_two.rb +43 -0
  19. data/examples/guides/getting_started/06_simple_chat_server_step_three.rb +98 -0
  20. data/examples/guides/getting_started/07_simple_chat_server_step_four.rb +121 -0
  21. data/examples/guides/getting_started/08_simple_chat_server_step_five.rb +141 -0
  22. data/examples/{ex_channel.rb → old/ex_channel.rb} +3 -3
  23. data/examples/old/ex_tick_loop_array.rb +15 -0
  24. data/examples/old/ex_tick_loop_counter.rb +32 -0
  25. data/ext/binder.cpp +0 -1
  26. data/ext/cmain.cpp +40 -29
  27. data/ext/ed.cpp +189 -134
  28. data/ext/ed.h +34 -40
  29. data/ext/em.cpp +388 -340
  30. data/ext/em.h +29 -32
  31. data/ext/eventmachine.h +7 -6
  32. data/ext/extconf.rb +57 -48
  33. data/ext/fastfilereader/extconf.rb +5 -3
  34. data/ext/fastfilereader/mapper.cpp +1 -1
  35. data/ext/fastfilereader/rubymain.cpp +0 -1
  36. data/ext/kb.cpp +1 -3
  37. data/ext/pipe.cpp +9 -11
  38. data/ext/project.h +12 -8
  39. data/ext/rubymain.cpp +158 -112
  40. data/java/src/com/rubyeventmachine/EmReactor.java +3 -2
  41. data/lib/em/buftok.rb +35 -63
  42. data/lib/em/callback.rb +43 -11
  43. data/lib/em/channel.rb +22 -15
  44. data/lib/em/completion.rb +303 -0
  45. data/lib/em/connection.rb +341 -208
  46. data/lib/em/deferrable/pool.rb +2 -0
  47. data/lib/em/deferrable.rb +20 -2
  48. data/lib/em/file_watch.rb +37 -18
  49. data/lib/em/iterator.rb +270 -0
  50. data/lib/em/pool.rb +146 -0
  51. data/lib/em/process_watch.rb +5 -4
  52. data/lib/em/processes.rb +8 -4
  53. data/lib/em/protocols/httpclient.rb +27 -11
  54. data/lib/em/protocols/httpclient2.rb +15 -5
  55. data/lib/em/protocols/line_protocol.rb +29 -0
  56. data/lib/em/protocols/memcache.rb +17 -9
  57. data/lib/em/protocols/object_protocol.rb +2 -1
  58. data/lib/em/protocols/postgres3.rb +2 -1
  59. data/lib/em/protocols/smtpclient.rb +19 -11
  60. data/lib/em/protocols/smtpserver.rb +101 -8
  61. data/lib/em/protocols/stomp.rb +9 -7
  62. data/lib/em/protocols/tcptest.rb +3 -2
  63. data/lib/em/protocols.rb +1 -1
  64. data/lib/{pr_eventmachine.rb → em/pure_ruby.rb} +188 -205
  65. data/lib/em/queue.rb +23 -13
  66. data/lib/em/resolver.rb +192 -0
  67. data/lib/em/spawnable.rb +9 -10
  68. data/lib/em/streamer.rb +34 -46
  69. data/lib/em/threaded_resource.rb +90 -0
  70. data/lib/em/tick_loop.rb +85 -0
  71. data/lib/em/timers.rb +8 -3
  72. data/lib/em/version.rb +1 -1
  73. data/lib/eventmachine.rb +582 -686
  74. data/lib/jeventmachine.rb +25 -3
  75. data/tasks/package.rake +98 -0
  76. data/tasks/test.rake +8 -0
  77. data/tests/em_test_helper.rb +64 -0
  78. data/tests/test_attach.rb +56 -56
  79. data/tests/test_basic.rb +111 -168
  80. data/tests/test_channel.rb +5 -6
  81. data/tests/test_completion.rb +177 -0
  82. data/tests/test_connection_count.rb +1 -3
  83. data/tests/test_defer.rb +3 -32
  84. data/tests/test_deferrable.rb +35 -0
  85. data/tests/test_epoll.rb +27 -57
  86. data/tests/test_error_handler.rb +10 -7
  87. data/tests/test_exc.rb +6 -33
  88. data/tests/test_file_watch.rb +51 -35
  89. data/tests/test_futures.rb +10 -38
  90. data/tests/test_get_sock_opt.rb +27 -20
  91. data/tests/test_handler_check.rb +1 -3
  92. data/tests/test_hc.rb +49 -112
  93. data/tests/test_httpclient.rb +34 -62
  94. data/tests/test_httpclient2.rb +14 -39
  95. data/tests/test_inactivity_timeout.rb +44 -40
  96. data/tests/test_kb.rb +26 -52
  97. data/tests/test_ltp.rb +27 -71
  98. data/tests/test_ltp2.rb +1 -30
  99. data/tests/test_next_tick.rb +2 -31
  100. data/tests/test_object_protocol.rb +8 -9
  101. data/tests/test_pause.rb +45 -37
  102. data/tests/test_pending_connect_timeout.rb +42 -38
  103. data/tests/test_pool.rb +128 -0
  104. data/tests/test_process_watch.rb +37 -37
  105. data/tests/test_processes.rb +92 -110
  106. data/tests/test_proxy_connection.rb +137 -61
  107. data/tests/test_pure.rb +30 -67
  108. data/tests/test_queue.rb +10 -4
  109. data/tests/test_resolver.rb +55 -0
  110. data/tests/test_running.rb +1 -29
  111. data/tests/test_sasl.rb +8 -33
  112. data/tests/test_send_file.rb +163 -188
  113. data/tests/test_servers.rb +12 -55
  114. data/tests/test_shutdown_hooks.rb +23 -0
  115. data/tests/test_smtpclient.rb +1 -29
  116. data/tests/test_smtpserver.rb +1 -29
  117. data/tests/test_spawn.rb +2 -31
  118. data/tests/test_ssl_args.rb +9 -10
  119. data/tests/test_ssl_methods.rb +1 -3
  120. data/tests/test_ssl_verify.rb +63 -63
  121. data/tests/test_threaded_resource.rb +53 -0
  122. data/tests/test_tick_loop.rb +59 -0
  123. data/tests/test_timers.rb +52 -91
  124. data/tests/test_ud.rb +1 -29
  125. data/tests/test_unbind_reason.rb +31 -0
  126. metadata +113 -70
  127. data/README +0 -82
  128. data/docs/DEFERRABLES +0 -133
  129. data/docs/LIGHTWEIGHT_CONCURRENCY +0 -70
  130. data/docs/SMTP +0 -2
  131. data/docs/SPAWNED_PROCESSES +0 -89
  132. data/ext/cplusplus.cpp +0 -202
  133. data/ext/emwin.cpp +0 -300
  134. data/ext/emwin.h +0 -94
  135. data/ext/epoll.cpp +0 -26
  136. data/ext/epoll.h +0 -25
  137. data/ext/eventmachine_cpp.h +0 -96
  138. data/ext/files.cpp +0 -94
  139. data/ext/files.h +0 -65
  140. data/ext/sigs.cpp +0 -89
  141. data/ext/sigs.h +0 -32
  142. data/java/src/com/rubyeventmachine/application/Application.java +0 -194
  143. data/java/src/com/rubyeventmachine/application/Connection.java +0 -74
  144. data/java/src/com/rubyeventmachine/application/ConnectionFactory.java +0 -37
  145. data/java/src/com/rubyeventmachine/application/DefaultConnectionFactory.java +0 -46
  146. data/java/src/com/rubyeventmachine/application/PeriodicTimer.java +0 -38
  147. data/java/src/com/rubyeventmachine/application/Timer.java +0 -54
  148. data/java/src/com/rubyeventmachine/tests/ApplicationTest.java +0 -109
  149. data/java/src/com/rubyeventmachine/tests/ConnectTest.java +0 -148
  150. data/java/src/com/rubyeventmachine/tests/EMTest.java +0 -80
  151. data/java/src/com/rubyeventmachine/tests/TestDatagrams.java +0 -53
  152. data/java/src/com/rubyeventmachine/tests/TestServers.java +0 -75
  153. data/java/src/com/rubyeventmachine/tests/TestTimers.java +0 -90
  154. data/lib/evma/callback.rb +0 -32
  155. data/lib/evma/container.rb +0 -75
  156. data/lib/evma/factory.rb +0 -77
  157. data/lib/evma/protocol.rb +0 -87
  158. data/lib/evma/reactor.rb +0 -48
  159. data/lib/evma.rb +0 -32
  160. data/setup.rb +0 -1585
  161. data/tests/test_errors.rb +0 -82
  162. data/tests/testem.rb +0 -31
  163. data/web/whatis +0 -7
  164. /data/{docs/GNU → GNU} +0 -0
  165. /data/{docs/COPYING → LICENSE} +0 -0
  166. /data/docs/{ChangeLog → old/ChangeLog} +0 -0
  167. /data/docs/{EPOLL → old/EPOLL} +0 -0
  168. /data/docs/{INSTALL → old/INSTALL} +0 -0
  169. /data/docs/{LEGAL → old/LEGAL} +0 -0
  170. /data/docs/{PURE_RUBY → old/PURE_RUBY} +0 -0
  171. /data/docs/{RELEASE_NOTES → old/RELEASE_NOTES} +0 -0
  172. /data/docs/{TODO → old/TODO} +0 -0
  173. /data/examples/{ex_queue.rb → old/ex_queue.rb} +0 -0
  174. /data/examples/{helper.rb → old/helper.rb} +0 -0
data/lib/eventmachine.rb CHANGED
@@ -1,84 +1,25 @@
1
- #--
2
- #
3
- # Author:: Francis Cianfrocca (gmail: blackhedd)
4
- # Homepage:: http://rubyeventmachine.com
5
- # Date:: 8 Apr 2006
6
- #
7
- # See EventMachine and EventMachine::Connection for documentation and
8
- # usage examples.
9
- #
10
- #----------------------------------------------------------------------------
11
- #
12
- # Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
13
- # Gmail: blackhedd
14
- #
15
- # This program is free software; you can redistribute it and/or modify
16
- # it under the terms of either: 1) the GNU General Public License
17
- # as published by the Free Software Foundation; either version 2 of the
18
- # License, or (at your option) any later version; or 2) Ruby's License.
19
- #
20
- # See the file COPYING for complete licensing information.
21
- #
22
- #---------------------------------------------------------------------------
23
- #
24
- #
25
-
26
-
27
- #-- Select in a library based on a global variable.
28
- # PROVISIONALLY commented out this whole mechanism which selects
29
- # a pure-Ruby EM implementation if the extension is not available.
30
- # I expect this will cause a lot of people's code to break, as it
31
- # exposes misconfigurations and path problems that were masked up
32
- # till now. The reason I'm disabling it is because the pure-Ruby
33
- # code will have problems of its own, and it's not nearly as fast
34
- # anyway. Suggested by a problem report from Moshe Litvin. 05Jun07.
35
- #
36
- # 05Dec07: Re-enabled the pure-ruby mechanism, but without the automatic
37
- # fallback feature that tripped up Moshe Litvin. We shouldn't fail over to
38
- # the pure Ruby version because it's possible that the user intended to
39
- # run the extension but failed to do so because of a compilation or
40
- # similar error. So we require either a global variable or an environment
41
- # string be set in order to select the pure-Ruby version.
42
- #
43
-
44
-
45
- unless defined?($eventmachine_library)
46
- $eventmachine_library = ENV['EVENTMACHINE_LIBRARY'] || :cascade
47
- end
48
- $eventmachine_library = $eventmachine_library.to_sym
49
-
50
- case $eventmachine_library
51
- when :pure_ruby
52
- require 'pr_eventmachine'
53
- when :extension
54
- require 'rubyeventmachine'
55
- when :java
1
+ if RUBY_PLATFORM =~ /java/
2
+ require 'java'
56
3
  require 'jeventmachine'
57
- else # :cascade
58
- # This is the case that most user code will take.
59
- # Prefer the extension if available.
4
+ elsif defined?(EventMachine.library_type) and EventMachine.library_type == :pure_ruby
5
+ # assume 'em/pure_ruby' was loaded already
6
+ else
60
7
  begin
61
- if RUBY_PLATFORM =~ /java/
62
- require 'java'
63
- require 'jeventmachine'
64
- $eventmachine_library = :java
65
- else
66
- require 'rubyeventmachine'
67
- $eventmachine_library = :extension
68
- end
8
+ require 'rubyeventmachine'
69
9
  rescue LoadError
70
- warn "# EventMachine fell back to pure ruby mode" if $DEBUG
71
- require 'pr_eventmachine'
72
- $eventmachine_library = :pure_ruby
10
+ warn "Unable to load the EventMachine C extension; To use the pure-ruby reactor, require 'em/pure_ruby'"
11
+ raise
73
12
  end
74
13
  end
75
14
 
76
- require "em/version"
15
+ require 'em/version'
16
+ require 'em/pool'
77
17
  require 'em/deferrable'
78
18
  require 'em/future'
79
19
  require 'em/streamer'
80
20
  require 'em/spawnable'
81
21
  require 'em/processes'
22
+ require 'em/iterator'
82
23
  require 'em/buftok'
83
24
  require 'em/timers'
84
25
  require 'em/protocols'
@@ -88,153 +29,136 @@ require 'em/queue'
88
29
  require 'em/channel'
89
30
  require 'em/file_watch'
90
31
  require 'em/process_watch'
32
+ require 'em/tick_loop'
33
+ require 'em/resolver'
34
+ require 'em/completion'
35
+ require 'em/threaded_resource'
91
36
 
92
37
  require 'shellwords'
93
38
  require 'thread'
39
+ require 'resolv'
94
40
 
95
- # == Introduction
96
- # EventMachine provides a fast, lightweight framework for implementing
97
- # Ruby programs that can use the network to communicate with other
98
- # processes. Using EventMachine, Ruby programmers can easily connect
99
- # to remote servers and act as servers themselves. EventMachine does not
100
- # supplant the Ruby IP libraries. It does provide an alternate technique
101
- # for those applications requiring better performance, scalability,
102
- # and discipline over the behavior of network sockets, than is easily
103
- # obtainable using the built-in libraries, especially in applications
104
- # which are structurally well-suited for the event-driven programming model.
41
+ # Top-level EventMachine namespace. If you are looking for EventMachine examples, see {file:docs/GettingStarted.md EventMachine tutorial}.
105
42
  #
106
- # EventMachine provides a perpetual event-loop which your programs can
107
- # start and stop. Within the event loop, TCP network connections are
108
- # initiated and accepted, based on EventMachine methods called by your
109
- # program. You also define callback methods which are called by EventMachine
110
- # when events of interest occur within the event-loop.
43
+ # ## Key methods ##
44
+ # ### Starting and stopping the event loop ###
111
45
  #
112
- # User programs will be called back when the following events occur:
113
- # * When the event loop accepts network connections from remote peers
114
- # * When data is received from network connections
115
- # * When connections are closed, either by the local or the remote side
116
- # * When user-defined timers expire
46
+ # * {EventMachine.run}
47
+ # * {EventMachine.stop_event_loop}
117
48
  #
118
- # == Usage example
49
+ # ### Implementing clients ###
119
50
  #
120
- # Here's a fully-functional echo server implemented in EventMachine:
51
+ # * {EventMachine.connect}
121
52
  #
122
- # require 'eventmachine'
53
+ # ### Implementing servers ###
123
54
  #
124
- # module EchoServer
125
- # def post_init
126
- # puts "-- someone connected to the echo server!"
127
- # end
55
+ # * {EventMachine.start_server}
128
56
  #
129
- # def receive_data data
130
- # send_data ">>>you sent: #{data}"
131
- # close_connection if data =~ /quit/i
132
- # end
57
+ # ### Working with timers ###
133
58
  #
134
- # def unbind
135
- # puts "-- someone disconnected from the echo server!"
136
- # end
137
- # end
59
+ # * {EventMachine.add_timer}
60
+ # * {EventMachine.add_periodic_timer}
61
+ # * {EventMachine.cancel_timer}
138
62
  #
139
- # EventMachine::run {
140
- # EventMachine::start_server "127.0.0.1", 8081, EchoServer
141
- # }
63
+ # ### Working with blocking tasks ###
142
64
  #
143
- # What's going on here? Well, we have defined the module EchoServer to
144
- # implement the semantics of the echo protocol (more about that shortly).
145
- # The last three lines invoke the event-machine itself, which runs forever
146
- # unless one of your callbacks terminates it. The block that you supply
147
- # to EventMachine::run contains code that runs immediately after the event
148
- # machine is initialized and before it starts looping. This is the place
149
- # to open up a TCP server by specifying the address and port it will listen
150
- # on, together with the module that will process the data.
151
- #
152
- # Our EchoServer is extremely simple as the echo protocol doesn't require
153
- # much work. Basically you want to send back to the remote peer whatever
154
- # data it sends you. We'll dress it up with a little extra text to make it
155
- # interesting. Also, we'll close the connection in case the received data
156
- # contains the word "quit."
157
- #
158
- # So what about this module EchoServer? Well, whenever a network connection
159
- # (either a client or a server) starts up, EventMachine instantiates an anonymous
160
- # class, that your module has been mixed into. Exactly one of these class
161
- # instances is created for each connection. Whenever an event occurs on a
162
- # given connection, its corresponding object automatically calls specific
163
- # instance methods which your module may redefine. The code in your module
164
- # always runs in the context of a class instance, so you can create instance
165
- # variables as you wish and they will be carried over to other callbacks
166
- # made on that same connection.
167
- #
168
- # Looking back up at EchoServer, you can see that we've defined the method
169
- # receive_data which (big surprise) is called whenever data has been received
170
- # from the remote end of the connection. Very simple. We get the data
171
- # (a String object) and can do whatever we wish with it. In this case,
172
- # we use the method send_data to return the received data to the caller,
173
- # with some extra text added in. And if the user sends the word "quit,"
174
- # we'll close the connection with (naturally) close_connection.
175
- # (Notice that closing the connection doesn't terminate the processing loop,
176
- # or change the fact that your echo server is still accepting connections!)
65
+ # * {EventMachine.defer}
66
+ # * {EventMachine.next_tick}
177
67
  #
178
- # == Questions and Futures
179
- # Would it be useful for EventMachine to incorporate the Observer pattern
180
- # and make use of the corresponding Ruby <tt>observer</tt> package?
181
- # Interesting thought.
68
+ # ### Efficient proxying ###
182
69
  #
70
+ # * {EventMachine.enable_proxy}
71
+ # * {EventMachine.disable_proxy}
183
72
  module EventMachine
184
- class <<self
73
+ class << self
185
74
  # Exposed to allow joining on the thread, when run in a multithreaded
186
75
  # environment. Performing other actions on the thread has undefined
187
- # semantics.
76
+ # semantics (read: a dangerous endevor).
77
+ #
78
+ # @return [Thread]
188
79
  attr_reader :reactor_thread
189
80
  end
190
81
  @next_tick_mutex = Mutex.new
191
82
  @reactor_running = false
192
- @next_tick_queue = nil
83
+ @next_tick_queue = []
84
+ @tails = []
193
85
  @threadpool = nil
194
-
195
-
196
- # EventMachine::run initializes and runs an event loop.
197
- # This method only returns if user-callback code calls stop_event_loop.
198
- # Use the supplied block to define your clients and servers.
199
- # The block is called by EventMachine::run immediately after initializing
200
- # its internal event loop but <i>before</i> running the loop.
201
- # Therefore this block is the right place to call start_server if you
202
- # want to accept connections from remote clients.
203
- #
204
- # For programs that are structured as servers, it's usually appropriate
205
- # to start an event loop by calling EventMachine::run, and let it
206
- # run forever. It's also possible to use EventMachine::run to make a single
207
- # client-connection to a remote server, process the data flow from that
208
- # single connection, and then call stop_event_loop to force EventMachine::run
209
- # to return. Your program will then continue from the point immediately
210
- # following the call to EventMachine::run.
211
- #
212
- # You can of course do both client and servers simultaneously in the same program.
213
- # One of the strengths of the event-driven programming model is that the
214
- # handling of network events on many different connections will be interleaved,
215
- # and scheduled according to the actual events themselves. This maximizes
216
- # efficiency.
217
- #
218
- # === Server usage example
219
- #
220
- # See EventMachine.start_server
221
- #
222
- # === Client usage example
223
- #
224
- # See EventMachine.connect
225
- #
226
- #--
227
- # Obsoleted the use_threads mechanism.
228
- # 25Nov06: Added the begin/ensure block. We need to be sure that release_machine
229
- # gets called even if an exception gets thrown within any of the user code
230
- # that the event loop runs. The best way to see this is to run a unit
231
- # test with two functions, each of which calls EventMachine#run and each of
232
- # which throws something inside of #run. Without the ensure, the second test
233
- # will start without release_machine being called and will immediately throw
234
- # a C++ runtime error.
86
+
87
+ # System errnos
88
+ # @private
89
+ ERRNOS = Errno::constants.grep(/^E/).inject(Hash.new(:unknown)) { |hash, name|
90
+ errno = Errno.__send__(:const_get, name)
91
+ if errno.is_a? Module
92
+ hash[errno::Errno] = errno
93
+ end
94
+ hash
95
+ }
96
+
97
+ # Initializes and runs an event loop. This method only returns if code inside the block passed to this method
98
+ # calls {EventMachine.stop_event_loop}. The block is executed after initializing its internal event loop but *before* running the loop,
99
+ # therefore this block is the right place to call any code that needs event loop to run, for example, {EventMachine.start_server},
100
+ # {EventMachine.connect} or similar methods of libraries that use EventMachine under the hood
101
+ # (like `EventMachine::HttpRequest.new` or `AMQP.start`).
235
102
  #
103
+ # Programs that are run for long periods of time (e.g. servers) usually start event loop by calling {EventMachine.run}, and let it
104
+ # run "forever". It's also possible to use {EventMachine.run} to make a single client-connection to a remote server,
105
+ # process the data flow from that single connection, and then call {EventMachine.stop_event_loop} to stop, in other words,
106
+ # to run event loop for a short period of time (necessary to complete some operation) and then shut it down.
107
+ #
108
+ # Once event loop is running, it is perfectly possible to start multiple servers and clients simultaneously: content-aware
109
+ # proxies like [Proxymachine](https://github.com/mojombo/proxymachine) do just that.
110
+ #
111
+ # ## Using EventMachine with Ruby on Rails and other Web application frameworks ##
112
+ #
113
+ # Standalone applications often run event loop on the main thread, thus blocking for their entire lifespan. In case of Web applications,
114
+ # if you are running an EventMachine-based app server such as [Thin](http://code.macournoyer.com/thin/) or [Goliath](https://github.com/postrank-labs/goliath/),
115
+ # they start event loop for you. Servers like Unicorn, Apache Passenger or Mongrel occupy main Ruby thread to serve HTTP(S) requests. This means
116
+ # that calling {EventMachine.run} on the same thread is not an option (it will result in Web server never binding to the socket).
117
+ # In that case, start event loop in a separate thread as demonstrated below.
118
+ #
119
+ #
120
+ # @example Starting EventMachine event loop in the current thread to run the "Hello, world"-like Echo server example
121
+ #
122
+ # #!/usr/bin/env ruby
123
+ #
124
+ # require 'rubygems' # or use Bundler.setup
125
+ # require 'eventmachine'
126
+ #
127
+ # class EchoServer < EM::Connection
128
+ # def receive_data(data)
129
+ # send_data(data)
130
+ # end
131
+ # end
132
+ #
133
+ # EventMachine.run do
134
+ # EventMachine.start_server("0.0.0.0", 10000, EchoServer)
135
+ # end
136
+ #
137
+ #
138
+ # @example Starting EventMachine event loop in a separate thread
139
+ #
140
+ # # doesn't block current thread, can be used with Ruby on Rails, Sinatra, Merb, Rack
141
+ # # and any other application server that occupies main Ruby thread.
142
+ # Thread.new { EventMachine.run }
143
+ #
144
+ #
145
+ # @note This method blocks calling thread. If you need to start EventMachine event loop from a Web app
146
+ # running on a non event-driven server (Unicorn, Apache Passenger, Mongrel), do it in a separate thread like demonstrated
147
+ # in one of the examples.
148
+ # @see file:docs/GettingStarted.md Getting started with EventMachine
149
+ # @see EventMachine.stop_event_loop
236
150
  def self.run blk=nil, tail=nil, &block
237
- @tails ||= []
151
+ # Obsoleted the use_threads mechanism.
152
+ # 25Nov06: Added the begin/ensure block. We need to be sure that release_machine
153
+ # gets called even if an exception gets thrown within any of the user code
154
+ # that the event loop runs. The best way to see this is to run a unit
155
+ # test with two functions, each of which calls {EventMachine.run} and each of
156
+ # which throws something inside of #run. Without the ensure, the second test
157
+ # will start without release_machine being called and will immediately throw
158
+
159
+ #
160
+
161
+
238
162
  tail and @tails.unshift(tail)
239
163
 
240
164
  if reactor_running?
@@ -245,6 +169,7 @@ module EventMachine
245
169
  @timers = {}
246
170
  @wrapped_exception = nil
247
171
  @next_tick_queue ||= []
172
+ @tails ||= []
248
173
  begin
249
174
  @reactor_running = true
250
175
  initialize_event_machine
@@ -266,15 +191,21 @@ module EventMachine
266
191
  @threadpool.each { |t| t.exit }
267
192
  @threadpool.each do |t|
268
193
  next unless t.alive?
269
- # ruby 1.9 has no kill!
270
- t.respond_to?(:kill!) ? t.kill! : t.kill
194
+ begin
195
+ # Thread#kill! does not exist on 1.9 or rbx, and raises
196
+ # NotImplemented on jruby
197
+ t.kill!
198
+ rescue NoMethodError, NotImplementedError
199
+ t.kill
200
+ # XXX t.join here?
201
+ end
271
202
  end
272
203
  @threadqueue = nil
273
204
  @resultqueue = nil
274
205
  @threadpool = nil
275
206
  end
276
207
 
277
- @next_tick_queue = nil
208
+ @next_tick_queue = []
278
209
  end
279
210
  @reactor_running = false
280
211
  @reactor_thread = nil
@@ -286,8 +217,8 @@ module EventMachine
286
217
 
287
218
  # Sugars a common use case. Will pass the given block to #run, but will terminate
288
219
  # the reactor loop and exit the function as soon as the code in the block completes.
289
- # (Normally, #run keeps running indefinitely, even after the block supplied to it
290
- # finishes running, until user code calls #stop.)
220
+ # (Normally, {EventMachine.run} keeps running indefinitely, even after the block supplied to it
221
+ # finishes running, until user code calls {EventMachine.stop})
291
222
  #
292
223
  def self.run_block &block
293
224
  pr = proc {
@@ -297,13 +228,13 @@ module EventMachine
297
228
  run(&pr)
298
229
  end
299
230
 
300
- # Returns true if the calling thread is the same thread as the reactor.
231
+ # @return [Boolean] true if the calling thread is the same thread as the reactor.
301
232
  def self.reactor_thread?
302
233
  Thread.current == @reactor_thread
303
234
  end
304
235
 
305
236
  # Runs the given callback on the reactor thread, or immediately if called
306
- # from the reactor thread. Accepts the same arguments as EM::Callback
237
+ # from the reactor thread. Accepts the same arguments as {EventMachine::Callback}
307
238
  def self.schedule(*a, &b)
308
239
  cb = Callback(*a, &b)
309
240
  if reactor_running? && reactor_thread?
@@ -313,13 +244,12 @@ module EventMachine
313
244
  end
314
245
  end
315
246
 
316
- # fork_reactor forks a new process and calls EM#run inside of it, passing your block.
317
- #--
318
- # This implementation is subject to change, especially if we clean up the relationship
319
- # of EM#run to @reactor_running.
320
- # Original patch by Aman Gupta.
321
- #
247
+ # Forks a new process, properly stops the reactor and then calls {EventMachine.run} inside of it again, passing your block.
322
248
  def self.fork_reactor &block
249
+ # This implementation is subject to change, especially if we clean up the relationship
250
+ # of EM#run to @reactor_running.
251
+ # Original patch by Aman Gupta.
252
+ #
323
253
  Kernel.fork do
324
254
  if self.reactor_running?
325
255
  self.stop_event_loop
@@ -330,43 +260,54 @@ module EventMachine
330
260
  end
331
261
  end
332
262
 
333
- # EventMachine#add_timer adds a one-shot timer to the event loop.
263
+ # Adds a block to call as the reactor is shutting down.
264
+ #
265
+ # These callbacks are called in the _reverse_ order to which they are added.
266
+ #
267
+ # @example Scheduling operations to be run when EventMachine event loop is stopped
268
+ #
269
+ # EventMachine.run do
270
+ # EventMachine.add_shutdown_hook { puts "b" }
271
+ # EventMachine.add_shutdown_hook { puts "a" }
272
+ # EventMachine.stop
273
+ # end
274
+ #
275
+ # # Outputs:
276
+ # # a
277
+ # # b
278
+ #
279
+ def self.add_shutdown_hook &block
280
+ @tails << block
281
+ end
282
+
283
+ # Adds a one-shot timer to the event loop.
334
284
  # Call it with one or two parameters. The first parameters is a delay-time
335
- # expressed in <i>seconds</i> (not milliseconds). The second parameter, if
336
- # present, must be a proc object. If a proc object is not given, then you
285
+ # expressed in *seconds* (not milliseconds). The second parameter, if
286
+ # present, must be an object that responds to :call. If 2nd parameter is not given, then you
337
287
  # can also simply pass a block to the method call.
338
288
  #
339
- # EventMachine#add_timer may be called from the block passed to EventMachine#run
289
+ # This method may be called from the block passed to {EventMachine.run}
340
290
  # or from any callback method. It schedules execution of the proc or block
341
- # passed to add_timer, after the passage of an interval of time equal to
342
- # <i>at least</i> the number of seconds specified in the first parameter to
291
+ # passed to it, after the passage of an interval of time equal to
292
+ # *at least* the number of seconds specified in the first parameter to
343
293
  # the call.
344
294
  #
345
- # EventMachine#add_timer is a <i>non-blocking</i> call. Callbacks can and will
295
+ # {EventMachine.add_timer} is a non-blocking method. Callbacks can and will
346
296
  # be called during the interval of time that the timer is in effect.
347
297
  # There is no built-in limit to the number of timers that can be outstanding at
348
298
  # any given time.
349
299
  #
350
- # === Usage example
351
- #
352
- # This example shows how easy timers are to use. Observe that two timers are
353
- # initiated simultaneously. Also, notice that the event loop will continue
354
- # to run even after the second timer event is processed, since there was
355
- # no call to EventMachine#stop_event_loop. There will be no activity, of
356
- # course, since no network clients or servers are defined. Stop the program
357
- # with Ctrl-C.
300
+ # @example Setting a one-shot timer with EventMachine
358
301
  #
359
- # EventMachine::run {
302
+ # EventMachine.run {
360
303
  # puts "Starting the run now: #{Time.now}"
361
- # EventMachine::add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
362
- # EventMachine::add_timer( 10 ) { puts "Executing timer event: #{Time.now}" }
304
+ # EventMachine.add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
305
+ # EventMachine.add_timer(10) { puts "Executing timer event: #{Time.now}" }
363
306
  # }
364
307
  #
365
- #
366
- # Also see EventMachine::Timer
367
- #--
368
- # Changed 04Oct06: We now pass the interval as an integer number of milliseconds.
369
- #
308
+ # @param [Integer] delay Delay in seconds
309
+ # @see EventMachine::Timer
310
+ # @see EventMachine.add_periodic_timer
370
311
  def self.add_timer *args, &block
371
312
  interval = args.shift
372
313
  code = args.shift || block
@@ -378,24 +319,22 @@ module EventMachine
378
319
  end
379
320
  end
380
321
 
381
- # EventMachine#add_periodic_timer adds a periodic timer to the event loop.
382
- # It takes the same parameters as the one-shot timer method, EventMachine#add_timer.
322
+ # Adds a periodic timer to the event loop.
323
+ # It takes the same parameters as the one-shot timer method, {EventMachine.add_timer}.
383
324
  # This method schedules execution of the given block repeatedly, at intervals
384
- # of time <i>at least</i> as great as the number of seconds given in the first
325
+ # of time *at least* as great as the number of seconds given in the first
385
326
  # parameter to the call.
386
- #
387
- # === Usage example
388
327
  #
389
- # The following sample program will write a dollar-sign to stderr every five seconds.
390
- # (Of course if the program defined network clients and/or servers, they would
391
- # be doing their work while the periodic timer is counting off.)
328
+ # @example Write a dollar-sign to stderr every five seconds, without blocking
392
329
  #
393
- # EventMachine::run {
394
- # EventMachine::add_periodic_timer( 5 ) { $stderr.write "$" }
330
+ # EventMachine.run {
331
+ # EventMachine.add_periodic_timer( 5 ) { $stderr.write "$" }
395
332
  # }
396
333
  #
334
+ # @param [Integer] delay Delay in seconds
397
335
  #
398
- # Also see EventMachine::PeriodicTimer
336
+ # @see EventMachine::PeriodicTimer
337
+ # @see EventMachine.add_timer
399
338
  #
400
339
  def self.add_periodic_timer *args, &block
401
340
  interval = args.shift
@@ -404,8 +343,11 @@ module EventMachine
404
343
  EventMachine::PeriodicTimer.new(interval, code)
405
344
  end
406
345
 
407
- # Cancel a timer using its signature. You can also use EventMachine::Timer#cancel
346
+
347
+ # Cancel a timer (can be a callback or an {EventMachine::Timer} instance).
408
348
  #
349
+ # @param [#cancel, #call] timer_or_sig A timer to cancel
350
+ # @see EventMachine::Timer#cancel
409
351
  def self.cancel_timer timer_or_sig
410
352
  if timer_or_sig.respond_to? :cancel
411
353
  timer_or_sig.cancel
@@ -415,19 +357,14 @@ module EventMachine
415
357
  end
416
358
 
417
359
 
418
- # stop_event_loop may called from within a callback method
419
- # while EventMachine's processing loop is running.
420
- # It causes the processing loop to stop executing, which
421
- # will cause all open connections and accepting servers
422
- # to be run down and closed. <i>Callbacks for connection-termination
423
- # will be called</i> as part of the processing of stop_event_loop.
424
- # (There currently is no option to panic-stop the loop without
425
- # closing connections.) When all of this processing is complete,
426
- # the call to EventMachine::run which started the processing loop
427
- # will return and program flow will resume from the statement
428
- # following EventMachine::run call.
360
+ # Causes the processing loop to stop executing, which will cause all open connections and accepting servers
361
+ # to be run down and closed. Connection termination callbacks added using {EventMachine.add_shutdown_hook}
362
+ # will be called as part of running this method.
363
+ #
364
+ # When all of this processing is complete, the call to {EventMachine.run} which started the processing loop
365
+ # will return and program flow will resume from the statement following {EventMachine.run} call.
429
366
  #
430
- # === Usage example
367
+ # @example Stopping a running EventMachine event loop
431
368
  #
432
369
  # require 'rubygems'
433
370
  # require 'eventmachine'
@@ -437,40 +374,40 @@ module EventMachine
437
374
  # puts "We're sending a dumb HTTP request to the remote peer."
438
375
  # send_data "GET / HTTP/1.1\r\nHost: www.microsoft.com\r\n\r\n"
439
376
  # end
440
- #
377
+ #
441
378
  # def receive_data data
442
379
  # puts "We received #{data.length} bytes from the remote peer."
443
380
  # puts "We're going to stop the event loop now."
444
381
  # EventMachine::stop_event_loop
445
382
  # end
446
- #
383
+ #
447
384
  # def unbind
448
385
  # puts "A connection has terminated."
449
386
  # end
450
387
  # end
451
- #
388
+ #
452
389
  # puts "We're starting the event loop now."
453
- # EventMachine::run {
454
- # EventMachine::connect "www.microsoft.com", 80, Redmond
390
+ # EventMachine.run {
391
+ # EventMachine.connect "www.microsoft.com", 80, Redmond
455
392
  # }
456
393
  # puts "The event loop has stopped."
457
- #
458
- # This program will produce approximately the following output:
459
394
  #
460
- # We're starting the event loop now.
461
- # We're sending a dumb HTTP request to the remote peer.
462
- # We received 1440 bytes from the remote peer.
463
- # We're going to stop the event loop now.
464
- # A connection has terminated.
465
- # The event loop has stopped.
395
+ # # This program will produce approximately the following output:
396
+ # #
397
+ # # We're starting the event loop now.
398
+ # # We're sending a dumb HTTP request to the remote peer.
399
+ # # We received 1440 bytes from the remote peer.
400
+ # # We're going to stop the event loop now.
401
+ # # A connection has terminated.
402
+ # # The event loop has stopped.
466
403
  #
467
404
  #
468
405
  def self.stop_event_loop
469
406
  EventMachine::stop
470
407
  end
471
408
 
472
- # EventMachine::start_server initiates a TCP server (socket
473
- # acceptor) on the specified IP address and port.
409
+ # Initiates a TCP server (socket acceptor) on the specified IP address and port.
410
+ #
474
411
  # The IP address must be valid on the machine where the program
475
412
  # runs, and the process must be privileged enough to listen
476
413
  # on the specified port (on Unix-like systems, superuser privileges
@@ -478,35 +415,37 @@ module EventMachine
478
415
  # Only one listener may be running on any given address/port
479
416
  # combination. start_server will fail if the given address and port
480
417
  # are already listening on the machine, either because of a prior call
481
- # to start_server or some unrelated process running on the machine.
482
- # If start_server succeeds, the new network listener becomes active
418
+ # to {.start_server} or some unrelated process running on the machine.
419
+ # If {.start_server} succeeds, the new network listener becomes active
483
420
  # immediately and starts accepting connections from remote peers,
484
421
  # and these connections generate callback events that are processed
485
- # by the code specified in the handler parameter to start_server.
422
+ # by the code specified in the handler parameter to {.start_server}.
486
423
  #
487
- # The optional handler which is passed to start_server is the key
424
+ # The optional handler which is passed to this method is the key
488
425
  # to EventMachine's ability to handle particular network protocols.
489
426
  # The handler parameter passed to start_server must be a Ruby Module
490
427
  # that you must define. When the network server that is started by
491
428
  # start_server accepts a new connection, it instantiates a new
492
- # object of an anonymous class that is inherited from EventMachine::Connection,
493
- # <i>into which the methods from your handler have been mixed.</i>
494
- # Your handler module may redefine any of the methods in EventMachine::Connection
495
- # in order to implement the specific behavior of the network protocol.
429
+ # object of an anonymous class that is inherited from {EventMachine::Connection},
430
+ # *into which your handler module have been included*.
431
+ #
432
+ # Your handler module may override any of the methods in {EventMachine::Connection},
433
+ # such as {EventMachine::Connection#receive_data}, in order to implement the specific behavior
434
+ # of the network protocol.
496
435
  #
497
- # Callbacks invoked in response to network events <i>always</i> take place
498
- # within the execution context of the object derived from EventMachine::Connection
436
+ # Callbacks invoked in response to network events *always* take place
437
+ # within the execution context of the object derived from {EventMachine::Connection}
499
438
  # extended by your handler module. There is one object per connection, and
500
439
  # all of the callbacks invoked for a particular connection take the form
501
- # of instance methods called against the corresponding EventMachine::Connection
440
+ # of instance methods called against the corresponding {EventMachine::Connection}
502
441
  # object. Therefore, you are free to define whatever instance variables you
503
442
  # wish, in order to contain the per-connection state required by the network protocol you are
504
443
  # implementing.
505
444
  #
506
- # start_server is often called inside the block passed to EventMachine::run,
507
- # but it can be called from any EventMachine callback. start_server will fail
445
+ # {EventMachine.start_server} is usually called inside the block passed to {EventMachine.run},
446
+ # but it can be called from any EventMachine callback. {EventMachine.start_server} will fail
508
447
  # unless the EventMachine event loop is currently running (which is why
509
- # it's often called in the block suppled to EventMachine::run).
448
+ # it's often called in the block suppled to {EventMachine.run}).
510
449
  #
511
450
  # You may call start_server any number of times to start up network
512
451
  # listeners on different address/port combinations. The servers will
@@ -514,29 +453,29 @@ module EventMachine
514
453
  # can specify a different handler module and thus implement a different
515
454
  # network protocol from all the others.
516
455
  #
517
- # === Usage example
518
- # Here is an example of a server that counts lines of input from the remote
519
- # peer and sends back the total number of lines received, after each line.
520
- # Try the example with more than one client connection opened via telnet,
521
- # and you will see that the line count increments independently on each
522
- # of the client connections. Also very important to note, is that the
523
- # handler for the receive_data function, which our handler redefines, may
524
- # not assume that the data it receives observes any kind of message boundaries.
525
- # Also, to use this example, be sure to change the server and port parameters
526
- # to the start_server call to values appropriate for your environment.
456
+ # @example
527
457
  #
528
458
  # require 'rubygems'
529
459
  # require 'eventmachine'
530
460
  #
461
+ # # Here is an example of a server that counts lines of input from the remote
462
+ # # peer and sends back the total number of lines received, after each line.
463
+ # # Try the example with more than one client connection opened via telnet,
464
+ # # and you will see that the line count increments independently on each
465
+ # # of the client connections. Also very important to note, is that the
466
+ # # handler for the receive_data function, which our handler redefines, may
467
+ # # not assume that the data it receives observes any kind of message boundaries.
468
+ # # Also, to use this example, be sure to change the server and port parameters
469
+ # # to the start_server call to values appropriate for your environment.
531
470
  # module LineCounter
532
471
  # MaxLinesPerConnection = 10
533
- #
472
+ #
534
473
  # def post_init
535
474
  # puts "Received a new connection"
536
475
  # @data_received = ""
537
476
  # @line_count = 0
538
477
  # end
539
- #
478
+ #
540
479
  # def receive_data data
541
480
  # @data_received << data
542
481
  # while @data_received.slice!( /^[^\n]*[\n]/m )
@@ -546,15 +485,22 @@ module EventMachine
546
485
  # end
547
486
  # end
548
487
  # end
549
- #
550
- # EventMachine::run {
551
- # host,port = "192.168.0.100", 8090
552
- # EventMachine::start_server host, port, LineCounter
488
+ #
489
+ # EventMachine.run {
490
+ # host, port = "192.168.0.100", 8090
491
+ # EventMachine.start_server host, port, LineCounter
553
492
  # puts "Now accepting connections on address #{host}, port #{port}..."
554
- # EventMachine::add_periodic_timer( 10 ) { $stderr.write "*" }
493
+ # EventMachine.add_periodic_timer(10) { $stderr.write "*" }
555
494
  # }
556
- #
557
495
  #
496
+ # @param [String] server Host to bind to.
497
+ # @param [Integer] port Port to bind to.
498
+ # @param [Module, Class] handler A module or class that implements connection callbacks
499
+ #
500
+ # @note Don't forget that in order to bind to ports < 1024 on Linux, *BSD and Mac OS X your process must have superuser privileges.
501
+ #
502
+ # @see file:docs/GettingStarted.md EventMachine tutorial
503
+ # @see EventMachine.stop_server
558
504
  def self.start_server server, port=nil, handler=nil, *args, &block
559
505
  begin
560
506
  port = Integer(port)
@@ -578,122 +524,118 @@ module EventMachine
578
524
  end
579
525
 
580
526
 
581
- # Stop a TCP server socket that was started with EventMachine#start_server.
582
- #--
583
- # Requested by Kirk Haines. TODO, this isn't OOP enough. We ought somehow
584
- # to have #start_server return an object that has a close or a stop method on it.
585
- #
527
+ # Stop a TCP server socket that was started with {EventMachine.start_server}.
528
+ # @see EventMachine.start_server
586
529
  def self.stop_server signature
587
530
  EventMachine::stop_tcp_server signature
588
531
  end
589
532
 
590
- # Start a Unix-domain server
533
+ # Start a Unix-domain server.
534
+ #
535
+ # Note that this is an alias for {EventMachine.start_server}, which can be used to start both
536
+ # TCP and Unix-domain servers.
591
537
  #
592
- # Note that this is an alias for EventMachine::start_server, which can be used to start both
593
- # TCP and Unix-domain servers
538
+ # @see EventMachine.start_server
594
539
  def self.start_unix_domain_server filename, *args, &block
595
540
  start_server filename, *args, &block
596
541
  end
597
542
 
598
- # EventMachine#connect initiates a TCP connection to a remote
599
- # server and sets up event-handling for the connection.
600
- # You can call EventMachine#connect in the block supplied
601
- # to EventMachine#run or in any callback method.
543
+ # Initiates a TCP connection to a remote server and sets up event handling for the connection.
544
+ # {EventMachine.connect} requires event loop to be running (see {EventMachine.run}).
602
545
  #
603
- # EventMachine#connect takes the IP address (or hostname) and
546
+ # {EventMachine.connect} takes the IP address (or hostname) and
604
547
  # port of the remote server you want to connect to.
605
- # It also takes an optional handler Module which you must define, that
606
- # contains the callbacks that will be invoked by the event loop
607
- # on behalf of the connection.
548
+ # It also takes an optional handler (a module or a subclass of {EventMachine::Connection}) which you must define, that
549
+ # contains the callbacks that will be invoked by the event loop on behalf of the connection.
608
550
  #
609
- # See the description of EventMachine#start_server for a discussion
610
- # of the handler Module. All of the details given in that description
611
- # apply for connections created with EventMachine#connect.
551
+ # Learn more about connection lifecycle callbacks in the {file:docs/GettingStarted.md EventMachine tutorial} and
552
+ # {file:docs/ConnectionLifecycleCallbacks.md Connection lifecycle guide}.
612
553
  #
613
- # === Usage Example
614
554
  #
615
- # Here's a program which connects to a web server, sends a naive
616
- # request, parses the HTTP header of the response, and then
617
- # (antisocially) ends the event loop, which automatically drops the connection
618
- # (and incidentally calls the connection's unbind method).
619
- #
555
+ # @example
556
+ #
557
+ # # Here's a program which connects to a web server, sends a naive
558
+ # # request, parses the HTTP header of the response, and then
559
+ # # (antisocially) ends the event loop, which automatically drops the connection
560
+ # # (and incidentally calls the connection's unbind method).
620
561
  # module DumbHttpClient
621
562
  # def post_init
622
563
  # send_data "GET / HTTP/1.1\r\nHost: _\r\n\r\n"
623
564
  # @data = ""
624
565
  # @parsed = false
625
566
  # end
626
- #
567
+ #
627
568
  # def receive_data data
628
569
  # @data << data
629
570
  # if !@parsed and @data =~ /[\n][\r]*[\n]/m
630
571
  # @parsed = true
631
572
  # puts "RECEIVED HTTP HEADER:"
632
573
  # $`.each {|line| puts ">>> #{line}" }
633
- #
574
+ #
634
575
  # puts "Now we'll terminate the loop, which will also close the connection"
635
576
  # EventMachine::stop_event_loop
636
577
  # end
637
578
  # end
638
- #
579
+ #
639
580
  # def unbind
640
581
  # puts "A connection has terminated"
641
582
  # end
642
583
  # end
643
- #
644
- # EventMachine::run {
645
- # EventMachine::connect "www.bayshorenetworks.com", 80, DumbHttpClient
584
+ #
585
+ # EventMachine.run {
586
+ # EventMachine.connect "www.bayshorenetworks.com", 80, DumbHttpClient
646
587
  # }
647
588
  # puts "The event loop has ended"
648
- #
649
589
  #
650
- # There are times when it's more convenient to define a protocol handler
651
- # as a Class rather than a Module. Here's how to do this:
590
+ #
591
+ # @example Defining protocol handler as a class
652
592
  #
653
593
  # class MyProtocolHandler < EventMachine::Connection
654
594
  # def initialize *args
655
595
  # super
656
596
  # # whatever else you want to do here
657
597
  # end
658
- #
659
- # #.......your other class code
598
+ #
599
+ # # ...
660
600
  # end
661
601
  #
662
- # If you do this, then an instance of your class will be instantiated to handle
663
- # every network connection created by your code or accepted by servers that you
664
- # create. If you redefine #post_init in your protocol-handler class, your
665
- # #post_init method will be called _inside_ the call to #super that you will
666
- # make in your #initialize method (if you provide one).
667
- #
668
- #--
669
- # EventMachine::connect initiates a TCP connection to a remote
670
- # server and sets up event-handling for the connection.
671
- # It internally creates an object that should not be handled
672
- # by the caller. HOWEVER, it's often convenient to get the
673
- # object to set up interfacing to other objects in the system.
674
- # We return the newly-created anonymous-class object to the caller.
675
- # It's expected that a considerable amount of code will depend
676
- # on this behavior, so don't change it.
677
- #
678
- # Ok, added support for a user-defined block, 13Apr06.
679
- # This leads us to an interesting choice because of the
680
- # presence of the post_init call, which happens in the
681
- # initialize method of the new object. We call the user's
682
- # block and pass the new object to it. This is a great
683
- # way to do protocol-specific initiation. It happens
684
- # AFTER post_init has been called on the object, which I
685
- # certainly hope is the right choice.
686
- # Don't change this lightly, because accepted connections
687
- # are different from connected ones and we don't want
688
- # to have them behave differently with respect to post_init
689
- # if at all possible.
690
602
  #
603
+ # @param [String] server Host to connect to
604
+ # @param [Integer] port Port to connect to
605
+ # @param [Module, Class] handler A module or class that implements connection lifecycle callbacks
606
+ #
607
+ # @see EventMachine.start_server
608
+ # @see file:docs/GettingStarted.md EventMachine tutorial
691
609
  def self.connect server, port=nil, handler=nil, *args, &blk
610
+ # EventMachine::connect initiates a TCP connection to a remote
611
+ # server and sets up event-handling for the connection.
612
+ # It internally creates an object that should not be handled
613
+ # by the caller. HOWEVER, it's often convenient to get the
614
+ # object to set up interfacing to other objects in the system.
615
+ # We return the newly-created anonymous-class object to the caller.
616
+ # It's expected that a considerable amount of code will depend
617
+ # on this behavior, so don't change it.
618
+ #
619
+ # Ok, added support for a user-defined block, 13Apr06.
620
+ # This leads us to an interesting choice because of the
621
+ # presence of the post_init call, which happens in the
622
+ # initialize method of the new object. We call the user's
623
+ # block and pass the new object to it. This is a great
624
+ # way to do protocol-specific initiation. It happens
625
+ # AFTER post_init has been called on the object, which I
626
+ # certainly hope is the right choice.
627
+ # Don't change this lightly, because accepted connections
628
+ # are different from connected ones and we don't want
629
+ # to have them behave differently with respect to post_init
630
+ # if at all possible.
631
+
692
632
  bind_connect nil, nil, server, port, handler, *args, &blk
693
633
  end
694
634
 
695
- # EventMachine::bind_connect is like EventMachine::connect, but allows for a local address/port
635
+ # This method is like {EventMachine.connect}, but allows for a local address/port
696
636
  # to bind the connection to.
637
+ #
638
+ # @see EventMachine.connect
697
639
  def self.bind_connect bind_addr, bind_port, server, port=nil, handler=nil, *args
698
640
  begin
699
641
  port = Integer(port)
@@ -723,18 +665,18 @@ module EventMachine
723
665
  c
724
666
  end
725
667
 
726
- # EventMachine::watch registers a given file descriptor or IO object with the eventloop. The
668
+ # {EventMachine.watch} registers a given file descriptor or IO object with the eventloop. The
727
669
  # file descriptor will not be modified (it will remain blocking or non-blocking).
728
670
  #
729
671
  # The eventloop can be used to process readable and writable events on the file descriptor, using
730
- # EventMachine::Connection#notify_readable= and EventMachine::Connection#notify_writable=
672
+ # {EventMachine::Connection#notify_readable=} and {EventMachine::Connection#notify_writable=}
731
673
  #
732
- # EventMachine::Connection#notify_readable? and EventMachine::Connection#notify_writable? can be used
674
+ # {EventMachine::Connection#notify_readable?} and {EventMachine::Connection#notify_writable?} can be used
733
675
  # to check what events are enabled on the connection.
734
676
  #
735
- # To detach the file descriptor, use EventMachine::Connection#detach
677
+ # To detach the file descriptor, use {EventMachine::Connection#detach}
736
678
  #
737
- # === Usage Example
679
+ # @example
738
680
  #
739
681
  # module SimpleHttpClient
740
682
  # def notify_readable
@@ -756,15 +698,14 @@ module EventMachine
756
698
  # end
757
699
  # end
758
700
  #
759
- # EM.run{
760
- # $sock = TCPSocket.new('site.com', 80)
761
- # $sock.write("GET / HTTP/1.0\r\n\r\n")
762
- # conn = EM.watch $sock, SimpleHttpClient
701
+ # EventMachine.run {
702
+ # sock = TCPSocket.new('site.com', 80)
703
+ # sock.write("GET / HTTP/1.0\r\n\r\n")
704
+ # conn = EventMachine.watch(sock, SimpleHttpClient)
763
705
  # conn.notify_readable = true
764
706
  # }
765
707
  #
766
- #--
767
- # Thanks to Riham Aldakkak (eSpace Technologies) for the initial patch
708
+ # @author Riham Aldakkak (eSpace Technologies)
768
709
  def EventMachine::watch io, handler=nil, *args, &blk
769
710
  attach_io io, true, handler, *args, &blk
770
711
  end
@@ -773,13 +714,14 @@ module EventMachine
773
714
  # The file descriptor will be set as non-blocking, and EventMachine will process
774
715
  # receive_data and send_data events on it as it would for any other connection.
775
716
  #
776
- # To watch a fd instead, use EventMachine::watch, which will not alter the state of the socket
717
+ # To watch a fd instead, use {EventMachine.watch}, which will not alter the state of the socket
777
718
  # and fire notify_readable and notify_writable events instead.
778
719
  def EventMachine::attach io, handler=nil, *args, &blk
779
720
  attach_io io, false, handler, *args, &blk
780
721
  end
781
722
 
782
- def EventMachine::attach_io io, watch_mode, handler=nil, *args # :nodoc:
723
+ # @private
724
+ def EventMachine::attach_io io, watch_mode, handler=nil, *args
783
725
  klass = klass_from_handler(Connection, handler, *args)
784
726
 
785
727
  if !watch_mode and klass.public_instance_methods.any?{|m| [:notify_readable, :notify_writable].include? m.to_sym }
@@ -804,17 +746,19 @@ module EventMachine
804
746
  end
805
747
 
806
748
 
807
- # Connect to a given host/port and re-use the provided EventMachine::Connection instance
808
- #--
809
- # Observe, the test for already-connected FAILS if we call a reconnect inside post_init,
810
- # because we haven't set up the connection in @conns by that point.
811
- # RESIST THE TEMPTATION to "fix" this problem by redefining the behavior of post_init.
812
- #
813
- # Changed 22Nov06: if called on an already-connected handler, just return the
814
- # handler and do nothing more. Originally this condition raised an exception.
815
- # We may want to change it yet again and call the block, if any.
749
+ # Connect to a given host/port and re-use the provided {EventMachine::Connection} instance.
750
+ # Consider also {EventMachine::Connection#reconnect}.
816
751
  #
817
- def self.reconnect server, port, handler # :nodoc:
752
+ # @see EventMachine::Connection#reconnect
753
+ def self.reconnect server, port, handler
754
+ # Observe, the test for already-connected FAILS if we call a reconnect inside post_init,
755
+ # because we haven't set up the connection in @conns by that point.
756
+ # RESIST THE TEMPTATION to "fix" this problem by redefining the behavior of post_init.
757
+ #
758
+ # Changed 22Nov06: if called on an already-connected handler, just return the
759
+ # handler and do nothing more. Originally this condition raised an exception.
760
+ # We may want to change it yet again and call the block, if any.
761
+
818
762
  raise "invalid handler" unless handler.respond_to?(:connection_completed)
819
763
  #raise "still connected" if @conns.has_key?(handler.signature)
820
764
  return handler if @conns.has_key?(handler.signature)
@@ -827,90 +771,77 @@ module EventMachine
827
771
  end
828
772
 
829
773
 
830
- # Make a connection to a Unix-domain socket. This is not implemented on Windows platforms.
831
- # The parameter socketname is a String which identifies the Unix-domain socket you want
832
- # to connect to. socketname is the name of a file on your local system, and in most cases
833
- # is a fully-qualified path name. Make sure that your process has enough local permissions
834
- # to open the Unix-domain socket.
835
- # See also the documentation for #connect. This method behaves like #connect
836
- # in all respects except for the fact that it connects to a local Unix-domain
837
- # socket rather than a TCP socket.
838
- #
839
- # Note that this method is simply an alias for #connect, which can connect to both TCP
840
- # and Unix-domain sockets
841
- #--
842
- # For making connections to Unix-domain sockets.
843
- # Eventually this has to get properly documented and unified with the TCP-connect methods.
844
- # Note how nearly identical this is to EventMachine#connect
774
+ # Make a connection to a Unix-domain socket. This method is simply an alias for {.connect},
775
+ # which can connect to both TCP and Unix-domain sockets. Make sure that your process has sufficient
776
+ # permissions to open the socket it is given.
777
+ #
778
+ # @param [String] socketname Unix domain socket (local fully-qualified path) you want to connect to.
779
+ #
780
+ # @note UNIX sockets, as the name suggests, are not available on Microsoft Windows.
845
781
  def self.connect_unix_domain socketname, *args, &blk
846
782
  connect socketname, *args, &blk
847
783
  end
848
784
 
849
785
 
850
- # EventMachine#open_datagram_socket is for support of UDP-based
851
- # protocols. Its usage is similar to that of EventMachine#start_server.
852
- # It takes three parameters: an IP address (which must be valid
853
- # on the machine which executes the method), a port number,
854
- # and an optional Module name which will handle the data.
786
+ # Used for UDP-based protocols. Its usage is similar to that of {EventMachine.start_server}.
787
+ #
855
788
  # This method will create a new UDP (datagram) socket and
856
789
  # bind it to the address and port that you specify.
857
- # The normal callbacks (see EventMachine#start_server) will
790
+ # The normal callbacks (see {EventMachine.start_server}) will
858
791
  # be called as events of interest occur on the newly-created
859
792
  # socket, but there are some differences in how they behave.
860
793
  #
861
- # Connection#receive_data will be called when a datagram packet
794
+ # {Connection#receive_data} will be called when a datagram packet
862
795
  # is received on the socket, but unlike TCP sockets, the message
863
796
  # boundaries of the received data will be respected. In other words,
864
797
  # if the remote peer sent you a datagram of a particular size,
865
- # you may rely on Connection#receive_data to give you the
798
+ # you may rely on {Connection#receive_data} to give you the
866
799
  # exact data in the packet, with the original data length.
867
800
  # Also observe that Connection#receive_data may be called with a
868
- # <i>zero-length</i> data payload, since empty datagrams are permitted
869
- # in UDP.
801
+ # *zero-length* data payload, since empty datagrams are permitted in UDP.
870
802
  #
871
- # Connection#send_data is available with UDP packets as with TCP,
803
+ # {Connection#send_data} is available with UDP packets as with TCP,
872
804
  # but there is an important difference. Because UDP communications
873
- # are <i>connectionless,</i> there is no implicit recipient for the packets you
805
+ # are *connectionless*, there is no implicit recipient for the packets you
874
806
  # send. Ordinarily you must specify the recipient for each packet you send.
875
- # However, EventMachine
876
- # provides for the typical pattern of receiving a UDP datagram
807
+ # However, EventMachine provides for the typical pattern of receiving a UDP datagram
877
808
  # from a remote peer, performing some operation, and then sending
878
809
  # one or more packets in response to the same remote peer.
879
- # To support this model easily, just use Connection#send_data
880
- # in the code that you supply for Connection:receive_data.
881
- # EventMachine will
882
- # provide an implicit return address for any messages sent to
883
- # Connection#send_data within the context of a Connection#receive_data callback,
810
+ # To support this model easily, just use {Connection#send_data}
811
+ # in the code that you supply for {Connection#receive_data}.
812
+ #
813
+ # EventMachine will provide an implicit return address for any messages sent to
814
+ # {Connection#send_data} within the context of a {Connection#receive_data} callback,
884
815
  # and your response will automatically go to the correct remote peer.
885
- # (TODO: Example-code needed!)
886
816
  #
887
- # Observe that the port number that you supply to EventMachine#open_datagram_socket
817
+ # Observe that the port number that you supply to {EventMachine.open_datagram_socket}
888
818
  # may be zero. In this case, EventMachine will create a UDP socket
889
- # that is bound to an <i>ephemeral</i> (not well-known) port.
819
+ # that is bound to an [ephemeral port](http://en.wikipedia.org/wiki/Ephemeral_port).
890
820
  # This is not appropriate for servers that must publish a well-known
891
821
  # port to which remote peers may send datagrams. But it can be useful
892
822
  # for clients that send datagrams to other servers.
893
823
  # If you do this, you will receive any responses from the remote
894
- # servers through the normal Connection#receive_data callback.
824
+ # servers through the normal {Connection#receive_data} callback.
895
825
  # Observe that you will probably have issues with firewalls blocking
896
826
  # the ephemeral port numbers, so this technique is most appropriate for LANs.
897
- # (TODO: Need an example!)
898
827
  #
899
828
  # If you wish to send datagrams to arbitrary remote peers (not
900
829
  # necessarily ones that have sent data to which you are responding),
901
- # then see Connection#send_datagram.
902
- #
903
- # DO NOT call send_data from a datagram socket
904
- # outside of a #receive_data method. Use #send_datagram. If you do use #send_data
905
- # outside of a #receive_data method, you'll get a confusing error
906
- # because there is no "peer," as #send_data requires. (Inside of #receive_data,
907
- # #send_data "fakes" the peer as described above.)
830
+ # then see {Connection#send_datagram}.
908
831
  #
909
- #--
910
- # Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing
911
- # out that this originally did not take a class but only a module.
832
+ # DO NOT call send_data from a datagram socket outside of a {Connection#receive_data} method. Use {Connection#send_datagram}.
833
+ # If you do use {Connection#send_data} outside of a {Connection#receive_data} method, you'll get a confusing error
834
+ # because there is no "peer," as #send_data requires (inside of {EventMachine::Connection#receive_data},
835
+ # {EventMachine::Connection#send_data} "fakes" the peer as described above).
912
836
  #
837
+ # @param [String] address IP address
838
+ # @param [String] port Port
839
+ # @param [Class, Module] handler A class or a module that implements connection lifecycle callbacks.
913
840
  def self.open_datagram_socket address, port, handler=nil, *args
841
+ # Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing
842
+ # out that this originally did not take a class but only a module.
843
+
844
+
914
845
  klass = klass_from_handler(Connection, handler, *args)
915
846
  s = open_udp_socket address, port.to_i
916
847
  c = klass.new s, *args
@@ -922,31 +853,42 @@ module EventMachine
922
853
 
923
854
  # For advanced users. This function sets the default timer granularity, which by default is
924
855
  # slightly smaller than 100 milliseconds. Call this function to set a higher or lower granularity.
925
- # The function affects the behavior of #add_timer and #add_periodic_timer. Most applications
926
- # will not need to call this function.
856
+ # The function affects the behavior of {EventMachine.add_timer} and {EventMachine.add_periodic_timer}.
857
+ # Most applications will not need to call this function.
858
+ #
859
+ # Avoid setting the quantum to very low values because that may reduce performance under some extreme conditions.
860
+ # We recommend that you not use values lower than 10.
927
861
  #
928
- # The argument is a number of milliseconds. Avoid setting the quantum to very low values because
929
- # that may reduce performance under some extreme conditions. We recommend that you not set a quantum
930
- # lower than 10.
862
+ # This method only can be used if event loop is running.
931
863
  #
932
- # You may only call this function while an EventMachine loop is running (that is, after a call to
933
- # EventMachine#run and before a subsequent call to EventMachine#stop).
864
+ # @param [Integer] mills New timer granularity, in milliseconds
934
865
  #
866
+ # @see EventMachine.add_timer
867
+ # @see EventMachine.add_periodic_timer
868
+ # @see EventMachine::Timer
869
+ # @see EventMachine.run
935
870
  def self.set_quantum mills
936
871
  set_timer_quantum mills.to_i
937
872
  end
938
873
 
939
874
  # Sets the maximum number of timers and periodic timers that may be outstanding at any
940
- # given time. You only need to call #set_max_timers if you need more than the default
875
+ # given time. You only need to call {.set_max_timers} if you need more than the default
941
876
  # number of timers, which on most platforms is 1000.
942
- # Call this method before calling EventMachine#run.
943
877
  #
878
+ # @note This method has to be used *before* event loop is started.
879
+ #
880
+ # @param [Integer] ct Maximum number of timers that may be outstanding at any given time
881
+ #
882
+ # @see EventMachine.add_timer
883
+ # @see EventMachine.add_periodic_timer
884
+ # @see EventMachine::Timer
944
885
  def self.set_max_timers ct
945
886
  set_max_timer_count ct
946
887
  end
947
888
 
948
889
  # Gets the current maximum number of allowed timers
949
890
  #
891
+ # @return [Integer] Maximum number of timers that may be outstanding at any given time
950
892
  def self.get_max_timers
951
893
  get_max_timer_count
952
894
  end
@@ -955,92 +897,101 @@ module EventMachine
955
897
  # Note that a tick must pass after the 'initiation' of a connection for this number to increment.
956
898
  # It's usually accurate, but don't rely on the exact precision of this number unless you really know EM internals.
957
899
  #
958
- # For example, $count will be 0 in this case:
900
+ # @example
959
901
  #
960
- # EM.run {
961
- # EM.connect("rubyeventmachine.com", 80)
962
- # $count = EM.connection_count
902
+ # EventMachine.run {
903
+ # EventMachine.connect("rubyeventmachine.com", 80)
904
+ # # count will be 0 in this case, because connection is not
905
+ # # established yet
906
+ # count = EventMachine.connection_count
963
907
  # }
964
908
  #
965
- # In this example, $count will be 1 since the connection has been established in the next loop of the reactor.
966
909
  #
967
- # EM.run {
968
- # EM.connect("rubyeventmachine.com", 80)
969
- # EM.next_tick {
970
- # $count = EM.connection_count
910
+ # @example
911
+ #
912
+ # EventMachine.run {
913
+ # EventMachine.connect("rubyeventmachine.com", 80)
914
+ #
915
+ # EventMachine.next_tick {
916
+ # # In this example, count will be 1 since the connection has been established in
917
+ # # the next loop of the reactor.
918
+ # count = EventMachine.connection_count
971
919
  # }
972
920
  # }
973
921
  #
922
+ # @return [Integer] Number of connections currently held by the reactor.
974
923
  def self.connection_count
975
924
  self.get_connection_count
976
925
  end
977
926
 
978
- #--
979
927
  # The is the responder for the loopback-signalled event.
980
- # It can be fired either by code running on a separate thread (EM#defer) or on
981
- # the main thread (EM#next_tick).
928
+ # It can be fired either by code running on a separate thread ({EventMachine.defer}) or on
929
+ # the main thread ({EventMachine.next_tick}).
982
930
  # It will often happen that a next_tick handler will reschedule itself. We
983
931
  # consume a copy of the tick queue so that tick events scheduled by tick events
984
932
  # have to wait for the next pass through the reactor core.
985
933
  #
986
- def self.run_deferred_callbacks # :nodoc:
934
+ # @private
935
+ def self.run_deferred_callbacks
987
936
  until (@resultqueue ||= []).empty?
988
937
  result,cback = @resultqueue.pop
989
938
  cback.call result if cback
990
939
  end
991
940
 
992
- jobs = @next_tick_mutex.synchronize do
941
+ @next_tick_mutex.synchronize do
993
942
  jobs, @next_tick_queue = @next_tick_queue, []
994
943
  jobs
995
- end
996
- jobs.each { |j| j.call }
944
+ end.each { |j| j.call }
997
945
  end
998
946
 
999
947
 
1000
- # #defer is for integrating blocking operations into EventMachine's control flow.
1001
- # Call #defer with one or two blocks, as shown below (the second block is <i>optional</i>):
1002
- #
1003
- # operation = proc {
1004
- # # perform a long-running operation here, such as a database query.
1005
- # "result" # as usual, the last expression evaluated in the block will be the return value.
1006
- # }
1007
- # callback = proc {|result|
1008
- # # do something with result here, such as send it back to a network client.
1009
- # }
1010
- #
1011
- # EventMachine.defer( operation, callback )
1012
- #
1013
- # The action of #defer is to take the block specified in the first parameter (the "operation")
948
+ # EventMachine.defer is used for integrating blocking operations into EventMachine's control flow.
949
+ # The action of {.defer} is to take the block specified in the first parameter (the "operation")
1014
950
  # and schedule it for asynchronous execution on an internal thread pool maintained by EventMachine.
1015
951
  # When the operation completes, it will pass the result computed by the block (if any)
1016
952
  # back to the EventMachine reactor. Then, EventMachine calls the block specified in the
1017
- # second parameter to #defer (the "callback"), as part of its normal, synchronous
1018
- # event handling loop. The result computed by the operation block is passed as a parameter
1019
- # to the callback. You may omit the callback parameter if you don't need to execute any code
1020
- # after the operation completes.
953
+ # second parameter to {.defer} (the "callback"), as part of its normal event handling loop.
954
+ # The result computed by the operation block is passed as a parameter to the callback.
955
+ # You may omit the callback parameter if you don't need to execute any code after the operation completes.
956
+ #
957
+ # ## Caveats ##
1021
958
  #
1022
- # == Caveats
1023
959
  # Note carefully that the code in your deferred operation will be executed on a separate
1024
960
  # thread from the main EventMachine processing and all other Ruby threads that may exist in
1025
961
  # your program. Also, multiple deferred operations may be running at once! Therefore, you
1026
- # are responsible for ensuring that your operation code is threadsafe. [Need more explanation
1027
- # and examples.]
962
+ # are responsible for ensuring that your operation code is threadsafe.
963
+ #
1028
964
  # Don't write a deferred operation that will block forever. If so, the current implementation will
1029
965
  # not detect the problem, and the thread will never be returned to the pool. EventMachine limits
1030
966
  # the number of threads in its pool, so if you do this enough times, your subsequent deferred
1031
- # operations won't get a chance to run. [We might put in a timer to detect this problem.]
967
+ # operations won't get a chance to run.
968
+ #
969
+ # @example
970
+ #
971
+ # operation = proc {
972
+ # # perform a long-running operation here, such as a database query.
973
+ # "result" # as usual, the last expression evaluated in the block will be the return value.
974
+ # }
975
+ # callback = proc {|result|
976
+ # # do something with result here, such as send it back to a network client.
977
+ # }
1032
978
  #
1033
- #--
1034
- # OBSERVE that #next_tick hacks into this mechanism, so don't make any changes here
1035
- # without syncing there.
979
+ # EventMachine.defer(operation, callback)
1036
980
  #
1037
- # Running with $VERBOSE set to true gives a warning unless all ivars are defined when
1038
- # they appear in rvalues. But we DON'T ever want to initialize @threadqueue unless we
1039
- # need it, because the Ruby threads are so heavyweight. We end up with this bizarre
1040
- # way of initializing @threadqueue because EventMachine is a Module, not a Class, and
1041
- # has no constructor.
981
+ # @param [#call] op An operation you want to offload to EventMachine thread pool
982
+ # @param [#call] callback A callback that will be run on the event loop thread after `operation` finishes.
1042
983
  #
984
+ # @see EventMachine.threadpool_size
1043
985
  def self.defer op = nil, callback = nil, &blk
986
+ # OBSERVE that #next_tick hacks into this mechanism, so don't make any changes here
987
+ # without syncing there.
988
+ #
989
+ # Running with $VERBOSE set to true gives a warning unless all ivars are defined when
990
+ # they appear in rvalues. But we DON'T ever want to initialize @threadqueue unless we
991
+ # need it, because the Ruby threads are so heavyweight. We end up with this bizarre
992
+ # way of initializing @threadqueue because EventMachine is a Module, not a Class, and
993
+ # has no constructor.
994
+
1044
995
  unless @threadpool
1045
996
  require 'thread'
1046
997
  @threadpool = []
@@ -1052,9 +1003,12 @@ module EventMachine
1052
1003
  @threadqueue << [op||blk,callback]
1053
1004
  end
1054
1005
 
1055
- def self.spawn_threadpool # :nodoc:
1006
+
1007
+ # @private
1008
+ def self.spawn_threadpool
1056
1009
  until @threadpool.size == @threadpool_size.to_i
1057
1010
  thread = Thread.new do
1011
+ Thread.current.abort_on_exception = true
1058
1012
  while true
1059
1013
  op, cback = *@threadqueue.pop
1060
1014
  result = op.call
@@ -1067,9 +1021,11 @@ module EventMachine
1067
1021
  end
1068
1022
 
1069
1023
  class << self
1070
- attr_reader :threadpool # :nodoc:
1024
+ # @private
1025
+ attr_reader :threadpool
1071
1026
 
1072
1027
  # Size of the EventMachine.defer threadpool (defaults to 20)
1028
+ # @return [Number]
1073
1029
  attr_accessor :threadpool_size
1074
1030
  EventMachine.threadpool_size = 20
1075
1031
  end
@@ -1077,64 +1033,67 @@ module EventMachine
1077
1033
  # Schedules a proc for execution immediately after the next "turn" through the reactor
1078
1034
  # core. An advanced technique, this can be useful for improving memory management and/or
1079
1035
  # application responsiveness, especially when scheduling large amounts of data for
1080
- # writing to a network connection. TODO, we need a FAQ entry on this subject.
1081
- #
1082
- # #next_tick takes either a single argument (which must be a Proc) or a block.
1083
- #--
1084
- # This works by adding to the @resultqueue that's used for #defer.
1085
- # The general idea is that next_tick is used when we want to give the reactor a chance
1086
- # to let other operations run, either to balance the load out more evenly, or to let
1087
- # outbound network buffers drain, or both. So we probably do NOT want to block, and
1088
- # we probably do NOT want to be spinning any threads. A program that uses next_tick
1089
- # but not #defer shouldn't suffer the penalty of having Ruby threads running. They're
1090
- # extremely expensive even if they're just sleeping.
1036
+ # writing to a network connection.
1091
1037
  #
1038
+ # This method takes either a single argument (which must be a callable object) or a block.
1039
+ #
1040
+ # @param [#call] pr A callable object to run
1092
1041
  def self.next_tick pr=nil, &block
1042
+ # This works by adding to the @resultqueue that's used for #defer.
1043
+ # The general idea is that next_tick is used when we want to give the reactor a chance
1044
+ # to let other operations run, either to balance the load out more evenly, or to let
1045
+ # outbound network buffers drain, or both. So we probably do NOT want to block, and
1046
+ # we probably do NOT want to be spinning any threads. A program that uses next_tick
1047
+ # but not #defer shouldn't suffer the penalty of having Ruby threads running. They're
1048
+ # extremely expensive even if they're just sleeping.
1049
+
1093
1050
  raise ArgumentError, "no proc or block given" unless ((pr && pr.respond_to?(:call)) or block)
1094
1051
  @next_tick_mutex.synchronize do
1095
- (@next_tick_queue ||= []) << ( pr || block )
1052
+ @next_tick_queue << ( pr || block )
1096
1053
  end
1097
1054
  signal_loopbreak if reactor_running?
1098
1055
  end
1099
1056
 
1100
1057
  # A wrapper over the setuid system call. Particularly useful when opening a network
1101
1058
  # server on a privileged port because you can use this call to drop privileges
1102
- # after opening the port. Also very useful after a call to #set_descriptor_table_size,
1059
+ # after opening the port. Also very useful after a call to {.set_descriptor_table_size},
1103
1060
  # which generally requires that you start your process with root privileges.
1104
1061
  #
1105
- # This method has no effective implementation on Windows or in the pure-Ruby
1106
- # implementation of EventMachine.
1107
- # Call #set_effective_user by passing it a string containing the effective name
1108
- # of the user whose privilege-level your process should attain.
1109
1062
  # This method is intended for use in enforcing security requirements, consequently
1110
1063
  # it will throw a fatal error and end your program if it fails.
1111
1064
  #
1065
+ # @param [String] username The effective name of the user whose privilege-level your process should attain.
1066
+ #
1067
+ # @note This method has no effective implementation on Windows or in the pure-Ruby
1068
+ # implementation of EventMachine
1112
1069
  def self.set_effective_user username
1113
1070
  EventMachine::setuid_string username
1114
1071
  end
1115
1072
 
1116
1073
 
1117
1074
  # Sets the maximum number of file or socket descriptors that your process may open.
1118
- # You can pass this method an integer specifying the new size of the descriptor table.
1119
- # Returns the new descriptor-table size, which may be less than the number you
1120
- # requested. If you call this method with no arguments, it will simply return
1075
+ # If you call this method with no arguments, it will simply return
1121
1076
  # the current size of the descriptor table without attempting to change it.
1122
1077
  #
1123
- # The new limit on open descriptors ONLY applies to sockets and other descriptors
1124
- # that belong to EventMachine. It has NO EFFECT on the number of descriptors
1078
+ # The new limit on open descriptors **only** applies to sockets and other descriptors
1079
+ # that belong to EventMachine. It has **no effect** on the number of descriptors
1125
1080
  # you can create in ordinary Ruby code.
1126
1081
  #
1127
1082
  # Not available on all platforms. Increasing the number of descriptors beyond its
1128
- # default limit usually requires superuser privileges. (See #set_effective_user
1083
+ # default limit usually requires superuser privileges. (See {.set_effective_user}
1129
1084
  # for a way to drop superuser privileges while your program is running.)
1130
1085
  #
1086
+ # @param [Integer] n_descriptors The maximum number of file or socket descriptors that your process may open
1087
+ # @return [Integer] The new descriptor table size.
1131
1088
  def self.set_descriptor_table_size n_descriptors=nil
1132
1089
  EventMachine::set_rlimit_nofile n_descriptors
1133
1090
  end
1134
1091
 
1135
1092
 
1136
1093
 
1137
- # Run an external process. This does not currently work on Windows.
1094
+ # Runs an external process.
1095
+ #
1096
+ # @example
1138
1097
  #
1139
1098
  # module RubyCounter
1140
1099
  # def post_init
@@ -1149,16 +1108,17 @@ module EventMachine
1149
1108
  # end
1150
1109
  # end
1151
1110
  #
1152
- # EM.run{
1153
- # EM.popen("ruby -e' $stdout.sync = true; gets.to_i.times{ |i| puts i+1; sleep 1 } '", RubyCounter)
1111
+ # EventMachine.run {
1112
+ # EventMachine.popen("ruby -e' $stdout.sync = true; gets.to_i.times{ |i| puts i+1; sleep 1 } '", RubyCounter)
1154
1113
  # }
1155
1114
  #
1156
- # Also see EventMachine::DeferrableChildProcess and EventMachine.system
1157
- #--
1158
- # At this moment, it's only available on Unix.
1159
- # Perhaps misnamed since the underlying function uses socketpair and is full-duplex.
1160
- #
1115
+ # @note This method is not supported on Microsoft Windows
1116
+ # @see EventMachine::DeferrableChildProcess
1117
+ # @see EventMachine.system
1161
1118
  def self.popen cmd, handler=nil, *args
1119
+ # At this moment, it's only available on Unix.
1120
+ # Perhaps misnamed since the underlying function uses socketpair and is full-duplex.
1121
+
1162
1122
  klass = klass_from_handler(Connection, handler, *args)
1163
1123
  w = Shellwords::shellwords( cmd )
1164
1124
  w.unshift( w.first ) if w.first
@@ -1170,16 +1130,15 @@ module EventMachine
1170
1130
  end
1171
1131
 
1172
1132
 
1173
- # Tells you whether the EventMachine reactor loop is currently running. Returns true or
1174
- # false. Useful when writing libraries that want to run event-driven code, but may
1175
- # be running in programs that are already event-driven. In such cases, if EventMachine#reactor_running?
1176
- # returns false, your code can invoke EventMachine#run and run your application code inside
1177
- # the block passed to that method. If EventMachine#reactor_running? returns true, just
1178
- # execute your event-aware code.
1133
+ # Tells you whether the EventMachine reactor loop is currently running.
1179
1134
  #
1180
- # This method is necessary because calling EventMachine#run inside of another call to
1181
- # EventMachine#run generates a fatal error.
1135
+ # Useful when writing libraries that want to run event-driven code, but may
1136
+ # be running in programs that are already event-driven. In such cases, if {EventMachine.reactor_running?}
1137
+ # returns false, your code can invoke {EventMachine.run} and run your application code inside
1138
+ # the block passed to that method. If this method returns true, just
1139
+ # execute your event-aware code.
1182
1140
  #
1141
+ # @return [Boolean] true if the EventMachine reactor loop is currently running
1183
1142
  def self.reactor_running?
1184
1143
  (@reactor_running || false)
1185
1144
  end
@@ -1187,7 +1146,7 @@ module EventMachine
1187
1146
 
1188
1147
  # (Experimental)
1189
1148
  #
1190
- #
1149
+ # @private
1191
1150
  def self.open_keyboard handler=nil, *args
1192
1151
  klass = klass_from_handler(Connection, handler, *args)
1193
1152
 
@@ -1199,7 +1158,7 @@ module EventMachine
1199
1158
  end
1200
1159
 
1201
1160
  # EventMachine's file monitoring API. Currently supported are the following events
1202
- # on individual files, using inotify on Linux systems, and kqueue for OSX/BSD:
1161
+ # on individual files, using inotify on Linux systems, and kqueue for *BSD and Mac OS X:
1203
1162
  #
1204
1163
  # * File modified (written to)
1205
1164
  # * File moved/renamed
@@ -1207,26 +1166,26 @@ module EventMachine
1207
1166
  #
1208
1167
  # EventMachine::watch_file takes a filename and a handler Module containing your custom callback methods.
1209
1168
  # This will setup the low level monitoring on the specified file, and create a new EventMachine::FileWatch
1210
- # object with your Module mixed in. FileWatch is a subclass of EM::Connection, so callbacks on this object
1169
+ # object with your Module mixed in. FileWatch is a subclass of {EventMachine::Connection}, so callbacks on this object
1211
1170
  # work in the familiar way. The callbacks that will be fired by EventMachine are:
1212
1171
  #
1213
1172
  # * file_modified
1214
1173
  # * file_moved
1215
1174
  # * file_deleted
1216
1175
  #
1217
- # You can access the filename being monitored from within this object using FileWatch#path.
1176
+ # You can access the filename being monitored from within this object using {FileWatch#path}.
1218
1177
  #
1219
- # When a file is deleted, FileWatch#stop_watching will be called after your file_deleted callback,
1220
- # to clean up the underlying monitoring and remove EventMachine's reference to the now-useless FileWatch.
1178
+ # When a file is deleted, {FileWatch#stop_watching} will be called after your file_deleted callback,
1179
+ # to clean up the underlying monitoring and remove EventMachine's reference to the now-useless {FileWatch} instance.
1221
1180
  # This will in turn call unbind, if you wish to use it.
1222
1181
  #
1223
1182
  # The corresponding system-level Errno will be raised when attempting to monitor non-existent files,
1224
1183
  # files with wrong permissions, or if an error occurs dealing with inotify/kqueue.
1225
1184
  #
1226
- # === Usage example:
1185
+ # @example
1227
1186
  #
1228
- # Make sure we have a file to monitor:
1229
- # $ echo "bar" > /tmp/foo
1187
+ # # Before running this example, make sure we have a file to monitor:
1188
+ # # $ echo "bar" > /tmp/foo
1230
1189
  #
1231
1190
  # module Handler
1232
1191
  # def file_modified
@@ -1246,20 +1205,22 @@ module EventMachine
1246
1205
  # end
1247
1206
  # end
1248
1207
  #
1249
- # EM.kqueue = true if EM.kqueue? # file watching requires kqueue on OSX
1208
+ # # for efficient file watching, use kqueue on Mac OS X
1209
+ # EventMachine.kqueue = true if EventMachine.kqueue?
1250
1210
  #
1251
- # EM.run {
1252
- # EM.watch_file("/tmp/foo", Handler)
1211
+ # EventMachine.run {
1212
+ # EventMachine.watch_file("/tmp/foo", Handler)
1253
1213
  # }
1254
1214
  #
1255
- # $ echo "baz" >> /tmp/foo => "/tmp/foo modified"
1256
- # $ mv /tmp/foo /tmp/oof => "/tmp/foo moved"
1257
- # $ rm /tmp/oof => "/tmp/foo deleted"
1258
- # => "/tmp/foo monitoring ceased"
1215
+ # # $ echo "baz" >> /tmp/foo => "/tmp/foo modified"
1216
+ # # $ mv /tmp/foo /tmp/oof => "/tmp/foo moved"
1217
+ # # $ rm /tmp/oof => "/tmp/foo deleted"
1259
1218
  #
1260
- # Note that we have not implemented the ability to pick up on the new filename after a rename.
1261
- # Calling #path will always return the filename you originally used.
1219
+ # @note The ability to pick up on the new filename after a rename is not yet supported.
1220
+ # Calling #path will always return the filename you originally used.
1262
1221
  #
1222
+ # @param [String] filename Local path to the file to watch.
1223
+ # @param [Class, Module] handler A class or module that implements event handlers associated with the file.
1263
1224
  def self.watch_file(filename, handler=nil, *args)
1264
1225
  klass = klass_from_handler(FileWatch, handler, *args)
1265
1226
 
@@ -1272,9 +1233,9 @@ module EventMachine
1272
1233
  c
1273
1234
  end
1274
1235
 
1275
- # EventMachine's process monitoring API. Currently supported using kqueue for OSX/BSD.
1236
+ # EventMachine's process monitoring API. On Mac OS X and *BSD this method is implemented using kqueue.
1276
1237
  #
1277
- # === Usage example:
1238
+ # @example
1278
1239
  #
1279
1240
  # module ProcessWatcher
1280
1241
  # def process_exited
@@ -1284,11 +1245,13 @@ module EventMachine
1284
1245
  #
1285
1246
  # pid = fork{ sleep }
1286
1247
  #
1287
- # EM.run{
1288
- # EM.watch_process(pid, ProcessWatcher)
1289
- # EM.add_timer(1){ Process.kill('TERM', pid) }
1248
+ # EventMachine.run {
1249
+ # EventMachine.watch_process(pid, ProcessWatcher)
1250
+ # EventMachine.add_timer(1){ Process.kill('TERM', pid) }
1290
1251
  # }
1291
1252
  #
1253
+ # @param [Integer] pid PID of the process to watch.
1254
+ # @param [Class, Module] handler A class or module that implements event handlers associated with the file.
1292
1255
  def self.watch_process(pid, handler=nil, *args)
1293
1256
  pid = pid.to_i
1294
1257
 
@@ -1305,10 +1268,13 @@ module EventMachine
1305
1268
 
1306
1269
  # Catch-all for errors raised during event loop callbacks.
1307
1270
  #
1308
- # EM.error_handler{ |e|
1309
- # puts "Error raised during event loop: #{e.message}"
1310
- # }
1271
+ # @example
1311
1272
  #
1273
+ # EventMachine.error_handler{ |e|
1274
+ # puts "Error raised during event loop: #{e.message}"
1275
+ # }
1276
+ #
1277
+ # @param [#call] cb Global catch-all errback
1312
1278
  def self.error_handler cb = nil, &blk
1313
1279
  if cb or blk
1314
1280
  @error_handler = cb || blk
@@ -1317,12 +1283,12 @@ module EventMachine
1317
1283
  end
1318
1284
  end
1319
1285
 
1320
- # enable_proxy allows for direct writing of incoming data back out to another descriptor, at the C++ level in the reactor.
1321
- # This is especially useful for proxies where high performance is required. Propogating data from a server response
1286
+ # This method allows for direct writing of incoming data back out to another descriptor, at the C++ level in the reactor.
1287
+ # This is very efficient and especially useful for proxies where high performance is required. Propogating data from a server response
1322
1288
  # all the way up to Ruby, and then back down to the reactor to be sent back to the client, is often unnecessary and
1323
1289
  # incurs a significant performance decrease.
1324
1290
  #
1325
- # The two arguments are Connections, 'from' and 'to'. 'from' is the connection whose inbound data you want
1291
+ # The two arguments are instance of {EventMachine::Connection} subclasses, 'from' and 'to'. 'from' is the connection whose inbound data you want
1326
1292
  # relayed back out. 'to' is the connection to write it to.
1327
1293
  #
1328
1294
  # Once you call this method, the 'from' connection will no longer get receive_data callbacks from the reactor,
@@ -1330,10 +1296,10 @@ module EventMachine
1330
1296
  # in the example, that proxy_target_unbound will be called when this occurs. After that, further incoming
1331
1297
  # data will be passed into receive_data as normal.
1332
1298
  #
1333
- # Note also that this feature supports different types of descriptors - TCP, UDP, and pipes. You can relay
1334
- # data from one kind to another.
1299
+ # Note also that this feature supports different types of descriptors: TCP, UDP, and pipes. You can relay
1300
+ # data from one kind to another, for example, feed a pipe from a UDP stream.
1335
1301
  #
1336
- # Example:
1302
+ # @example
1337
1303
  #
1338
1304
  # module ProxyConnection
1339
1305
  # def initialize(client, request)
@@ -1361,42 +1327,55 @@ module EventMachine
1361
1327
  # def receive_data(data)
1362
1328
  # (@buf ||= "") << data
1363
1329
  # if @buf =~ /\r\n\r\n/ # all http headers received
1364
- # EM.connect("10.0.0.15", 80, ProxyConnection, self, data)
1330
+ # EventMachine.connect("10.0.0.15", 80, ProxyConnection, self, data)
1365
1331
  # end
1366
1332
  # end
1367
1333
  # end
1368
1334
  #
1369
- # EM.run {
1370
- # EM.start_server("127.0.0.1", 8080, ProxyServer)
1335
+ # EventMachine.run {
1336
+ # EventMachine.start_server("127.0.0.1", 8080, ProxyServer)
1371
1337
  # }
1372
- def self.enable_proxy(from, to, bufsize=0)
1373
- EM::start_proxy(from.signature, to.signature, bufsize)
1338
+ #
1339
+ # @param [EventMachine::Connection] from Source of data to be proxies/streamed.
1340
+ # @param [EventMachine::Connection] to Destination of data to be proxies/streamed.
1341
+ # @param [Integer] bufsize Buffer size to use
1342
+ # @param [Integer] length Maximum number of bytes to proxy.
1343
+ #
1344
+ # @see EventMachine.disable_proxy
1345
+ def self.enable_proxy(from, to, bufsize=0, length=0)
1346
+ EM::start_proxy(from.signature, to.signature, bufsize, length)
1374
1347
  end
1375
1348
 
1376
- # disable_proxy takes just one argument, a Connection that has proxying enabled via enable_proxy.
1349
+ # Takes just one argument, a {Connection} that has proxying enabled via {EventMachine.enable_proxy}.
1377
1350
  # Calling this method will remove that functionality and your connection will begin receiving
1378
- # data via receive_data again.
1351
+ # data via {Connection#receive_data} again.
1352
+ #
1353
+ # @param [EventMachine::Connection] from Source of data that is being proxied
1354
+ # @see EventMachine.enable_proxy
1379
1355
  def self.disable_proxy(from)
1380
1356
  EM::stop_proxy(from.signature)
1381
1357
  end
1382
1358
 
1383
1359
  # Retrieve the heartbeat interval. This is how often EventMachine will check for dead connections
1384
- # that have had an InactivityTimeout set via Connection#set_comm_inactivity_timeout.
1360
+ # that have had an inactivity timeout set via {Connection#set_comm_inactivity_timeout}.
1385
1361
  # Default is 2 seconds.
1362
+ #
1363
+ # @return [Integer] Heartbeat interval, in seconds
1386
1364
  def self.heartbeat_interval
1387
1365
  EM::get_heartbeat_interval
1388
1366
  end
1389
1367
 
1390
1368
  # Set the heartbeat interval. This is how often EventMachine will check for dead connections
1391
- # that have had an InactivityTimeout set via Connection#set_comm_inactivity_timeout.
1369
+ # that have had an inactivity timeout set via {Connection#set_comm_inactivity_timeout}.
1392
1370
  # Takes a Numeric number of seconds. Default is 2.
1393
- def self.heartbeat_interval= (time)
1371
+ #
1372
+ # @param [Integer] time Heartbeat interval, in seconds
1373
+ def self.heartbeat_interval=(time)
1394
1374
  EM::set_heartbeat_interval time.to_f
1395
1375
  end
1396
1376
 
1397
- private
1398
-
1399
- def self.event_callback conn_binding, opcode, data # :nodoc:
1377
+ # @private
1378
+ def self.event_callback conn_binding, opcode, data
1400
1379
  #
1401
1380
  # Changed 27Dec07: Eliminated the hookable error handling.
1402
1381
  # No one was using it, and it degraded performance significantly.
@@ -1414,7 +1393,11 @@ module EventMachine
1414
1393
  if opcode == ConnectionUnbound
1415
1394
  if c = @conns.delete( conn_binding )
1416
1395
  begin
1417
- c.unbind
1396
+ if c.original_method(:unbind).arity == 1
1397
+ c.unbind(data == 0 ? nil : EventMachine::ERRNOS[data])
1398
+ else
1399
+ c.unbind
1400
+ end
1418
1401
  rescue
1419
1402
  @wrapped_exception = $!
1420
1403
  stop
@@ -1422,7 +1405,12 @@ module EventMachine
1422
1405
  elsif c = @acceptors.delete( conn_binding )
1423
1406
  # no-op
1424
1407
  else
1425
- raise ConnectionNotBound, "recieved ConnectionUnbound for an unknown signature: #{conn_binding}"
1408
+ if $! # Bubble user generated errors.
1409
+ @wrapped_exception = $!
1410
+ EM.stop
1411
+ else
1412
+ raise ConnectionNotBound, "received ConnectionUnbound for an unknown signature: #{conn_binding}"
1413
+ end
1426
1414
  end
1427
1415
  elsif opcode == ConnectionAccepted
1428
1416
  accep,args,blk = @acceptors[conn_binding]
@@ -1431,12 +1419,12 @@ module EventMachine
1431
1419
  @conns[data] = c
1432
1420
  blk and blk.call(c)
1433
1421
  c # (needed?)
1422
+ ##
1423
+ # The remaining code is a fallback for the pure ruby and java reactors.
1424
+ # In the C++ reactor, these events are handled in the C event_callback() in rubymain.cpp
1434
1425
  elsif opcode == ConnectionCompleted
1435
1426
  c = @conns[conn_binding] or raise ConnectionNotBound, "received ConnectionCompleted for unknown signature: #{conn_binding}"
1436
1427
  c.connection_completed
1437
- ##
1438
- # The remaining code is a fallback for the pure ruby and java reactors.
1439
- # In the C++ reactor, these events are handled in the C event_callback() in rubymain.cpp
1440
1428
  elsif opcode == TimerFired
1441
1429
  t = @timers.delete( data )
1442
1430
  return if t == false # timer cancelled
@@ -1456,107 +1444,10 @@ module EventMachine
1456
1444
  end
1457
1445
  end
1458
1446
 
1459
- #--
1460
- # The original event_callback below handled runtime errors in ruby and degraded performance significantly.
1461
- # An optional C-based error handler is now available via EM::error_handler
1462
- #
1463
- # private
1464
- # def EventMachine::original_event_callback conn_binding, opcode, data
1465
- # #
1466
- # # Added 03Oct07: Any code path that invokes user-written code must
1467
- # # wrap itself in a begin/rescue for RuntimeErrors, that calls the
1468
- # # user-overridable class method #handle_runtime_error.
1469
- # #
1470
- # if opcode == ConnectionData
1471
- # c = @conns[conn_binding] or raise ConnectionNotBound
1472
- # begin
1473
- # c.receive_data data
1474
- # rescue
1475
- # EventMachine.handle_runtime_error
1476
- # end
1477
- # elsif opcode == ConnectionUnbound
1478
- # if c = @conns.delete( conn_binding )
1479
- # begin
1480
- # c.unbind
1481
- # rescue
1482
- # EventMachine.handle_runtime_error
1483
- # end
1484
- # elsif c = @acceptors.delete( conn_binding )
1485
- # # no-op
1486
- # else
1487
- # raise ConnectionNotBound
1488
- # end
1489
- # elsif opcode == ConnectionAccepted
1490
- # accep,args,blk = @acceptors[conn_binding]
1491
- # raise NoHandlerForAcceptedConnection unless accep
1492
- # c = accep.new data, *args
1493
- # @conns[data] = c
1494
- # begin
1495
- # blk and blk.call(c)
1496
- # rescue
1497
- # EventMachine.handle_runtime_error
1498
- # end
1499
- # c # (needed?)
1500
- # elsif opcode == TimerFired
1501
- # t = @timers.delete( data ) or raise UnknownTimerFired
1502
- # begin
1503
- # t.call
1504
- # rescue
1505
- # EventMachine.handle_runtime_error
1506
- # end
1507
- # elsif opcode == ConnectionCompleted
1508
- # c = @conns[conn_binding] or raise ConnectionNotBound
1509
- # begin
1510
- # c.connection_completed
1511
- # rescue
1512
- # EventMachine.handle_runtime_error
1513
- # end
1514
- # elsif opcode == LoopbreakSignalled
1515
- # begin
1516
- # run_deferred_callbacks
1517
- # rescue
1518
- # EventMachine.handle_runtime_error
1519
- # end
1520
- # end
1521
- # end
1522
- #
1523
- #
1524
- # # Default handler for RuntimeErrors that are raised in user code.
1525
- # # The default behavior is to re-raise the error, which ends your program.
1526
- # # To override the default behavior, re-implement this method in your code.
1527
- # # For example:
1528
- # #
1529
- # # module EventMachine
1530
- # # def self.handle_runtime_error
1531
- # # $>.puts $!
1532
- # # end
1533
- # # end
1534
- # #
1535
- # #--
1536
- # # We need to ensure that any code path which invokes user code rescues RuntimeError
1537
- # # and calls this method. The obvious place to do that is in #event_callback,
1538
- # # but, scurrilously, it turns out that we need to be finer grained that that.
1539
- # # Periodic timers, in particular, wrap their invocations of user code inside
1540
- # # procs that do other stuff we can't not do, like schedule the next invocation.
1541
- # # This is a potential non-robustness, since we need to remember to hook in the
1542
- # # error handler whenever and wherever we change how user code is invoked.
1543
- # #
1544
- # def EventMachine::handle_runtime_error
1545
- # @runtime_error_hook ? @runtime_error_hook.call : raise
1546
- # end
1547
- #
1548
- # # Sets a handler for RuntimeErrors that are raised in user code.
1549
- # # Pass a block with no parameters. You can also call this method without a block,
1550
- # # which restores the default behavior (see #handle_runtime_error).
1551
- # #
1552
- # def EventMachine::set_runtime_error_hook &blk
1553
- # @runtime_error_hook = blk
1554
- # end
1555
-
1556
- #--
1557
- # This is a provisional implementation of a stream-oriented file access object.
1558
- # We also experiment with wrapping up some better exception reporting.
1559
- def self._open_file_for_writing filename, handler=nil # :nodoc:
1447
+ #
1448
+ #
1449
+ # @private
1450
+ def self._open_file_for_writing filename, handler=nil
1560
1451
  klass = klass_from_handler(Connection, handler)
1561
1452
 
1562
1453
  s = _write_file filename
@@ -1566,13 +1457,17 @@ module EventMachine
1566
1457
  c
1567
1458
  end
1568
1459
 
1569
- private
1460
+ # @private
1570
1461
  def self.klass_from_handler(klass = Connection, handler = nil, *args)
1571
1462
  klass = if handler and handler.is_a?(Class)
1572
1463
  raise ArgumentError, "must provide module or subclass of #{klass.name}" unless klass >= handler
1573
1464
  handler
1574
1465
  elsif handler
1575
- Class.new(klass){ include handler }
1466
+ begin
1467
+ handler::EM_CONNECTION_CLASS
1468
+ rescue NameError
1469
+ handler::const_set(:EM_CONNECTION_CLASS, Class.new(klass) {include handler})
1470
+ end
1576
1471
  else
1577
1472
  klass
1578
1473
  end
@@ -1587,6 +1482,7 @@ module EventMachine
1587
1482
  end
1588
1483
  end # module EventMachine
1589
1484
 
1590
- # Save everyone some typing.
1485
+ # Alias for {EventMachine}
1591
1486
  EM = EventMachine
1592
- EM::P = EventMachine::Protocols
1487
+ # Alias for {EventMachine::Protocols}
1488
+ EM::P = EventMachine::Protocols