@@ -33,9 +33,9 @@ def run
3333 # Something went wrong
3434 break if rc == -1
3535
36- process_backend if @poller . readables . include? ( @backend_socket )
36+ check_and_process_backend
3737 process_local_queue # Fair ordering so queued requests get in before new requests
38- process_frontend if @poller . readables . include? ( @frontend_socket )
38+ check_and_process_frontend
3939 end
4040 ensure
4141 teardown
@@ -47,6 +47,39 @@ def running?
4747
4848 private
4949
50+ def backend_poll_weight
51+ @backend_poll_weight ||= [ ENV [ "PB_ZMQ_SERVER_BACKEND_POLL_WEIGHT" ] . to_i , 1 ] . max
52+ end
53+
54+ def check_and_process_backend
55+ readables_include_backend = @poller . readables . include? ( @backend_socket )
56+ message_count_read_from_backend = 0
57+
58+ while readables_include_backend && message_count_read_from_backend < backend_poll_weight do
59+ message_count_read_from_backend += 1
60+ process_backend
61+ @poller . poll_nonblock
62+ readables_include_backend = @poller . readables . include? ( @backend_socket )
63+ end
64+ end
65+
66+ def check_and_process_frontend
67+ readables_include_frontend = @poller . readables . include? ( @frontend_socket )
68+ message_count_read_from_frontend = 0
69+
70+ while readables_include_frontend && message_count_read_from_frontend < frontend_poll_weight do
71+ message_count_read_from_frontend += 1
72+ process_frontend
73+ break unless local_queue_available? # no need to read frontend just to throw away messages, will prioritize backend when full
74+ @poller . poll_nonblock
75+ readables_include_frontend = @poller . readables . include? ( @frontend_socket )
76+ end
77+ end
78+
79+ def frontend_poll_weight
80+ @frontend_poll_weight ||= [ ENV [ "PB_ZMQ_SERVER_FRONTEND_POLL_WEIGHT" ] . to_i , 1 ] . max
81+ end
82+
5083 def init_backend_socket
5184 @backend_socket = @zmq_context . socket ( ZMQ ::ROUTER )
5285 zmq_error_check ( @backend_socket . bind ( @server . backend_uri ) )
@@ -79,6 +112,10 @@ def inproc?
79112 !!@server . try ( :inproc? )
80113 end
81114
115+ def local_queue_available?
116+ local_queue . size < local_queue_max_size
117+ end
118+
82119 def local_queue_max_size
83120 @local_queue_max_size ||= [ ENV [ "PB_ZMQ_SERVER_QUEUE_MAX_SIZE" ] . to_i , 5 ] . max
84121 end
@@ -97,7 +134,7 @@ def process_frontend
97134 address , _ , message , *frames = read_from_frontend
98135
99136 if message == ::Protobuf ::Rpc ::Zmq ::CHECK_AVAILABLE_MESSAGE
100- if local_queue . size < local_queue_max_size
137+ if local_queue_available?
101138 write_to_frontend ( [ address , ::Protobuf ::Rpc ::Zmq ::EMPTY_STRING , ::Protobuf ::Rpc ::Zmq ::WORKERS_AVAILABLE ] )
102139 else
103140 write_to_frontend ( [ address , ::Protobuf ::Rpc ::Zmq ::EMPTY_STRING , ::Protobuf ::Rpc ::Zmq ::NO_WORKERS_AVAILABLE ] )
0 commit comments