Class: Raptor::Reactor

Inherits:
Object
  • Object
show all
Defined in:
lib/raptor/reactor.rb,
sig/generated/raptor/reactor.rbs

Overview

Multiplexes client connections, manages connection deadlines, feeds ready bytes to the parser pipeline, and hands completed requests back to the caller-provided handlers.

Defined Under Namespace

Classes: ConnectionIO, Http1IO, Http2IO, TimeoutClient

Constant Summary collapse

CHUNK_SIZE =

Returns:

  • (Object)
64 * 1024
DETACHED_CONNECTION_BUFFER_SIZE =

Returns:

  • (Object)
1024 * 1024
DETACHED_WRITE_BATCH =

Returns:

  • (::Integer)
8
DETACHED_WORKER_BUFFER_SIZE =

Returns:

  • (Object)
16 * 1024 * 1024
TIMEOUT_RESPONSE =

Returns:

  • (::String)
"HTTP/1.1 408 Request Timeout\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"

Instance Method Summary collapse

Constructor Details

#initialize(http1_ractor_pool, http2_ractor_pool, thread_pool, connection_options:, http1_options:, http2_options:) ⇒ Reactor

Creates a new Reactor instance.

Parameters:

  • http1_ractor_pool (RactorPool) —

    ractor pool for HTTP/1.x parsing

  • http2_ractor_pool (RactorPool, nil) —

    ractor pool for HTTP/2 parsing, or nil when no listener supports HTTP/2

  • thread_pool (AtomicThreadPool) —

    thread pool for application processing

  • connection_options (Hash) —

    per-connection timeout configuration

  • http1_options (Hash) —

    HTTP/1.1-specific configuration

  • http2_options (Hash) —

    HTTP/2-specific configuration

  • connection_options: (Hash[Symbol, untyped])
  • http1_options: (Hash[Symbol, untyped])
  • http2_options: (Hash[Symbol, untyped])

Options Hash (connection_options:):

  • :first_data_timeout (Integer) —

    timeout for initial data

  • :chunk_data_timeout (Integer) —

    timeout for subsequent chunks

  • :write_timeout (Integer) —

    timeout for non-blocking writes

Options Hash (http1_options:):

  • :persistent_data_timeout (Integer) —

    timeout for keep-alive idle connections

Options Hash (http2_options:):

  • :keepalive_interval (Integer) —

    idle time before sending a PING

  • :keepalive_timeout (Integer) —

    time to await a PING acknowledgement



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/raptor/reactor.rb', line 247

def initialize(http1_ractor_pool, http2_ractor_pool, thread_pool, connection_options:, http1_options:, http2_options:)
  @http1_ractor_pool = http1_ractor_pool
  @http2_ractor_pool = http2_ractor_pool
  @thread_pool = thread_pool
  @first_data_timeout = connection_options[:first_data_timeout]
  @chunk_data_timeout = connection_options[:chunk_data_timeout]
  @write_timeout = connection_options[:write_timeout]
  @persistent_data_timeout = http1_options[:persistent_data_timeout]
  @http2_keepalive_interval = http2_options[:keepalive_interval]
  @http2_keepalive_timeout = http2_options[:keepalive_timeout]

  @selector = NIO::Selector.new
  @queue = Queue.new
  @io_queue = AtomicQueue.new
  @io_applied = AtomicConditionVariable.new
  @timeouts = RedBlackTree.new

  @id_to_socket = {}
  @socket_to_state = {}
  @id_to_timeout = {}
  @id_to_writer = {}
  @id_to_flow_control = {}
  @id_to_http2_last_stream = {}
  @id_to_http2_drain_stream = {}
  @id_to_http2_keepalive = {}
  @id_to_io = {}
  @detached_budget = DetachedBody::Budget.new(DETACHED_WORKER_BUFFER_SIZE)
  @detached_count = Atom.new(0)
  @detached_drained = AtomicConditionVariable.new
  @thread = nil
end

Instance Method Details

#acknowledge_http2_ping(id, payloads) ⇒ void

This method returns an undefined value.

Records acknowledgements for server keepalive probes.

Parameters:

  • id (Integer) —

    unique connection identifier

  • payloads (Array<String>, nil) —

    acknowledged PING payloads



628
629
630
631
632
633
# File 'lib/raptor/reactor.rb', line 628

def acknowledge_http2_ping(id, payloads)
  keepalive = @id_to_http2_keepalive[id]
  return unless keepalive && payloads&.include?(keepalive[:payload])

  keepalive.delete(:deadline)
end

#add(state) ⇒ void

This method returns an undefined value.

Adds a new client connection to the reactor.

Parameters:

  • state (Hash) —

    client connection state including socket and ID

Options Hash (state):

  • :socket (TCPSocket) —

    the client socket

  • :id (Integer) —

    unique identifier for the client



335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/raptor/reactor.rb', line 335

def add(state)
  socket = state[:socket]
  state.delete(:socket)
  writer = state.delete(:writer)
  flow_control = state.delete(:flow_control)
  @id_to_socket[state[:id]] = socket
  @socket_to_state[socket] = state
  @id_to_writer[state[:id]] = writer if writer
  @id_to_flow_control[state[:id]] = flow_control if flow_control

  read_and_queue_for_parse(socket, state)
end

#attach_http1_body(socket, id, body, state, finished) ⇒ Boolean

Attaches a detached response body to an HTTP/1.x connection.

Parameters:

  • socket (TCPSocket) —

    the client socket

  • id (Integer) —

    unique client identifier

  • body (DetachedBody) —

    the response body

  • state (Hash) —

    connection state restored once the response finishes

  • finished (Proc) —

    called with the close reason

Returns:

  • (Boolean) —

    whether the body was attached



451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/raptor/reactor.rb', line 451

def attach_http1_body(socket, id, body, state, finished)
  attached = AtomicBoolean.new(false)
  @io_queue << [:attach_http1, id, socket, body, attached, finished, state]
  @selector.wakeup rescue nil
  @io_applied.wait { attached.true? }
  return false if body.closed?

  body.open
  true
rescue
  remove_connection(id)
  raise
end

#attach_http1_detached_body(socket, id, body, state, finished) ⇒ void

This method returns an undefined value.

Adds a detached body to an HTTP/1.x connection.

Parameters:

  • socket (TCPSocket) —

    the client socket

  • id (Integer) —

    unique client identifier

  • body (DetachedBody) —

    the response body

  • state (Hash) —

    connection state restored once the response finishes

  • finished (Proc) —

    called with the close reason



801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
# File 'lib/raptor/reactor.rb', line 801

def attach_http1_detached_body(socket, id, body, state, finished)
  io = Http1IO.new(body, state)
  dispatch = proc { |callback| @thread_pool << callback }
  wake = proc do
    @io_queue << [:ready_http1, id]
    @selector.wakeup rescue nil
  end
  unless body.attach([io.budget, @detached_budget], wake, dispatch, finished)
    socket.close rescue nil
    return
  end

  @id_to_socket[id] = socket
  @socket_to_state[socket] = { id: id, protocol: :http1, detached: true }
  @id_to_io[id] = io
  @detached_count.swap { |count| count + 1 }
  update_monitor(id, io)
end

#attach_http2(id:, socket:, state:, writer:, flow_control:, ping_frame:, ping_payload:) ⇒ void

This method returns an undefined value.

Stores an HTTP/2 connection's socket, state, writer, and flow controller in the reactor's per-connection maps.

Parameters:

  • id (Integer) —

    unique client identifier

  • socket (TCPSocket) —

    the connection socket

  • state (Hash) —

    initial connection state

  • writer (Http2::Writer) —

    per-connection frame writer

  • flow_control (Http2::FlowControl) —

    per-connection outbound flow controller

  • ping_frame (String) —

    serialized PING frame for keepalive probes

  • ping_payload (String) —

    payload expected in the corresponding acknowledgement

  • id: (Integer)
  • socket: (TCPSocket)
  • state: (Hash[Symbol, untyped])
  • writer: (Object)
  • flow_control: (Object)
  • ping_frame: (String)
  • ping_payload: (String)


608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/raptor/reactor.rb', line 608

def attach_http2(id:, socket:, state:, writer:, flow_control:, ping_frame:, ping_payload:)
  @id_to_socket[id] = socket
  @socket_to_state[socket] = state
  @id_to_writer[id] = writer
  @id_to_flow_control[id] = flow_control
  @id_to_http2_last_stream[id] = 0
  @id_to_io[id] = Http2IO.new
  writer.attach(self, id)
  if @http2_keepalive_interval.positive?
    @id_to_http2_keepalive[id] = { frame: ping_frame, payload: ping_payload }
  end
end

#attach_http2_body(id, stream_id, body, finished) ⇒ Boolean

Attaches a detached response body to an HTTP/2 stream.

Parameters:

  • id (Integer) —

    unique connection identifier

  • stream_id (Integer) —

    HTTP/2 stream identifier

  • body (DetachedBody) —

    the response body

  • finished (Proc) —

    called with the close reason

Returns:

  • (Boolean) —

    whether the body was attached



532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/raptor/reactor.rb', line 532

def attach_http2_body(id, stream_id, body, finished)
  attached = AtomicBoolean.new(false)
  @io_queue << [:attach_http2, id, stream_id, body, attached, finished]
  @selector.wakeup rescue nil
  @io_applied.wait { attached.true? }
  return false if body.closed?

  body.open
  true
rescue
  cancel_http2_body(id, stream_id)
  raise
end

#attach_http2_detached_body(id, stream_id, body, finished) ⇒ void

This method returns an undefined value.

Adds a detached body to an HTTP/2 stream.

Parameters:

  • id (Integer) —

    unique connection identifier

  • stream_id (Integer) —

    HTTP/2 stream identifier

  • body (DetachedBody) —

    the response body

  • finished (Proc) —

    called with the close reason



922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
# File 'lib/raptor/reactor.rb', line 922

def attach_http2_detached_body(id, stream_id, body, finished)
  io = @id_to_io[id]
  dispatch = proc { |callback| @thread_pool << callback }
  unless io
    body.attach([], proc {}, dispatch, finished)
    body.finish(:connection_closed)
    return
  end

  wake = proc do
    @io_queue << [:ready_http2, id, stream_id]
    @selector.wakeup rescue nil
  end
  return unless body.attach([io.budget, @detached_budget], wake, dispatch, finished)

  io.detached[stream_id] = body
  @detached_count.swap { |count| count + 1 }
end

#backlog ⇒ Integer

Returns the number of complete requests either being processed or awaiting processing.

Returns:

  • (Integer) —

    number of complete requests



697
698
699
# File 'lib/raptor/reactor.rb', line 697

def backlog
  @thread_pool.queue_size + @thread_pool.active_count
end

#cancel_detached_bodies ⇒ void

This method returns an undefined value.

Cancels every detached response during worker shutdown.



1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
# File 'lib/raptor/reactor.rb', line 1062

def cancel_detached_bodies
  @id_to_io.to_a.each do |id, io|
    if io.is_a?(Http1IO)
      remove_http1_detached_body(id, :shutdown)
    else
      io.detached.each_key.to_a.each do |stream_id|
        remove_http2_detached_body(id, stream_id, :shutdown)
      end
    end
  end
end

#cancel_http2_body(id, stream_id) ⇒ void

This method returns an undefined value.

Cancels a detached response stream.

Parameters:

  • id (Integer) —

    unique connection identifier

  • stream_id (Integer) —

    HTTP/2 stream identifier



566
567
568
569
570
571
# File 'lib/raptor/reactor.rb', line 566

def cancel_http2_body(id, stream_id)
  return if @detached_count.value.zero?

  @io_queue << [:cancel_http2, id, stream_id]
  @selector.wakeup rescue nil
end

#cleanup(socket) ⇒ void

This method returns an undefined value.

Cleans up a client connection by removing it from tracking and closing the socket.

Parameters:

  • socket (TCPSocket) —

    the socket to clean up



1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
# File 'lib/raptor/reactor.rb', line 1471

def cleanup(socket)
  state = @socket_to_state.delete(socket)
  io = @id_to_io.delete(state[:id])
  deregister(socket, io)
  @id_to_socket.delete(state[:id])
  @id_to_writer.delete(state[:id])
  @id_to_flow_control.delete(state[:id])&.close
  @id_to_http2_last_stream.delete(state[:id])
  @id_to_http2_drain_stream.delete(state[:id])
  @id_to_http2_keepalive.delete(state[:id])
  if io.is_a?(Http1IO)
    if io.body
      io.body.finish(:connection_closed)
      io.body = nil
      detached_body_removed
    end
  elsif io
    io.detached.each_value do |body|
      body.finish(:connection_closed)
      detached_body_removed
    end
  end
  client = @id_to_timeout.delete(state[:id])
  @timeouts.delete!(client) if client
  clear_write_timeout(io)
  socket.close rescue nil
end

#clear_write_timeout(io) ⇒ void

This method returns an undefined value.

Removes one connection's non-blocking write deadline.

Parameters:



1247
1248
1249
1250
1251
# File 'lib/raptor/reactor.rb', line 1247

def clear_write_timeout(io)
  client = io&.timeout
  @timeouts.delete!(client) if client
  io.timeout = nil if io
end

#close_after_writes(id) ⇒ void

This method returns an undefined value.

Closes a connection once its queued frames are written.

Parameters:

  • id (Integer) —

    unique client identifier



1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
# File 'lib/raptor/reactor.rb', line 1094

def close_after_writes(id)
  io = @id_to_io[id]
  return unless io

  if io.empty?
    remove_connection(id)
  else
    io.closing = true
  end
end

#close_connection(id) ⇒ void

This method returns an undefined value.

Closes a connection after writing any frames already queued for it.

Parameters:

  • id (Integer) —

    unique client identifier



675
676
677
678
# File 'lib/raptor/reactor.rb', line 675

def close_connection(id)
  @io_queue << [:close, id]
  @selector.wakeup rescue nil
end

#complete?(state) ⇒ Boolean

Returns true when the request has been fully parsed.

Parameters:

  • state (Hash) —

    connection state

Returns:

  • (Boolean) —

    true if the request is complete



1505
1506
1507
# File 'lib/raptor/reactor.rb', line 1505

def complete?(state)
  state[:complete]
end

#deregister(socket, io) ⇒ void

This method returns an undefined value.

Removes a socket from selector tracking.

Parameters:

  • socket (TCPSocket) —

    socket to deregister

  • io (ConnectionIO, nil) —

    connection I/O state



1260
1261
1262
1263
1264
1265
1266
# File 'lib/raptor/reactor.rb', line 1260

def deregister(socket, io)
  return unless io&.monitor || @selector.registered?(socket)

  @selector.deregister(socket)
  io.monitor = nil if io
rescue IOError
end

#detached_body_removed ⇒ void

This method returns an undefined value.

Records one detached stream finishing.



1079
1080
1081
1082
1083
1084
1085
1086
# File 'lib/raptor/reactor.rb', line 1079

def detached_body_removed
  remaining = nil
  @detached_count.swap do |count|
    remaining = count - 1
    remaining
  end
  @detached_drained.broadcast if remaining.zero?
end

#dispatch_http2_stream(id, stream_id) ⇒ Boolean

Records an HTTP/2 stream before application dispatch, rejecting streams that arrived after graceful draining began.

Parameters:

  • id (Integer) —

    unique connection identifier

  • stream_id (Integer) —

    HTTP/2 stream identifier

Returns:

  • (Boolean) —

    whether the stream may be dispatched



473
474
475
476
477
478
479
480
481
# File 'lib/raptor/reactor.rb', line 473

def dispatch_http2_stream(id, stream_id)
  if (last_stream = @id_to_http2_drain_stream[id])
    return stream_id <= last_stream
  end

  current = @id_to_http2_last_stream[id] || 0
  @id_to_http2_last_stream[id] = stream_id if stream_id > current
  true
end

#drain_detached_bodies(timeout) ⇒ void

This method returns an undefined value.

Waits for detached responses to finish, then cancels any that outlive the worker drain period.

Parameters:

  • timeout (Numeric) —

    seconds to wait before cancelling open bodies



580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/raptor/reactor.rb', line 580

def drain_detached_bodies(timeout)
  barrier = AtomicBoolean.new(false)
  @io_queue << [:barrier, nil, barrier]
  @selector.wakeup rescue nil
  @io_applied.wait { barrier.true? }

  Timeout.timeout(timeout) do
    @detached_drained.wait { @detached_count.value.zero? }
  end
rescue Timeout::Error
  @io_queue << [:cancel_all]
  @selector.wakeup rescue nil
  @detached_drained.wait { @detached_count.value.zero? }
end

#drain_http2 {|stream_id| ... } ⇒ void

This method returns an undefined value.

Sends GOAWAY on every HTTP/2 connection and fixes the last stream each connection may dispatch while existing application work drains.

Yields:

Yield Parameters:

  • stream_id (Integer) —

    last dispatched stream identifier

Yield Returns:

  • (String) —

    serialized GOAWAY frame



491
492
493
494
495
496
497
498
499
# File 'lib/raptor/reactor.rb', line 491

def drain_http2
  @id_to_flow_control.each_key do |id|
    last_stream = @id_to_http2_last_stream[id] || 0
    @id_to_http2_drain_stream[id] = last_stream
    writer = @id_to_writer[id]
    socket = @id_to_socket[id]
    writer.write_frames(socket, [yield(last_stream)]) if writer && socket
  end
end

#drain_io_queue ⇒ void

This method returns an undefined value.

Applies queued reactor-owned I/O operations.



738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
# File 'lib/raptor/reactor.rb', line 738

def drain_io_queue
  connections = {}
  while (operation = @io_queue.pop)
    type, id, value, body, attached, finished, state = operation
    case type
    when :write
      data = value
      queue_output(@id_to_io[id], data)
      connections[id] = true
    when :close
      close_after_writes(id)
    when :attach_http2
      begin
        attach_http2_detached_body(id, value, body, finished)
      ensure
        attached.make_true
        @io_applied.broadcast
      end
      connections[id] = true
    when :attach_http1
      begin
        attach_http1_detached_body(value, id, body, state, finished)
      ensure
        attached.make_true
        @io_applied.broadcast
      end
    when :ready_http1
      flush_http1_detached_body(id)
    when :ready_http2
      mark_http2_detached_body_ready(id, value)
      connections[id] = true
    when :flush_http2
      connections[id] = true
    when :resume_http2
      resume_http2_detached_bodies(id)
      connections[id] = true
    when :cancel_http2
      remove_http2_detached_body(id, value, :cancelled)
    when :cancel_all
      cancel_detached_bodies
    when :barrier
      value.make_true
      @io_applied.broadcast
    end
  end

  connections.each_key do |id|
    io = @id_to_io[id]
    flush_output(id, io) if io && !io.wait
    flush_http2_detached_bodies(id) if io.is_a?(Http2IO) && !io.wait && !io.detached.empty?
  end
end

#expire_timeouts(now) ⇒ void

This method returns an undefined value.

Handles every expired connection deadline in order.

Parameters:

  • now (Float) —

    current monotonic timestamp



719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/raptor/reactor.rb', line 719

def expire_timeouts(now)
  while (client = @timeouts.min) && client.timeout(now).zero?
    @timeouts.delete!(client)
    id = client.client_data[:id]
    if client.client_data[:write]
      @id_to_io[id]&.timeout = nil
      remove_connection(id)
    else
      @id_to_timeout.delete(id)
      handle_timeout(client, now)
    end
  end
end

#finish_http1_detached_body(id, io) ⇒ void

This method returns an undefined value.

Finishes an HTTP/1.x detached response and either reuses or closes its connection.

Parameters:

  • id (Integer) —

    unique client identifier

  • io (Http1IO) —

    connection I/O state



860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
# File 'lib/raptor/reactor.rb', line 860

def finish_http1_detached_body(id, io)
  socket = @id_to_socket[id]
  return unless socket

  body = io.body
  io.body = nil
  body.finish(:closed)
  detached_body_removed
  @id_to_io.delete(id)
  deregister(socket, io)
  clear_write_timeout(io)

  if io.state[:keep_alive]
    state = {
      id: id,
      request_count: io.state[:request_count],
      remote_addr: io.state[:remote_addr],
      url_scheme: io.state[:url_scheme],
      persisted: true
    }
    unless io.input.empty?
      state[:buffer] = io.input
      @socket_to_state[socket] = state
      @http1_ractor_pool << Ractor.make_shareable(state)
      return
    end

    persist(socket, id, io.state[:request_count], remote_addr: io.state[:remote_addr], url_scheme: io.state[:url_scheme])
  else
    @socket_to_state.delete(socket)
    @id_to_socket.delete(id)
    socket.close rescue nil
  end
end

#finish_http2_detached_body(id, stream_id, body) ⇒ void

This method returns an undefined value.

Finishes an HTTP/2 detached stream with DATA or trailing HEADERS.

Parameters:

  • id (Integer) —

    unique connection identifier

  • stream_id (Integer) —

    HTTP/2 stream identifier

  • body (DetachedBody) —

    the response body



1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/raptor/reactor.rb', line 1025

def finish_http2_detached_body(id, stream_id, body)
  parser = Http2Parser.new
  frame = if body.trailers.empty?
    parser.build_frame(:data, Http2::FLAG_END_STREAM, stream_id, nil)
  else
    encoded = parser.encode_response_trailers(body.trailers)
    parser.build_frame(:headers, Http2::FLAG_END_STREAM | Http2::FLAG_END_HEADERS, stream_id, encoded)
  end
  io = @id_to_io[id]
  queue_output(io, frame)
  flush_output(id, io)
  remove_http2_detached_body(id, stream_id, :closed)
end

#first_data_received?(state) ⇒ Boolean

Checks if any data has been received for this connection.

Parameters:

  • state (Hash) —

    connection state

Returns:

  • (Boolean) —

    true if first data has been received



1515
1516
1517
# File 'lib/raptor/reactor.rb', line 1515

def first_data_received?(state)
  complete?(state) || (state.dig(:parse_data, :parse_count) || 0) >= 1
end

#flow_control_for(id) ⇒ Object?

Returns the flow controller associated with a given connection, if one was supplied when the connection was added.

Parameters:

  • id (Integer) —

    unique client identifier

Returns:

  • (Object, nil) —

    the flow controller, if found



437
438
439
# File 'lib/raptor/reactor.rb', line 437

def flow_control_for(id)
  @id_to_flow_control[id]
end

#flush_http1_detached_body(id) ⇒ void

This method returns an undefined value.

Writes buffered HTTP/1.x body chunks without blocking.

Parameters:

  • id (Integer) —

    unique client identifier



826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
# File 'lib/raptor/reactor.rb', line 826

def flush_http1_detached_body(id)
  io = @id_to_io[id]
  return unless io.is_a?(Http1IO) && !io.wait && io.output.empty?

  DETACHED_WRITE_BATCH.times do
    size = io.body&.next_size
    break unless size

    if size.zero?
      queue_output(io, Http1.encode_trailers(io.body.trailers)) if io.state[:chunked]
      io.finishing = true
      flush_output(id, io)
      break
    end

    chunk = io.body.shift(size)
    queue_output(io, io.state[:chunked] ? Http1.encode_chunk(chunk) : chunk)
    flush_output(id, io)
    break if io.wait
  end

  if !io.finishing && !io.wait && io.body&.next_size
    @io_queue << [:ready_http1, id]
    @selector.wakeup rescue nil
  end
end

#flush_http2_detached_bodies(id) ⇒ void

This method returns an undefined value.

Writes HTTP/2 detached streams in round-robin order without waiting for flow control.

Parameters:

  • id (Integer) —

    unique connection identifier



975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
# File 'lib/raptor/reactor.rb', line 975

def flush_http2_detached_bodies(id)
  io = @id_to_io[id]
  flow_control = @id_to_flow_control[id]
  socket = @id_to_socket[id]
  return unless io && flow_control && socket

  DETACHED_WRITE_BATCH.times do
    break if io.wait || !io.output.empty?

    stream_id = io.ready.shift
    break unless stream_id

    io.ready_streams.delete(stream_id)
    body = io.detached[stream_id]
    next unless body

    size = body.next_size
    next unless size

    if size.zero?
      finish_http2_detached_body(id, stream_id, body)
      next
    end

    granted = flow_control.try_acquire(stream_id, size)
    next if granted.zero?

    chunk = body.shift(granted)
    parser = Http2Parser.new
    queue_output(io, parser.build_frame(:data, 0, stream_id, chunk))
    flush_output(id, io)
    mark_http2_detached_body_ready(id, stream_id) if body.next_size
  rescue Http2::StreamClosedError
    remove_http2_detached_body(id, stream_id, :cancelled)
  end

  if !io.wait && io.output.empty? && !io.ready.empty?
    @io_queue << [:flush_http2, id]
    @selector.wakeup rescue nil
  end
end

#flush_output(id, io) ⇒ void

This method returns an undefined value.

Drains one connection's queued response bytes without blocking.

Parameters:

  • id (Integer) —

    unique connection identifier

  • io (ConnectionIO) —

    connection I/O state



1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
# File 'lib/raptor/reactor.rb', line 1140

def flush_output(id, io)
  socket = @id_to_socket[id]
  return unless socket && io

  while (data = io.output.first)
    chunk = io.offset.zero? ? data : data.byteslice(io.offset..-1)

    begin
      written = socket.write_nonblock(chunk)
    rescue IO::WaitReadable
      wait_for_write(id, io, :read)
      return
    rescue IO::WaitWritable
      wait_for_write(id, io, :write)
      return
    rescue IOError, SystemCallError, OpenSSL::SSL::SSLError
      remove_connection(id)
      return
    end

    if written.zero?
      wait_for_write(id, io, :write)
      return
    end

    clear_write_timeout(io)
    io.offset += written
    if io.offset == data.bytesize
      io.output.shift
      io.offset = 0
    end
  end

  io.wait = nil
  if io.is_a?(Http1IO) && io.finishing
    finish_http1_detached_body(id, io)
  elsif io.closing
    remove_connection(id)
  else
    update_monitor(id, io)
  end
end

#handle_http1_detached_monitor(monitor, id) ⇒ void

This method returns an undefined value.

Handles readiness for an HTTP/1.x detached response.

Parameters:

  • monitor (NIO::Monitor) —

    ready selector monitor

  • id (Integer) —

    unique client identifier



1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
# File 'lib/raptor/reactor.rb', line 1394

def handle_http1_detached_monitor(monitor, id)
  socket = monitor.value
  io = @id_to_io[id]
  return unless io.is_a?(Http1IO)

  wait = io.wait
  if (wait == :read && monitor.readable?) || (wait == :write && monitor.writable?)
    flush_output(id, io)
    return unless @id_to_io.key?(id)

    flush_http1_detached_body(id) unless io.wait
  end

  return unless io.reading && monitor.readable?

  io.input << socket.read_nonblock(CHUNK_SIZE)
  io.reading = false
  update_monitor(id, io)
rescue IO::WaitReadable
rescue IO::WaitWritable
  wait_for_write(id, io, :write)
rescue EOFError, IOError, SystemCallError, OpenSSL::SSL::SSLError
  remove_connection(id)
end

#handle_monitor(monitor) ⇒ void

This method returns an undefined value.

Dispatches readable and writable events without allowing application threads to take ownership of HTTP/2 sockets.

Parameters:

  • monitor (NIO::Monitor) —

    ready selector monitor



1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
# File 'lib/raptor/reactor.rb', line 1351

def handle_monitor(monitor)
  socket = monitor.value
  state = @socket_to_state[socket]
  return unless state

  if state[:detached]
    handle_http1_detached_monitor(monitor, state[:id])
    return
  end

  unless state[:protocol] == :http2
    wakeup!(socket)
    return
  end

  id = state[:id]
  io = @id_to_io[id]
  return unless io

  wait = io.wait
  if (wait == :read && monitor.readable?) || (wait == :write && monitor.writable?)
    flush_output(id, io)
    return unless @id_to_socket.key?(id)
    return if io.wait == :read
    flush_http2_detached_bodies(id) unless io.detached.empty?
  end

  return unless io.reading && monitor.readable?

  io.reading = false
  update_monitor(id, io)
  to_client = @id_to_timeout.delete(id)
  @timeouts.delete!(to_client) if to_client
  read_and_queue_for_parse(socket, state)
end

#handle_timeout(client, now) ⇒ void

This method returns an undefined value.

Handles an expired connection deadline, sending an HTTP/2 keepalive probe before closing the connection when its acknowledgement is late.

Parameters:

  • client (TimeoutClient) —

    expired client

  • now (Float) —

    current monotonic timestamp



1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
# File 'lib/raptor/reactor.rb', line 1326

def handle_timeout(client, now)
  state = client.client_data
  id = state[:id]
  socket = @id_to_socket[id]
  return unless socket

  keepalive = @id_to_http2_keepalive[id] if state[:http2_preface_received]
  if keepalive && !keepalive[:deadline]
    keepalive[:deadline] = now + @http2_keepalive_timeout
    @id_to_writer[id].write_frames(socket, [keepalive[:frame]])
    track_timeout(state, keepalive[:deadline])
    return
  end

  socket.write(TIMEOUT_RESPONSE) rescue nil unless state[:protocol] == :http2
  cleanup(socket)
end

#mark_http2_detached_body_ready(id, stream_id) ⇒ void

This method returns an undefined value.

Marks an HTTP/2 detached stream eligible for fair scheduling.

Parameters:

  • id (Integer) —

    unique connection identifier

  • stream_id (Integer) —

    HTTP/2 stream identifier



948
949
950
951
952
953
954
# File 'lib/raptor/reactor.rb', line 948

def mark_http2_detached_body_ready(id, stream_id)
  io = @id_to_io[id]
  return unless io&.detached&.key?(stream_id) && !io.ready_streams.key?(stream_id)

  io.ready << stream_id
  io.ready_streams[stream_id] = true
end

#persist(socket, id, request_count, remote_addr:, url_scheme:) ⇒ void

This method returns an undefined value.

Re-registers a kept-alive connection for the next request cycle under the persistent-data timeout.

Parameters:

  • socket (TCPSocket) —

    the kept-alive client socket

  • id (Integer) —

    the unique client identifier

  • request_count (Integer) —

    number of requests handled on this connection

  • remote_addr (String) —

    the client's remote IP address

  • url_scheme (String) —

    "http" or "https"

  • remote_addr: (String)
  • url_scheme: (String)


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/raptor/reactor.rb', line 392

def persist(socket, id, request_count, remote_addr:, url_scheme:)
  state = {
    id: id,
    request_count: request_count,
    remote_addr: remote_addr,
    url_scheme: url_scheme,
    persisted: true
  }

  @id_to_socket[id] = socket
  @socket_to_state[socket] = state
  @queue << socket
  @selector.wakeup
rescue ClosedQueueError
  socket.close
end

#queue_output(io, data) ⇒ void

This method returns an undefined value.

Adds bytes to one connection and writes as much as the socket accepts.

Parameters:

  • io (ConnectionIO) —

    connection I/O state

  • data (String) —

    serialized response bytes



1123
1124
1125
1126
1127
1128
1129
1130
1131
# File 'lib/raptor/reactor.rb', line 1123

def queue_output(io, data)
  return unless io && !io.closing

  if io.output.empty?
    io.output << data
  else
    io.output[-1] << data
  end
end

#read_and_queue_for_parse(socket, state) ⇒ Hash?

Reads data from a socket and either queues it for parsing or returns it to the selector.

Parameters:

  • socket (TCPSocket) —

    the socket to read from and queue

  • state (Hash) —

    current connection state

Returns:

  • (Hash, nil) —

    updated state, if successful



1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
# File 'lib/raptor/reactor.rb', line 1441

def read_and_queue_for_parse(socket, state)
  data = begin
    socket.read_nonblock(CHUNK_SIZE)
  rescue IO::WaitReadable
    @queue << socket
    @selector.wakeup
    return
  rescue EOFError, IOError, SystemCallError, OpenSSL::SSL::SSLError
    cleanup(socket)
    return
  end

  buffer = state[:buffer] ? state[:buffer].dup : String.new
  buffer << data

  while socket.respond_to?(:pending) && socket.pending.positive?
    buffer << socket.read_nonblock(socket.pending)
  end

  state = state.frozen? ? state.merge(buffer: buffer) : state.merge!(buffer: buffer)
  pool = state[:protocol] == :http2 ? @http2_ractor_pool : @http1_ractor_pool
  pool << Ractor.make_shareable(state)
end

#register(socket) ⇒ void

This method returns an undefined value.

Registers a socket with the NIO selector and sets up timeout tracking.

Parameters:

  • socket (TCPSocket) —

    the socket to register



1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
# File 'lib/raptor/reactor.rb', line 1274

def register(socket)
  state = @socket_to_state[socket]
  return unless state

  if state[:protocol] == :http2
    io = @id_to_io[state[:id]]
    io.reading = true
    update_monitor(state[:id], io)
  else
    @selector.register(socket, :r).value = socket
  end

  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  timeout_at = if state[:protocol] == :http2
    if state[:http2_preface_received]
      keepalive = @id_to_http2_keepalive[state[:id]]
      keepalive && (keepalive[:deadline] || now + @http2_keepalive_interval)
    else
      now + @first_data_timeout
    end
  elsif state[:persisted]
    now + @persistent_data_timeout
  elsif first_data_received?(state)
    now + @chunk_data_timeout
  else
    now + @first_data_timeout
  end
  track_timeout(state, timeout_at) if timeout_at
end

#remove(id) ⇒ TCPSocket?

Drops the reactor's references to a client whose parsed request has been handed off to the thread pool. The socket itself is kept open so the worker can write the response.

Parameters:

  • id (Integer) —

    unique client identifier

Returns:

  • (TCPSocket, nil) —

    the socket associated with id, if any



375
376
377
378
379
# File 'lib/raptor/reactor.rb', line 375

def remove(id)
  @id_to_socket.delete(id).tap do |socket|
    @socket_to_state.delete(socket)
  end
end

#remove_connection(id) ⇒ void

This method returns an undefined value.

Immediately closes a connection and drops its reactor state.

Parameters:

  • id (Integer) —

    unique client identifier



1111
1112
1113
1114
# File 'lib/raptor/reactor.rb', line 1111

def remove_connection(id)
  socket = @id_to_socket[id]
  cleanup(socket) if socket
end

#remove_http1_detached_body(id, reason) ⇒ void

This method returns an undefined value.

Cancels an HTTP/1.x detached response and closes its connection.

Parameters:

  • id (Integer) —

    unique client identifier

  • reason (Symbol) —

    why the response closed



902
903
904
905
906
907
908
909
910
911
# File 'lib/raptor/reactor.rb', line 902

def remove_http1_detached_body(id, reason)
  io = @id_to_io[id]
  return unless io.is_a?(Http1IO) && io.body

  body = io.body
  io.body = nil
  body.finish(reason)
  detached_body_removed
  remove_connection(id)
end

#remove_http2_detached_body(id, stream_id, reason) ⇒ void

This method returns an undefined value.

Removes an HTTP/2 detached stream and schedules its close callback.

Parameters:

  • id (Integer) —

    unique connection identifier

  • stream_id (Integer) —

    HTTP/2 stream identifier

  • reason (Symbol) —

    why the stream closed



1047
1048
1049
1050
1051
1052
1053
1054
1055
# File 'lib/raptor/reactor.rb', line 1047

def remove_http2_detached_body(id, stream_id, reason)
  io = @id_to_io[id]
  body = io&.detached&.delete(stream_id)
  return unless body

  io.ready_streams.delete(stream_id)
  body.finish(reason)
  detached_body_removed
end

#resume_http2_bodies(id) ⇒ void

This method returns an undefined value.

Reconsiders detached streams after an outbound window update.

Parameters:

  • id (Integer) —

    unique connection identifier



552
553
554
555
556
557
# File 'lib/raptor/reactor.rb', line 552

def resume_http2_bodies(id)
  return if @detached_count.value.zero?

  @io_queue << [:resume_http2, id]
  @selector.wakeup rescue nil
end

#resume_http2_detached_bodies(id) ⇒ void

This method returns an undefined value.

Marks every HTTP/2 detached stream eligible after flow-control capacity changes.

Parameters:

  • id (Integer) —

    unique connection identifier



962
963
964
965
966
967
# File 'lib/raptor/reactor.rb', line 962

def resume_http2_detached_bodies(id)
  io = @id_to_io[id]
  return unless io

  io.detached.each_key { |stream_id| mark_http2_detached_body_ready(id, stream_id) }
end

#run ⇒ Thread

Starts the reactor's main event loop in a new thread. Runs until shutdown work and pending writes are drained.

Returns:

  • (Thread) —

    the thread running the reactor event loop



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/raptor/reactor.rb', line 285

def run
  Thread.new do
    Thread.current.name = "Reactor"
    @thread = Thread.current

    until stopped?
      begin
        now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
        timeout = @timeouts.min&.timeout(now)
        @selector.select(timeout) do |monitor|
          handle_monitor(monitor)
        end

        now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
        expire_timeouts(now)
        drain_io_queue

        until @queue.empty?
          register(@queue.pop)
        end
      rescue => error
        Log.rescued_error(error)
      end
    end

    @id_to_flow_control.each_value(&:close)
    @id_to_socket.each_value { |socket| socket.close rescue nil }
    @id_to_socket.clear
    @socket_to_state.clear
    @id_to_timeout.clear
    @id_to_writer.clear
    @id_to_flow_control.clear
    @id_to_http2_last_stream.clear
    @id_to_http2_drain_stream.clear
    @id_to_http2_keepalive.clear
    @id_to_io.clear
    @timeouts.clear!
    @thread = nil
    @selector.close
  end
end

#shutdown ⇒ void

This method returns an undefined value.

Closes the registration queue and wakes the selector so the event loop drains pending work and exits.



686
687
688
689
# File 'lib/raptor/reactor.rb', line 686

def shutdown
  @queue.close
  @selector.wakeup
end

#socket_for(id) ⇒ TCPSocket?

Returns the socket for a given client identifier without removing it.

Parameters:

  • id (Integer) —

    unique client identifier

Returns:

  • (TCPSocket, nil) —

    the socket, if found



415
416
417
# File 'lib/raptor/reactor.rb', line 415

def socket_for(id)
  @id_to_socket[id]
end

#stopped? ⇒ Boolean

Returns whether shutdown has no registrations or writes left to drain.

Returns:

  • (Boolean)


708
709
710
711
# File 'lib/raptor/reactor.rb', line 708

def stopped?
  @queue.closed? && @queue.empty? && @io_queue.empty? &&
    @id_to_io.each_value.all?(&:empty?)
end

#track_timeout(state, timeout_at) ⇒ void

This method returns an undefined value.

Adds a connection deadline to the timeout tree.

Parameters:

  • state (Hash) —

    client connection state

  • timeout_at (Float) —

    absolute monotonic expiry time



1311
1312
1313
1314
1315
1316
# File 'lib/raptor/reactor.rb', line 1311

def track_timeout(state, timeout_at)
  client = TimeoutClient.new(state)
  client.timeout_at = timeout_at
  @timeouts << client
  @id_to_timeout[state[:id]] = client
end

#track_write_timeout(id, io) ⇒ void

This method returns an undefined value.

Starts or refreshes one connection's non-blocking write deadline.

Parameters:

  • id (Integer) —

    unique connection identifier

  • io (ConnectionIO) —

    connection I/O state



1233
1234
1235
1236
1237
1238
1239
# File 'lib/raptor/reactor.rb', line 1233

def track_write_timeout(id, io)
  clear_write_timeout(io)
  client = TimeoutClient.new({ id: id, write: true })
  client.timeout_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) + @write_timeout
  @timeouts << client
  io.timeout = client
end

#update_http2_state(state) ⇒ void

This method returns an undefined value.

Updates connection state for an HTTP/2 connection and re-registers the socket for further reads.

Parameters:

  • state (Hash) —

    updated connection state from the ractor pool



658
659
660
661
662
663
664
665
666
667
# File 'lib/raptor/reactor.rb', line 658

def update_http2_state(state)
  socket = @id_to_socket[state[:id]]
  return unless socket

  @socket_to_state[socket] = state
  @queue << socket
  @selector.wakeup
rescue ClosedQueueError
  socket.close
end

#update_monitor(id, io) ⇒ void

This method returns an undefined value.

Updates selector interest for one reactor-owned connection.

Parameters:

  • id (Integer) —

    unique connection identifier

  • io (ConnectionIO) —

    connection I/O state



1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
# File 'lib/raptor/reactor.rb', line 1204

def update_monitor(id, io)
  socket = @id_to_socket[id]
  return unless socket && io

  read = io.reading || io.wait == :read
  write = io.wait == :write
  interests = if read && write
    :rw
  elsif read
    :r
  elsif write
    :w
  end

  if io.monitor
    io.monitor.interests = interests
  elsif interests
    io.monitor = @selector.register(socket, interests)
    io.monitor.value = socket
  end
end

#update_state(state) ⇒ void

This method returns an undefined value.

Updates the state of an existing client connection and re-registers it for further I/O.

Parameters:

  • state (Hash) —

    updated client connection state

Options Hash (state):

  • :id (Integer) —

    client identifier



356
357
358
359
360
361
362
363
364
365
# File 'lib/raptor/reactor.rb', line 356

def update_state(state)
  socket = @id_to_socket[state[:id]]
  return unless socket

  @socket_to_state[socket] = state
  @queue << socket
  @selector.wakeup
rescue ClosedQueueError
  socket.close
end

#wait_for_write(id, io, readiness) ⇒ void

This method returns an undefined value.

Registers the readiness needed to continue a partial socket write.

Parameters:

  • id (Integer) —

    unique connection identifier

  • io (ConnectionIO) —

    connection I/O state

  • readiness (Symbol) —

    :read or :write



1191
1192
1193
1194
1195
# File 'lib/raptor/reactor.rb', line 1191

def wait_for_write(id, io, readiness)
  io.wait = readiness
  track_write_timeout(id, io)
  update_monitor(id, io)
end

#wakeup!(socket) ⇒ void

This method returns an undefined value.

Handles socket wakeup by deregistering and queuing for processing.

Parameters:

  • socket (TCPSocket) —

    the socket that became ready



1425
1426
1427
1428
1429
1430
1431
# File 'lib/raptor/reactor.rb', line 1425

def wakeup!(socket)
  @selector.deregister(socket)
  state = @socket_to_state[socket]
  to_client = @id_to_timeout.delete(state[:id])
  @timeouts.delete!(to_client) if to_client
  read_and_queue_for_parse(socket, state)
end

#watch(id) ⇒ void

This method returns an undefined value.

Registers an attached socket for future reactor-driven reads.

Parameters:

  • id (Integer) —

    unique client identifier



641
642
643
644
645
646
647
648
649
# File 'lib/raptor/reactor.rb', line 641

def watch(id)
  socket = @id_to_socket[id]
  return unless socket

  @queue << socket
  @selector.wakeup
rescue ClosedQueueError
  socket.close
end

#write_http2_frames(id, frames) ⇒ void

This method returns an undefined value.

Queues serialized HTTP/2 frames for a connection. Producers never write to the socket or wait for it to become writable.

Parameters:

  • id (Integer) —

    unique connection identifier

  • frames (Array<String>) —

    frame bytes to write in order



509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/raptor/reactor.rb', line 509

def write_http2_frames(id, frames)
  data = frames.join
  return if data.empty?

  if Thread.current.equal?(@thread)
    io = @id_to_io[id]
    queue_output(io, data)
    flush_output(id, io) if io && !io.wait
  else
    @io_queue << [:write, id, data]
    @selector.wakeup rescue nil
  end
end

#writer_for(id) ⇒ Object?

Returns the writer object associated with a given connection, if one was supplied when the connection was added.

Parameters:

  • id (Integer) —

    unique client identifier

Returns:

  • (Object, nil) —

    the writer, if found



426
427
428
# File 'lib/raptor/reactor.rb', line 426

def writer_for(id)
  @id_to_writer[id]
end