polyphony 0.40 → 0.43.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/test.yml +11 -2
  3. data/.gitignore +2 -2
  4. data/.rubocop.yml +30 -0
  5. data/CHANGELOG.md +29 -2
  6. data/Gemfile.lock +13 -10
  7. data/README.md +0 -1
  8. data/Rakefile +3 -3
  9. data/TODO.md +27 -97
  10. data/docs/_config.yml +56 -7
  11. data/docs/_sass/custom/custom.scss +6 -26
  12. data/docs/_sass/overrides.scss +0 -46
  13. data/docs/{user-guide → _user-guide}/all-about-timers.md +0 -0
  14. data/docs/_user-guide/index.md +9 -0
  15. data/docs/{user-guide → _user-guide}/web-server.md +0 -0
  16. data/docs/api-reference/fiber.md +2 -2
  17. data/docs/api-reference/index.md +9 -0
  18. data/docs/api-reference/polyphony-process.md +1 -1
  19. data/docs/api-reference/thread.md +1 -1
  20. data/docs/faq.md +21 -11
  21. data/docs/favicon.ico +0 -0
  22. data/docs/getting-started/index.md +10 -0
  23. data/docs/getting-started/installing.md +2 -6
  24. data/docs/getting-started/overview.md +486 -0
  25. data/docs/getting-started/tutorial.md +27 -19
  26. data/docs/index.md +6 -2
  27. data/docs/main-concepts/concurrency.md +0 -5
  28. data/docs/main-concepts/design-principles.md +69 -21
  29. data/docs/main-concepts/extending.md +1 -1
  30. data/docs/main-concepts/index.md +9 -0
  31. data/docs/polyphony-logo.png +0 -0
  32. data/examples/adapters/redis_blpop.rb +12 -0
  33. data/examples/core/01-spinning-up-fibers.rb +1 -0
  34. data/examples/core/03-interrupting.rb +4 -1
  35. data/examples/core/04-handling-signals.rb +19 -0
  36. data/examples/core/xx-agent.rb +102 -0
  37. data/examples/core/xx-sleeping.rb +14 -6
  38. data/examples/io/xx-irb.rb +1 -1
  39. data/examples/performance/thread-vs-fiber/polyphony_mt_server.rb +7 -6
  40. data/examples/performance/thread-vs-fiber/polyphony_server.rb +13 -36
  41. data/examples/performance/thread-vs-fiber/polyphony_server_read_loop.rb +58 -0
  42. data/examples/performance/xx-array.rb +11 -0
  43. data/examples/performance/xx-fiber-switch.rb +9 -0
  44. data/examples/performance/xx-snooze.rb +15 -0
  45. data/ext/{gyro → polyphony}/extconf.rb +2 -2
  46. data/ext/{gyro → polyphony}/fiber.c +15 -22
  47. data/ext/{gyro → polyphony}/libev.c +0 -0
  48. data/ext/{gyro → polyphony}/libev.h +0 -0
  49. data/ext/polyphony/libev_agent.c +725 -0
  50. data/ext/polyphony/libev_queue.c +217 -0
  51. data/ext/{gyro/gyro.c → polyphony/polyphony.c} +12 -37
  52. data/ext/polyphony/polyphony.h +90 -0
  53. data/ext/polyphony/polyphony_ext.c +21 -0
  54. data/ext/{gyro → polyphony}/thread.c +34 -151
  55. data/ext/{gyro → polyphony}/tracing.c +1 -1
  56. data/lib/polyphony.rb +19 -12
  57. data/lib/polyphony/adapters/irb.rb +1 -1
  58. data/lib/polyphony/adapters/postgres.rb +6 -5
  59. data/lib/polyphony/adapters/process.rb +5 -5
  60. data/lib/polyphony/adapters/redis.rb +3 -2
  61. data/lib/polyphony/adapters/trace.rb +28 -28
  62. data/lib/polyphony/core/channel.rb +3 -3
  63. data/lib/polyphony/core/exceptions.rb +1 -1
  64. data/lib/polyphony/core/global_api.rb +13 -11
  65. data/lib/polyphony/core/resource_pool.rb +3 -3
  66. data/lib/polyphony/core/sync.rb +2 -2
  67. data/lib/polyphony/core/thread_pool.rb +6 -6
  68. data/lib/polyphony/core/throttler.rb +13 -6
  69. data/lib/polyphony/event.rb +27 -0
  70. data/lib/polyphony/extensions/core.rb +22 -14
  71. data/lib/polyphony/extensions/fiber.rb +4 -4
  72. data/lib/polyphony/extensions/io.rb +59 -25
  73. data/lib/polyphony/extensions/openssl.rb +36 -16
  74. data/lib/polyphony/extensions/socket.rb +28 -10
  75. data/lib/polyphony/extensions/thread.rb +16 -9
  76. data/lib/polyphony/net.rb +9 -9
  77. data/lib/polyphony/version.rb +1 -1
  78. data/polyphony.gemspec +3 -3
  79. data/test/helper.rb +12 -1
  80. data/test/test_agent.rb +130 -0
  81. data/test/{test_async.rb → test_event.rb} +13 -7
  82. data/test/test_ext.rb +25 -4
  83. data/test/test_fiber.rb +19 -10
  84. data/test/test_global_api.rb +6 -6
  85. data/test/test_io.rb +46 -24
  86. data/test/test_queue.rb +74 -0
  87. data/test/test_signal.rb +3 -40
  88. data/test/test_socket.rb +34 -0
  89. data/test/test_thread.rb +37 -16
  90. data/test/test_trace.rb +6 -5
  91. metadata +39 -41
  92. data/docs/_includes/nav.html +0 -51
  93. data/docs/_includes/prevnext.html +0 -17
  94. data/docs/_layouts/default.html +0 -106
  95. data/docs/api-reference.md +0 -11
  96. data/docs/api-reference/gyro-async.md +0 -57
  97. data/docs/api-reference/gyro-child.md +0 -29
  98. data/docs/api-reference/gyro-queue.md +0 -44
  99. data/docs/api-reference/gyro-timer.md +0 -51
  100. data/docs/api-reference/gyro.md +0 -25
  101. data/docs/getting-started.md +0 -10
  102. data/docs/main-concepts.md +0 -10
  103. data/docs/user-guide.md +0 -10
  104. data/examples/core/forever_sleep.rb +0 -19
  105. data/ext/gyro/async.c +0 -132
  106. data/ext/gyro/child.c +0 -108
  107. data/ext/gyro/gyro.h +0 -158
  108. data/ext/gyro/gyro_ext.c +0 -33
  109. data/ext/gyro/io.c +0 -457
  110. data/ext/gyro/queue.c +0 -146
  111. data/ext/gyro/selector.c +0 -205
  112. data/ext/gyro/signal.c +0 -99
  113. data/ext/gyro/socket.c +0 -213
  114. data/ext/gyro/timer.c +0 -115
  115. data/test/test_timer.rb +0 -56
@@ -20,22 +20,22 @@ end
20
20
 
21
21
  def handle_client(socket)
22
22
  parser = Http::Parser.new
23
- req = nil
23
+ reqs = []
24
24
  parser.on_message_complete = proc do |env|
25
- req = parser
25
+ reqs << Object.new # parser
26
26
  end
27
27
  while (data = socket.readpartial(8192)) do
28
28
  parser << data
29
- if req
29
+ while (req = reqs.shift)
30
30
  handle_request(socket, req)
31
31
  req = nil
32
- snooze
32
+ # snooze
33
33
  end
34
34
  end
35
35
  rescue IOError, SystemCallError => e
36
36
  # do nothing
37
37
  ensure
38
- socket.close rescue nil
38
+ socket&.close
39
39
  parser.reset!
40
40
  end
41
41
 
@@ -46,13 +46,14 @@ def handle_request(client, parser)
46
46
  client.write "HTTP/1.1 #{status_code}\r\n#{headers}\r\n#{data}"
47
47
  end
48
48
 
49
- $incoming = Gyro::Queue.new
49
+ $incoming = Polyphony::Queue.new
50
50
 
51
51
  $threads = (1..4).map {
52
52
  Thread.new {
53
53
  Thread.current.setup_fiber_scheduling
54
54
  loop {
55
55
  conn = $incoming.pop
56
+ puts "#{Thread.current.inspect} pop #{conn.inspect}"
56
57
  spin { handle_client(conn) }
57
58
  }
58
59
  }
@@ -4,21 +4,10 @@ require 'bundler/setup'
4
4
  require 'polyphony'
5
5
  require 'http/parser'
6
6
 
7
- class Http::Parser
8
- def setup_async
9
- self.on_message_complete = proc { @request_complete = true }
10
- end
11
-
12
- def parse(data)
13
- self << data
14
- return nil unless @request_complete
15
-
16
- @request_complete = nil
17
- self
18
- end
19
- end
7
+ $connection_count = 0
20
8
 
21
9
  def handle_client(socket)
10
+ $connection_count += 1
22
11
  parser = Http::Parser.new
23
12
  reqs = []
24
13
  parser.on_message_complete = proc do |env|
@@ -29,40 +18,28 @@ def handle_client(socket)
29
18
  while (req = reqs.shift)
30
19
  handle_request(socket, req)
31
20
  req = nil
32
- # snooze
21
+ snooze
33
22
  end
34
23
  end
35
24
  rescue IOError, SystemCallError => e
36
25
  # do nothing
37
26
  ensure
38
- socket.close rescue nil
39
- parser.reset!
27
+ $connection_count -= 1
28
+ socket&.close
40
29
  end
41
30
 
42
31
  def handle_request(client, parser)
43
- status_code = 200
32
+ status_code = "200 OK"
44
33
  data = "Hello world!\n"
45
- headers = "Content-Length: #{data.bytesize}\r\n"
34
+ headers = "Content-Type: text/plain\r\nContent-Length: #{data.bytesize}\r\n"
46
35
  client.write "HTTP/1.1 #{status_code}\r\n#{headers}\r\n#{data}"
47
36
  end
48
37
 
49
- spin do
50
- server = TCPServer.open('0.0.0.0', 1234)
51
- puts "listening on port 1234"
52
-
53
- loop do
54
- client = server.accept
55
- spin { handle_client(client) }
56
- # snooze
57
- end
58
- end
38
+ server = TCPServer.open('0.0.0.0', 1234)
39
+ puts "pid #{Process.pid}"
40
+ puts "listening on port 1234"
59
41
 
60
- spin do
61
- loop do
62
- sleep 1
63
- puts "#{Time.now} #{Thread.current.fiber_scheduling_stats}"
64
- end
42
+ loop do
43
+ client = server.accept
44
+ spin { handle_client(client) }
65
45
  end
66
-
67
- puts "pid #{Process.pid}"
68
- suspend
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/setup'
4
+ require 'polyphony'
5
+ require 'http/parser'
6
+
7
+ $connection_count = 0
8
+
9
+ def handle_client(socket)
10
+ $connection_count += 1
11
+ parser = Http::Parser.new
12
+ reqs = []
13
+ parser.on_message_complete = proc do |env|
14
+ reqs << Object.new # parser
15
+ end
16
+ socket.read_loop do |data|
17
+ parser << data
18
+ while (req = reqs.shift)
19
+ handle_request(socket, req)
20
+ end
21
+ end
22
+ rescue IOError, SystemCallError => e
23
+ # do nothing
24
+ ensure
25
+ $connection_count -= 1
26
+ socket&.close
27
+ end
28
+
29
+ def handle_request(client, parser)
30
+ status_code = "200 OK"
31
+ data = "Hello world!\n"
32
+ headers = "Content-Type: text/plain\r\nContent-Length: #{data.bytesize}\r\n"
33
+ client.write "HTTP/1.1 #{status_code}\r\n#{headers}\r\n#{data}"
34
+ end
35
+
36
+ spin do
37
+ server = TCPServer.open('0.0.0.0', 1234)
38
+ puts "listening on port 1234"
39
+
40
+ Thread.current.agent.accept_loop(server) do |client|
41
+ spin { handle_client(client) }
42
+ end
43
+ # loop do
44
+ # client = server.accept
45
+ # spin { handle_client(client) }
46
+ # end
47
+ ensure
48
+ server&.close
49
+ end
50
+
51
+ # every(1) {
52
+ # stats = Thread.current.fiber_scheduling_stats
53
+ # stats[:connection_count] = $connection_count
54
+ # puts "#{Time.now} #{stats}"
55
+ # }
56
+
57
+ puts "pid #{Process.pid}"
58
+ suspend
@@ -0,0 +1,11 @@
1
+ X = ARGV[0] ? ARGV[0].to_i : 10
2
+ a = (1..X).to_a
3
+
4
+ Y = 1_000_000
5
+ t0 = Time.now
6
+ Y.times do
7
+ i = a.shift
8
+ a.push i
9
+ end
10
+
11
+ puts "rate: #{Y / (Time.now - t0)}"
@@ -0,0 +1,9 @@
1
+ X = 1_000_000
2
+ f = Fiber.new do
3
+ loop { Fiber.yield }
4
+ end
5
+
6
+ t0 = Time.now
7
+ X.times { f.resume }
8
+ dt = Time.now - t0
9
+ puts "#{X / dt.to_f}/s"
@@ -0,0 +1,15 @@
1
+ require 'bundler/setup'
2
+ require 'polyphony'
3
+
4
+ Y = ARGV[0] ? ARGV[0].to_i : 1
5
+
6
+ count = 0
7
+ Y.times do
8
+ spin { loop { count += 1; snooze } }
9
+ end
10
+
11
+ t0 = Time.now
12
+ sleep 10
13
+ elapsed = Time.now - t0
14
+ rate = count / elapsed
15
+ puts "concurrency: #{Y} rate: #{rate} switchpoints per second"
@@ -16,5 +16,5 @@ $defs << "-DHAVE_SYS_RESOURCE_H" if have_header("sys/resource.h")
16
16
 
17
17
  CONFIG["optflags"] << " -fno-strict-aliasing" unless RUBY_PLATFORM =~ /mswin/
18
18
 
19
- dir_config "gyro_ext"
20
- create_makefile "gyro_ext"
19
+ dir_config "polyphony_ext"
20
+ create_makefile "polyphony_ext"
@@ -1,8 +1,7 @@
1
- #include "gyro.h"
1
+ #include "polyphony.h"
2
2
 
3
3
  ID ID_fiber_trace;
4
- ID ID_ivar_auto_async;
5
- ID ID_ivar_auto_io;
4
+ ID ID_ivar_auto_watcher;
6
5
  ID ID_trace_ev_loop_enter;
7
6
  ID ID_trace_ev_loop_leave;
8
7
  ID ID_trace_run;
@@ -10,6 +9,8 @@ ID ID_trace_runnable;
10
9
  ID ID_trace_terminate;
11
10
  ID ID_trace_wait;
12
11
 
12
+ VALUE cEvent = Qnil;
13
+
13
14
  VALUE SYM_dead;
14
15
  VALUE SYM_running;
15
16
  VALUE SYM_runnable;
@@ -32,22 +33,18 @@ static VALUE Fiber_safe_transfer(int argc, VALUE *argv, VALUE self) {
32
33
  return ret;
33
34
  }
34
35
 
35
- inline VALUE Fiber_auto_async(VALUE self) {
36
- VALUE async = rb_ivar_get(self, ID_ivar_auto_async);
37
- if (async == Qnil) {
38
- async = rb_funcall(cGyro_Async, ID_new, 0);
39
- rb_ivar_set(self, ID_ivar_auto_async, async);
36
+ inline VALUE Fiber_auto_watcher(VALUE self) {
37
+ VALUE watcher;
38
+ if (cEvent == Qnil) {
39
+ cEvent = rb_const_get(mPolyphony, rb_intern("Event"));
40
40
  }
41
- return async;
42
- }
43
41
 
44
- inline VALUE Fiber_auto_io(VALUE self) {
45
- VALUE io = rb_ivar_get(self, ID_ivar_auto_io);
46
- if (io == Qnil) {
47
- io = rb_funcall(cGyro_IO, ID_new, 2, Qnil, Qnil);
48
- rb_ivar_set(self, ID_ivar_auto_io, io);
42
+ watcher = rb_ivar_get(self, ID_ivar_auto_watcher);
43
+ if (watcher == Qnil) {
44
+ watcher = rb_funcall(cEvent, ID_new, 0);
45
+ rb_ivar_set(self, ID_ivar_auto_watcher, watcher);
49
46
  }
50
- return io;
47
+ return watcher;
51
48
  }
52
49
 
53
50
  static VALUE Fiber_schedule(int argc, VALUE *argv, VALUE self) {
@@ -71,21 +68,16 @@ void Fiber_make_runnable(VALUE fiber, VALUE value) {
71
68
  Thread_schedule_fiber(thread, fiber, value);
72
69
  }
73
70
  else {
74
- VALUE caller;
75
71
  rb_warn("No thread set for fiber (fiber, value, caller):");
76
- caller = rb_funcall(rb_cObject, rb_intern("caller"), 0);
77
- INSPECT(3, fiber, value, caller);
78
72
  }
79
73
  }
80
74
 
81
75
  void Init_Fiber() {
82
76
  VALUE cFiber = rb_const_get(rb_cObject, rb_intern("Fiber"));
83
- rb_define_method(cFiber, "auto_async", Fiber_auto_async, 0);
84
77
  rb_define_method(cFiber, "safe_transfer", Fiber_safe_transfer, -1);
85
78
  rb_define_method(cFiber, "schedule", Fiber_schedule, -1);
86
79
  rb_define_method(cFiber, "state", Fiber_state, 0);
87
-
88
- ID_ivar_auto_async = rb_intern("@auto_async");
80
+ rb_define_method(cFiber, "auto_watcher", Fiber_auto_watcher, 0);
89
81
 
90
82
  SYM_dead = ID2SYM(rb_intern("dead"));
91
83
  SYM_running = ID2SYM(rb_intern("running"));
@@ -97,6 +89,7 @@ void Init_Fiber() {
97
89
  rb_global_variable(&SYM_waiting);
98
90
 
99
91
  ID_fiber_trace = rb_intern("__fiber_trace__");
92
+ ID_ivar_auto_watcher = rb_intern("@auto_watcher");
100
93
 
101
94
  SYM_fiber_create = ID2SYM(rb_intern("fiber_create"));
102
95
  SYM_fiber_ev_loop_enter = ID2SYM(rb_intern("fiber_ev_loop_enter"));
File without changes
File without changes
@@ -0,0 +1,725 @@
1
+ #include <netdb.h>
2
+ #include <sys/socket.h>
3
+
4
+ #include "polyphony.h"
5
+ #include "../libev/ev.h"
6
+
7
+ VALUE cLibevAgent = Qnil;
8
+ VALUE cTCPSocket;
9
+
10
+ struct LibevAgent_t {
11
+ struct ev_loop *ev_loop;
12
+ struct ev_async break_async;
13
+ int running;
14
+ int ref_count;
15
+ int run_no_wait_count;
16
+ };
17
+
18
+ static size_t LibevAgent_size(const void *ptr) {
19
+ return sizeof(struct LibevAgent_t);
20
+ }
21
+
22
+ static const rb_data_type_t LibevAgent_type = {
23
+ "Libev",
24
+ {0, 0, LibevAgent_size,},
25
+ 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
26
+ };
27
+
28
+ static VALUE LibevAgent_allocate(VALUE klass) {
29
+ struct LibevAgent_t *agent = ALLOC(struct LibevAgent_t);
30
+
31
+ return TypedData_Wrap_Struct(klass, &LibevAgent_type, agent);
32
+ }
33
+
34
+ #define GetLibevAgent(obj, agent) \
35
+ TypedData_Get_Struct((obj), struct LibevAgent_t, &LibevAgent_type, (agent))
36
+
37
+ void break_async_callback(struct ev_loop *ev_loop, struct ev_async *ev_async, int revents) {
38
+ // This callback does nothing, the break async is used solely for breaking out
39
+ // of a *blocking* event loop (waking it up) in a thread-safe, signal-safe manner
40
+ }
41
+
42
+ static VALUE LibevAgent_initialize(VALUE self) {
43
+ struct LibevAgent_t *agent;
44
+ VALUE thread = rb_thread_current();
45
+ int is_main_thread = (thread == rb_thread_main());
46
+
47
+ GetLibevAgent(self, agent);
48
+ agent->ev_loop = is_main_thread ? EV_DEFAULT : ev_loop_new(EVFLAG_NOSIGMASK);
49
+
50
+ ev_async_init(&agent->break_async, break_async_callback);
51
+ ev_async_start(agent->ev_loop, &agent->break_async);
52
+ ev_unref(agent->ev_loop); // don't count the break_async watcher
53
+
54
+ agent->running = 0;
55
+ agent->ref_count = 0;
56
+ agent->run_no_wait_count = 0;
57
+
58
+ return Qnil;
59
+ }
60
+
61
+ VALUE LibevAgent_finalize(VALUE self) {
62
+ struct LibevAgent_t *agent;
63
+ GetLibevAgent(self, agent);
64
+
65
+ ev_async_stop(agent->ev_loop, &agent->break_async);
66
+
67
+ if (!ev_is_default_loop(agent->ev_loop)) ev_loop_destroy(agent->ev_loop);
68
+
69
+ return self;
70
+ }
71
+
72
+ VALUE LibevAgent_post_fork(VALUE self) {
73
+ struct LibevAgent_t *agent;
74
+ GetLibevAgent(self, agent);
75
+
76
+ if (!ev_is_default_loop(agent->ev_loop)) {
77
+ // post_fork is called only for the main thread of the forked process. If
78
+ // the forked process was forked from a thread other than the main one,
79
+ // we remove the old non-default ev_loop and use the default one instead.
80
+ ev_loop_destroy(agent->ev_loop);
81
+ agent->ev_loop = EV_DEFAULT;
82
+ }
83
+
84
+ ev_loop_fork(agent->ev_loop);
85
+
86
+ return self;
87
+ }
88
+
89
+ VALUE LibevAgent_ref(VALUE self) {
90
+ struct LibevAgent_t *agent;
91
+ GetLibevAgent(self, agent);
92
+
93
+ agent->ref_count++;
94
+ return self;
95
+ }
96
+
97
+ VALUE LibevAgent_unref(VALUE self) {
98
+ struct LibevAgent_t *agent;
99
+ GetLibevAgent(self, agent);
100
+
101
+ agent->ref_count--;
102
+ return self;
103
+ }
104
+
105
+ int LibevAgent_ref_count(VALUE self) {
106
+ struct LibevAgent_t *agent;
107
+ GetLibevAgent(self, agent);
108
+
109
+ return agent->ref_count;
110
+ }
111
+
112
+ void LibevAgent_reset_ref_count(VALUE self) {
113
+ struct LibevAgent_t *agent;
114
+ GetLibevAgent(self, agent);
115
+
116
+ agent->ref_count = 0;
117
+ }
118
+
119
+ VALUE LibevAgent_pending_count(VALUE self) {
120
+ int count;
121
+ struct LibevAgent_t *agent;
122
+ GetLibevAgent(self, agent);
123
+ count = ev_pending_count(agent->ev_loop);
124
+ return INT2NUM(count);
125
+ }
126
+
127
+ VALUE LibevAgent_poll(VALUE self, VALUE nowait, VALUE current_fiber, VALUE queue) {
128
+ int is_nowait = nowait == Qtrue;
129
+ struct LibevAgent_t *agent;
130
+ GetLibevAgent(self, agent);
131
+
132
+ if (is_nowait) {
133
+ long runnable_count = RARRAY_LEN(queue);
134
+ agent->run_no_wait_count++;
135
+ if (agent->run_no_wait_count < runnable_count || agent->run_no_wait_count < 10)
136
+ return self;
137
+ }
138
+
139
+ agent->run_no_wait_count = 0;
140
+
141
+ FIBER_TRACE(2, SYM_fiber_ev_loop_enter, current_fiber);
142
+ agent->running = 1;
143
+ ev_run(agent->ev_loop, is_nowait ? EVRUN_NOWAIT : EVRUN_ONCE);
144
+ agent->running = 0;
145
+ FIBER_TRACE(2, SYM_fiber_ev_loop_leave, current_fiber);
146
+
147
+ return self;
148
+ }
149
+
150
+ VALUE LibevAgent_break(VALUE self) {
151
+ struct LibevAgent_t *agent;
152
+ GetLibevAgent(self, agent);
153
+
154
+ if (agent->running) {
155
+ // Since the loop will run until at least one event has occurred, we signal
156
+ // the selector's associated async watcher, which will cause the ev loop to
157
+ // return. In contrast to using `ev_break` to break out of the loop, which
158
+ // should be called from the same thread (from within the ev_loop), using an
159
+ // `ev_async` allows us to interrupt the event loop across threads.
160
+ ev_async_send(agent->ev_loop, &agent->break_async);
161
+ return Qtrue;
162
+ }
163
+
164
+ return Qnil;
165
+ }
166
+
167
+ #include "polyphony.h"
168
+ #include "../libev/ev.h"
169
+
170
+ //////////////////////////////////////////////////////////////////////
171
+ //////////////////////////////////////////////////////////////////////
172
+ // the following is copied verbatim from the Ruby source code (io.c)
173
+ struct io_internal_read_struct {
174
+ int fd;
175
+ int nonblock;
176
+ void *buf;
177
+ size_t capa;
178
+ };
179
+
180
+ #define StringValue(v) rb_string_value(&(v))
181
+
182
+ int io_setstrbuf(VALUE *str, long len) {
183
+ #ifdef _WIN32
184
+ len = (len + 1) & ~1L; /* round up for wide char */
185
+ #endif
186
+ if (NIL_P(*str)) {
187
+ *str = rb_str_new(0, len);
188
+ return 1;
189
+ }
190
+ else {
191
+ VALUE s = StringValue(*str);
192
+ long clen = RSTRING_LEN(s);
193
+ if (clen >= len) {
194
+ rb_str_modify(s);
195
+ return 0;
196
+ }
197
+ len -= clen;
198
+ }
199
+ rb_str_modify_expand(*str, len);
200
+ return 0;
201
+ }
202
+
203
+ #define MAX_REALLOC_GAP 4096
204
+ static void io_shrink_read_string(VALUE str, long n) {
205
+ if (rb_str_capacity(str) - n > MAX_REALLOC_GAP) {
206
+ rb_str_resize(str, n);
207
+ }
208
+ }
209
+
210
+ void io_set_read_length(VALUE str, long n, int shrinkable) {
211
+ if (RSTRING_LEN(str) != n) {
212
+ rb_str_modify(str);
213
+ rb_str_set_len(str, n);
214
+ if (shrinkable) io_shrink_read_string(str, n);
215
+ }
216
+ }
217
+
218
+ static rb_encoding* io_read_encoding(rb_io_t *fptr) {
219
+ if (fptr->encs.enc) {
220
+ return fptr->encs.enc;
221
+ }
222
+ return rb_default_external_encoding();
223
+ }
224
+
225
+ VALUE io_enc_str(VALUE str, rb_io_t *fptr) {
226
+ OBJ_TAINT(str);
227
+ rb_enc_associate(str, io_read_encoding(fptr));
228
+ return str;
229
+ }
230
+
231
+ //////////////////////////////////////////////////////////////////////
232
+ //////////////////////////////////////////////////////////////////////
233
+
234
+ struct libev_io {
235
+ struct ev_io io;
236
+ VALUE fiber;
237
+ };
238
+
239
+ void LibevAgent_io_callback(EV_P_ ev_io *w, int revents)
240
+ {
241
+ struct libev_io *watcher = (struct libev_io *)w;
242
+ Fiber_make_runnable(watcher->fiber, Qnil);
243
+ }
244
+
245
+ inline VALUE libev_await(struct LibevAgent_t *agent) {
246
+ VALUE ret;
247
+ agent->ref_count++;
248
+ ret = Thread_switch_fiber(rb_thread_current());
249
+ agent->ref_count--;
250
+ RB_GC_GUARD(ret);
251
+ return ret;
252
+ }
253
+
254
+ VALUE libev_agent_await(VALUE self) {
255
+ struct LibevAgent_t *agent;
256
+ GetLibevAgent(self, agent);
257
+ return libev_await(agent);
258
+ }
259
+
260
+ VALUE libev_io_wait(struct LibevAgent_t *agent, struct libev_io *watcher, rb_io_t *fptr, int flags) {
261
+ VALUE switchpoint_result;
262
+
263
+ if (watcher->fiber == Qnil) {
264
+ watcher->fiber = rb_fiber_current();
265
+ ev_io_init(&watcher->io, LibevAgent_io_callback, fptr->fd, flags);
266
+ }
267
+ ev_io_start(agent->ev_loop, &watcher->io);
268
+ switchpoint_result = libev_await(agent);
269
+ ev_io_stop(agent->ev_loop, &watcher->io);
270
+
271
+ RB_GC_GUARD(switchpoint_result);
272
+ return switchpoint_result;
273
+ }
274
+
275
+ VALUE libev_snooze() {
276
+ Fiber_make_runnable(rb_fiber_current(), Qnil);
277
+ return Thread_switch_fiber(rb_thread_current());
278
+ }
279
+
280
+ VALUE LibevAgent_read(VALUE self, VALUE io, VALUE str, VALUE length, VALUE to_eof) {
281
+ struct LibevAgent_t *agent;
282
+ struct libev_io watcher;
283
+ rb_io_t *fptr;
284
+ long len = NUM2INT(length);
285
+ int shrinkable = io_setstrbuf(&str, len);
286
+ char *buf = RSTRING_PTR(str);
287
+ long total = 0;
288
+ VALUE switchpoint_result = Qnil;
289
+ int read_to_eof = RTEST(to_eof);
290
+ VALUE underlying_io = rb_iv_get(io, "@io");
291
+
292
+ GetLibevAgent(self, agent);
293
+ if (underlying_io != Qnil) io = underlying_io;
294
+ GetOpenFile(io, fptr);
295
+ rb_io_check_byte_readable(fptr);
296
+ rb_io_set_nonblock(fptr);
297
+ watcher.fiber = Qnil;
298
+
299
+ OBJ_TAINT(str);
300
+
301
+ while (len > 0) {
302
+ ssize_t n = read(fptr->fd, buf, len);
303
+ if (n < 0) {
304
+ int e = errno;
305
+ if (e != EWOULDBLOCK && e != EAGAIN) rb_syserr_fail(e, strerror(e));
306
+
307
+ switchpoint_result = libev_io_wait(agent, &watcher, fptr, EV_READ);
308
+ if (TEST_EXCEPTION(switchpoint_result)) goto error;
309
+ }
310
+ else {
311
+ switchpoint_result = libev_snooze();
312
+ if (TEST_EXCEPTION(switchpoint_result)) goto error;
313
+
314
+ if (n == 0) break; // EOF
315
+
316
+ total = total + n;
317
+ buf += n;
318
+ len -= n;
319
+ if (!read_to_eof || (len == 0)) break;
320
+ }
321
+ }
322
+
323
+ if (total == 0) return Qnil;
324
+
325
+ io_set_read_length(str, total, shrinkable);
326
+ io_enc_str(str, fptr);
327
+
328
+ RB_GC_GUARD(watcher.fiber);
329
+ RB_GC_GUARD(switchpoint_result);
330
+
331
+ return str;
332
+ error:
333
+ return rb_funcall(rb_mKernel, ID_raise, 1, switchpoint_result);
334
+ }
335
+
336
+ VALUE LibevAgent_read_loop(VALUE self, VALUE io) {
337
+
338
+ #define PREPARE_STR() { \
339
+ str = Qnil; \
340
+ shrinkable = io_setstrbuf(&str, len); \
341
+ buf = RSTRING_PTR(str); \
342
+ total = 0; \
343
+ }
344
+
345
+ #define YIELD_STR() { \
346
+ io_set_read_length(str, total, shrinkable); \
347
+ io_enc_str(str, fptr); \
348
+ rb_yield(str); \
349
+ PREPARE_STR(); \
350
+ }
351
+
352
+ struct LibevAgent_t *agent;
353
+ struct libev_io watcher;
354
+ rb_io_t *fptr;
355
+ VALUE str;
356
+ long total;
357
+ long len = 8192;
358
+ int shrinkable;
359
+ char *buf;
360
+ VALUE switchpoint_result = Qnil;
361
+ VALUE underlying_io = rb_iv_get(io, "@io");
362
+
363
+ PREPARE_STR();
364
+
365
+ GetLibevAgent(self, agent);
366
+ if (underlying_io != Qnil) io = underlying_io;
367
+ GetOpenFile(io, fptr);
368
+ rb_io_check_byte_readable(fptr);
369
+ rb_io_set_nonblock(fptr);
370
+ watcher.fiber = Qnil;
371
+
372
+ OBJ_TAINT(str);
373
+
374
+ while (1) {
375
+ ssize_t n = read(fptr->fd, buf, len);
376
+ if (n < 0) {
377
+ int e = errno;
378
+ if ((e != EWOULDBLOCK && e != EAGAIN)) rb_syserr_fail(e, strerror(e));
379
+
380
+ switchpoint_result = libev_io_wait(agent, &watcher, fptr, EV_READ);
381
+ if (TEST_EXCEPTION(switchpoint_result)) goto error;
382
+ }
383
+ else {
384
+ switchpoint_result = libev_snooze();
385
+ if (TEST_EXCEPTION(switchpoint_result)) goto error;
386
+
387
+ if (n == 0) break; // EOF
388
+
389
+ total = n;
390
+ YIELD_STR();
391
+ Fiber_make_runnable(rb_fiber_current(), Qnil);
392
+ switchpoint_result = Thread_switch_fiber(rb_thread_current());
393
+ if (TEST_EXCEPTION(switchpoint_result)) {
394
+ goto error;
395
+ }
396
+ }
397
+ }
398
+
399
+ RB_GC_GUARD(str);
400
+ RB_GC_GUARD(watcher.fiber);
401
+ RB_GC_GUARD(switchpoint_result);
402
+
403
+ return io;
404
+ error:
405
+ return rb_funcall(rb_mKernel, ID_raise, 1, switchpoint_result);
406
+ }
407
+
408
+ VALUE LibevAgent_write(VALUE self, VALUE io, VALUE str) {
409
+ struct LibevAgent_t *agent;
410
+ struct libev_io watcher;
411
+ rb_io_t *fptr;
412
+ VALUE switchpoint_result = Qnil;
413
+
414
+ char *buf = StringValuePtr(str);
415
+ long len = RSTRING_LEN(str);
416
+ long left = len;
417
+
418
+ VALUE underlying_io = rb_iv_get(io, "@io");
419
+ if (underlying_io != Qnil) io = underlying_io;
420
+ GetLibevAgent(self, agent);
421
+ io = rb_io_get_write_io(io);
422
+ GetOpenFile(io, fptr);
423
+ watcher.fiber = Qnil;
424
+
425
+ while (left > 0) {
426
+ ssize_t n = write(fptr->fd, buf, left);
427
+ if (n < 0) {
428
+ int e = errno;
429
+ if ((e != EWOULDBLOCK && e != EAGAIN)) rb_syserr_fail(e, strerror(e));
430
+
431
+ switchpoint_result = libev_io_wait(agent, &watcher, fptr, EV_WRITE);
432
+ if (TEST_EXCEPTION(switchpoint_result)) goto error;
433
+ }
434
+ else {
435
+ switchpoint_result = libev_snooze();
436
+ if (TEST_EXCEPTION(switchpoint_result)) goto error;
437
+
438
+ buf += n;
439
+ left -= n;
440
+ }
441
+ }
442
+
443
+ RB_GC_GUARD(watcher.fiber);
444
+ RB_GC_GUARD(switchpoint_result);
445
+
446
+ return INT2NUM(len);
447
+ error:
448
+ return rb_funcall(rb_mKernel, ID_raise, 1, switchpoint_result);
449
+ }
450
+
451
+ ///////////////////////////////////////////////////////////////////////////
452
+
453
+ VALUE LibevAgent_accept(VALUE self, VALUE sock) {
454
+ struct LibevAgent_t *agent;
455
+ struct libev_io watcher;
456
+ rb_io_t *fptr;
457
+ int fd;
458
+ struct sockaddr addr;
459
+ socklen_t len = (socklen_t)sizeof addr;
460
+ VALUE switchpoint_result = Qnil;
461
+ VALUE underlying_sock = rb_iv_get(sock, "@io");
462
+ if (underlying_sock != Qnil) sock = underlying_sock;
463
+
464
+ GetLibevAgent(self, agent);
465
+ GetOpenFile(sock, fptr);
466
+ rb_io_set_nonblock(fptr);
467
+ watcher.fiber = Qnil;
468
+ while (1) {
469
+ fd = accept(fptr->fd, &addr, &len);
470
+ if (fd < 0) {
471
+ int e = errno;
472
+ if ((e != EWOULDBLOCK && e != EAGAIN)) rb_syserr_fail(e, strerror(e));
473
+
474
+ switchpoint_result = libev_io_wait(agent, &watcher, fptr, EV_READ);
475
+ if (TEST_EXCEPTION(switchpoint_result)) goto error;
476
+ }
477
+ else {
478
+ VALUE socket;
479
+ rb_io_t *fp;
480
+ switchpoint_result = libev_snooze();
481
+ if (TEST_EXCEPTION(switchpoint_result)) {
482
+ close(fd); // close fd since we're raising an exception
483
+ goto error;
484
+ }
485
+
486
+ socket = rb_obj_alloc(cTCPSocket);
487
+ MakeOpenFile(socket, fp);
488
+ rb_update_max_fd(fd);
489
+ fp->fd = fd;
490
+ fp->mode = FMODE_READWRITE | FMODE_DUPLEX;
491
+ rb_io_ascii8bit_binmode(socket);
492
+ rb_io_set_nonblock(fp);
493
+ rb_io_synchronized(fp);
494
+
495
+ // if (rsock_do_not_reverse_lookup) {
496
+ // fp->mode |= FMODE_NOREVLOOKUP;
497
+ // }
498
+ return socket;
499
+ }
500
+ }
501
+ RB_GC_GUARD(switchpoint_result);
502
+ return Qnil;
503
+ error:
504
+ return rb_funcall(rb_mKernel, ID_raise, 1, switchpoint_result);
505
+ }
506
+
507
+ VALUE LibevAgent_accept_loop(VALUE self, VALUE sock) {
508
+ struct LibevAgent_t *agent;
509
+ struct libev_io watcher;
510
+ rb_io_t *fptr;
511
+ int fd;
512
+ struct sockaddr addr;
513
+ socklen_t len = (socklen_t)sizeof addr;
514
+ VALUE switchpoint_result = Qnil;
515
+ VALUE socket = Qnil;
516
+ VALUE underlying_sock = rb_iv_get(sock, "@io");
517
+ if (underlying_sock != Qnil) sock = underlying_sock;
518
+
519
+ GetLibevAgent(self, agent);
520
+ GetOpenFile(sock, fptr);
521
+ rb_io_set_nonblock(fptr);
522
+ watcher.fiber = Qnil;
523
+
524
+ while (1) {
525
+ fd = accept(fptr->fd, &addr, &len);
526
+ if (fd < 0) {
527
+ int e = errno;
528
+ if ((e != EWOULDBLOCK && e != EAGAIN)) rb_syserr_fail(e, strerror(e));
529
+
530
+ switchpoint_result = libev_io_wait(agent, &watcher, fptr, EV_READ);
531
+ if (TEST_EXCEPTION(switchpoint_result)) goto error;
532
+ }
533
+ else {
534
+ rb_io_t *fp;
535
+ switchpoint_result = libev_snooze();
536
+ if (TEST_EXCEPTION(switchpoint_result)) {
537
+ close(fd); // close fd since we're raising an exception
538
+ goto error;
539
+ }
540
+
541
+ socket = rb_obj_alloc(cTCPSocket);
542
+ MakeOpenFile(socket, fp);
543
+ rb_update_max_fd(fd);
544
+ fp->fd = fd;
545
+ fp->mode = FMODE_READWRITE | FMODE_DUPLEX;
546
+ rb_io_ascii8bit_binmode(socket);
547
+ rb_io_set_nonblock(fp);
548
+ rb_io_synchronized(fp);
549
+
550
+ rb_yield(socket);
551
+ socket = Qnil;
552
+ }
553
+ }
554
+
555
+ RB_GC_GUARD(socket);
556
+ RB_GC_GUARD(watcher.fiber);
557
+ RB_GC_GUARD(switchpoint_result);
558
+ return Qnil;
559
+ error:
560
+ return rb_funcall(rb_mKernel, ID_raise, 1, switchpoint_result);
561
+ }
562
+
563
+ // VALUE LibevAgent_connect(VALUE self, VALUE sock, VALUE host, VALUE port) {
564
+ // struct LibevAgent_t *agent;
565
+ // struct libev_io watcher;
566
+ // rb_io_t *fptr;
567
+ // struct sockaddr_in addr;
568
+ // char *host_buf = StringValueCStr(host);
569
+ // VALUE switchpoint_result = Qnil;
570
+ // VALUE underlying_sock = rb_iv_get(sock, "@io");
571
+ // if (underlying_sock != Qnil) sock = underlying_sock;
572
+
573
+ // GetLibevAgent(self, agent);
574
+ // GetOpenFile(sock, fptr);
575
+ // rb_io_set_nonblock(fptr);
576
+ // watcher.fiber = Qnil;
577
+
578
+ // addr.sin_family = AF_INET;
579
+ // addr.sin_addr.s_addr = inet_addr(host_buf);
580
+ // addr.sin_port = htons(NUM2INT(port));
581
+
582
+ // while (1) {
583
+ // int result = connect(fptr->fd, &addr, sizeof(addr));
584
+ // if (result < 0) {
585
+ // int e = errno;
586
+ // if ((e != EWOULDBLOCK && e != EAGAIN)) rb_syserr_fail(e, strerror(e));
587
+
588
+ // switchpoint_result = libev_io_wait(agent, &watcher, fptr, EV_WRITE);
589
+ // if (TEST_EXCEPTION(switchpoint_result)) goto error;
590
+ // }
591
+ // else {
592
+ // switchpoint_result = libev_snooze();
593
+ // if (TEST_EXCEPTION(switchpoint_result)) goto error;
594
+
595
+ // return sock;
596
+ // }
597
+ // }
598
+ // RB_GC_GUARD(switchpoint_result);
599
+ // return Qnil;
600
+ // error:
601
+ // return rb_funcall(rb_mKernel, ID_raise, 1, switchpoint_result);
602
+ // }
603
+
604
+ VALUE LibevAgent_wait_io(VALUE self, VALUE io, VALUE write) {
605
+ struct LibevAgent_t *agent;
606
+ struct libev_io watcher;
607
+ rb_io_t *fptr;
608
+ VALUE switchpoint_result = Qnil;
609
+ int events = RTEST(write) ? EV_WRITE : EV_READ;
610
+
611
+ VALUE underlying_io = rb_iv_get(io, "@io");
612
+ GetLibevAgent(self, agent);
613
+ if (underlying_io != Qnil) io = underlying_io;
614
+ GetOpenFile(io, fptr);
615
+
616
+ watcher.fiber = rb_fiber_current();
617
+ ev_io_init(&watcher.io, LibevAgent_io_callback, fptr->fd, events);
618
+ ev_io_start(agent->ev_loop, &watcher.io);
619
+ switchpoint_result = libev_await(agent);
620
+ ev_io_stop(agent->ev_loop, &watcher.io);
621
+
622
+ TEST_RESUME_EXCEPTION(switchpoint_result);
623
+ RB_GC_GUARD(watcher.fiber);
624
+ RB_GC_GUARD(switchpoint_result);
625
+ return switchpoint_result;
626
+ }
627
+
628
+ struct libev_timer {
629
+ struct ev_timer timer;
630
+ VALUE fiber;
631
+ };
632
+
633
+ void LibevAgent_timer_callback(EV_P_ ev_timer *w, int revents)
634
+ {
635
+ struct libev_timer *watcher = (struct libev_timer *)w;
636
+ Fiber_make_runnable(watcher->fiber, Qnil);
637
+ }
638
+
639
+ VALUE LibevAgent_sleep(VALUE self, VALUE duration) {
640
+ struct LibevAgent_t *agent;
641
+ struct libev_timer watcher;
642
+ VALUE switchpoint_result = Qnil;
643
+
644
+ GetLibevAgent(self, agent);
645
+ watcher.fiber = rb_fiber_current();
646
+ ev_timer_init(&watcher.timer, LibevAgent_timer_callback, NUM2DBL(duration), 0.);
647
+ ev_timer_start(agent->ev_loop, &watcher.timer);
648
+
649
+ switchpoint_result = libev_await(agent);
650
+ ev_timer_stop(agent->ev_loop, &watcher.timer);
651
+
652
+ TEST_RESUME_EXCEPTION(switchpoint_result);
653
+ RB_GC_GUARD(watcher.fiber);
654
+ RB_GC_GUARD(switchpoint_result);
655
+ return switchpoint_result;
656
+ }
657
+
658
+ struct libev_child {
659
+ struct ev_child child;
660
+ VALUE fiber;
661
+ };
662
+
663
+ void LibevAgent_child_callback(EV_P_ ev_child *w, int revents)
664
+ {
665
+ struct libev_child *watcher = (struct libev_child *)w;
666
+ int exit_status = w->rstatus >> 8; // weird, why should we do this?
667
+ VALUE status;
668
+
669
+ status = rb_ary_new_from_args(2, INT2NUM(w->rpid), INT2NUM(exit_status));
670
+ Fiber_make_runnable(watcher->fiber, status);
671
+ }
672
+
673
+ VALUE LibevAgent_waitpid(VALUE self, VALUE pid) {
674
+ struct LibevAgent_t *agent;
675
+ struct libev_child watcher;
676
+ VALUE switchpoint_result = Qnil;
677
+ GetLibevAgent(self, agent);
678
+
679
+ watcher.fiber = rb_fiber_current();
680
+ ev_child_init(&watcher.child, LibevAgent_child_callback, NUM2INT(pid), 0);
681
+ ev_child_start(agent->ev_loop, &watcher.child);
682
+
683
+ switchpoint_result = libev_await(agent);
684
+ ev_child_stop(agent->ev_loop, &watcher.child);
685
+
686
+ TEST_RESUME_EXCEPTION(switchpoint_result);
687
+ RB_GC_GUARD(watcher.fiber);
688
+ RB_GC_GUARD(switchpoint_result);
689
+ return switchpoint_result;
690
+ }
691
+
692
+ struct ev_loop *LibevAgent_ev_loop(VALUE self) {
693
+ struct LibevAgent_t *agent;
694
+ GetLibevAgent(self, agent);
695
+ return agent->ev_loop;
696
+ }
697
+
698
+ void Init_LibevAgent() {
699
+ rb_require("socket");
700
+ cTCPSocket = rb_const_get(rb_cObject, rb_intern("TCPSocket"));
701
+
702
+ cLibevAgent = rb_define_class_under(mPolyphony, "LibevAgent", rb_cData);
703
+ rb_define_alloc_func(cLibevAgent, LibevAgent_allocate);
704
+
705
+ rb_define_method(cLibevAgent, "initialize", LibevAgent_initialize, 0);
706
+ rb_define_method(cLibevAgent, "finalize", LibevAgent_finalize, 0);
707
+ rb_define_method(cLibevAgent, "post_fork", LibevAgent_post_fork, 0);
708
+ rb_define_method(cLibevAgent, "pending_count", LibevAgent_pending_count, 0);
709
+
710
+ rb_define_method(cLibevAgent, "ref", LibevAgent_ref, 0);
711
+ rb_define_method(cLibevAgent, "unref", LibevAgent_unref, 0);
712
+
713
+ rb_define_method(cLibevAgent, "poll", LibevAgent_poll, 3);
714
+ rb_define_method(cLibevAgent, "break", LibevAgent_break, 0);
715
+
716
+ rb_define_method(cLibevAgent, "read", LibevAgent_read, 4);
717
+ rb_define_method(cLibevAgent, "read_loop", LibevAgent_read_loop, 1);
718
+ rb_define_method(cLibevAgent, "write", LibevAgent_write, 2);
719
+ rb_define_method(cLibevAgent, "accept", LibevAgent_accept, 1);
720
+ rb_define_method(cLibevAgent, "accept_loop", LibevAgent_accept_loop, 1);
721
+ // rb_define_method(cLibevAgent, "connect", LibevAgent_accept, 3);
722
+ rb_define_method(cLibevAgent, "wait_io", LibevAgent_wait_io, 2);
723
+ rb_define_method(cLibevAgent, "sleep", LibevAgent_sleep, 1);
724
+ rb_define_method(cLibevAgent, "waitpid", LibevAgent_waitpid, 1);
725
+ }