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, http1_ractor_pool, http2_ractor_pool, thread_pool, connection_options:, http1_options:, http2_options:) ⇒ Reactor

Creates a new Reactor.

Parameters:

  • http1 (Http1) —

    the HTTP/1.1 handler that resumes idle keep-alive connections

  • 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



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/raptor/reactor.rb', line 222

def initialize(http1, http1_ractor_pool, http2_ractor_pool, thread_pool, connection_options:, http1_options:, http2_options:)
  @http1 = http1
  @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



602
603
604
605
606
607
# File 'lib/raptor/reactor.rb', line 602

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 connection identifier



311
312
313
314
315
316
317
# File 'lib/raptor/reactor.rb', line 311

def add(state)
  socket = state.delete(:socket)
  @id_to_socket[state[:id]] = socket
  @socket_to_state[socket] = state

  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 connection 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



422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/raptor/reactor.rb', line 422

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
  @io_queue << [:cancel_http1, id]
  @selector.wakeup rescue nil
  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 connection identifier

  • body (DetachedBody) —

    the response body

  • state (Hash) —

    connection state restored once the response finishes

  • finished (Proc) —

    called with the close reason



758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/raptor/reactor.rb', line 758

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 connection identifier

  • socket (TCPSocket) —

    the connection socket

  • state (Hash) —

    initial connection state

  • writer (Http2::Writer) —

    frame writer for the connection

  • 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: (Http2::Writer)
  • flow_control: (Http2::FlowControl)
  • ping_frame: (String)
  • ping_payload: (String)


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

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) —

    the HTTP/2 stream identifier

  • body (DetachedBody) —

    the response body

  • finished (Proc) —

    called with the close reason

Returns:

  • (Boolean) —

    whether the body was attached



506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/raptor/reactor.rb', line 506

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) —

    the HTTP/2 stream identifier

  • body (DetachedBody) —

    the response body

  • finished (Proc) —

    called with the close reason



879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
# File 'lib/raptor/reactor.rb', line 879

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



653
654
655
# File 'lib/raptor/reactor.rb', line 653

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.



1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
# File 'lib/raptor/reactor.rb', line 1019

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) —

    the HTTP/2 stream identifier



540
541
542
543
544
545
# File 'lib/raptor/reactor.rb', line 540

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



1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
# File 'lib/raptor/reactor.rb', line 1461

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:



1204
1205
1206
1207
1208
# File 'lib/raptor/reactor.rb', line 1204

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 connection identifier



1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
# File 'lib/raptor/reactor.rb', line 1051

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 connection identifier



631
632
633
634
# File 'lib/raptor/reactor.rb', line 631

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

#complete?(state) ⇒ Boolean

Returns whether the request has been fully parsed.

Parameters:

  • state (Hash) —

    connection state

Returns:

  • (Boolean)


1495
1496
1497
# File 'lib/raptor/reactor.rb', line 1495

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



1217
1218
1219
1220
1221
1222
1223
# File 'lib/raptor/reactor.rb', line 1217

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.



1036
1037
1038
1039
1040
1041
1042
1043
# File 'lib/raptor/reactor.rb', line 1036

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) —

    the HTTP/2 stream identifier

Returns:

  • (Boolean) —

    whether the stream may be dispatched



445
446
447
448
449
450
451
452
453
# File 'lib/raptor/reactor.rb', line 445

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



554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/raptor/reactor.rb', line 554

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:

  • for each HTTP/2 connection

Yield Parameters:

  • stream_id (Integer) —

    the last dispatched HTTP/2 stream identifier

Yield Returns:

  • (String) —

    serialized GOAWAY frame



464
465
466
467
468
469
470
471
472
473
# File 'lib/raptor/reactor.rb', line 464

def drain_http2
  # Connections may attach on other threads while this iterates.
  @id_to_flow_control.keys.each 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.



694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
# File 'lib/raptor/reactor.rb', line 694

def drain_io_queue
  connections = {}
  while (operation = @io_queue.pop)
    type, id, value, body, attached, finished, state = operation
    case type
    when :write
      queue_output(@id_to_io[id], value)
      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 :cancel_http1
      remove_http1_detached_body(id, :cancelled)
    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



675
676
677
678
679
680
681
682
683
684
685
686
687
# File 'lib/raptor/reactor.rb', line 675

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 connection identifier

  • io (Http1IO) —

    connection I/O state



817
818
819
820
821
822
823
824
825
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
# File 'lib/raptor/reactor.rb', line 817

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) —

    the HTTP/2 stream identifier

  • body (DetachedBody) —

    the response body



982
983
984
985
986
987
988
989
990
991
992
993
994
# File 'lib/raptor/reactor.rb', line 982

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

Returns whether any data has been received for this connection.

Parameters:

  • state (Hash) —

    connection state

Returns:

  • (Boolean)


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

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

#flow_control_for(id) ⇒ Http2::FlowControl?

Returns the HTTP/2 flow controller registered by #attach_http2 for a connection.

Parameters:

  • id (Integer) —

    unique connection identifier

Returns:



408
409
410
# File 'lib/raptor/reactor.rb', line 408

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 connection identifier



783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# File 'lib/raptor/reactor.rb', line 783

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



932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
# File 'lib/raptor/reactor.rb', line 932

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, nil) —

    connection I/O state



1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
# File 'lib/raptor/reactor.rb', line 1097

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 connection identifier



1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
# File 'lib/raptor/reactor.rb', line 1352

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



1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
# File 'lib/raptor/reactor.rb', line 1308

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)
  client = @id_to_timeout.delete(id)
  @timeouts.delete!(client) if 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



1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
# File 'lib/raptor/reactor.rb', line 1283

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) —

    the HTTP/2 stream identifier



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

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) —

    unique connection identifier

  • request_count (Integer) —

    number of requests handled on this connection

  • remote_addr (String) —

    the client IP address

  • url_scheme (String) —

    "http" or "https"

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


363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/raptor/reactor.rb', line 363

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.

Appends bytes to one connection's pending output.

Parameters:

  • io (ConnectionIO, nil) —

    connection I/O state

  • data (String) —

    serialized response bytes



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

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) ⇒ void

This method returns an undefined value.

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



1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
# File 'lib/raptor/reactor.rb', line 1431

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



1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
# File 'lib/raptor/reactor.rb', line 1231

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 connection identifier

Returns:

  • (TCPSocket, nil) —

    the socket associated with id, if any



346
347
348
349
350
# File 'lib/raptor/reactor.rb', line 346

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 connection identifier



1068
1069
1070
1071
# File 'lib/raptor/reactor.rb', line 1068

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 connection identifier

  • reason (Symbol) —

    why the response closed



859
860
861
862
863
864
865
866
867
868
# File 'lib/raptor/reactor.rb', line 859

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) —

    the HTTP/2 stream identifier

  • reason (Symbol) —

    why the stream closed



1004
1005
1006
1007
1008
1009
1010
1011
1012
# File 'lib/raptor/reactor.rb', line 1004

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



526
527
528
529
530
531
# File 'lib/raptor/reactor.rb', line 526

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



919
920
921
922
923
924
# File 'lib/raptor/reactor.rb', line 919

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

#resume_keepalive(socket, state) ⇒ void

This method returns an undefined value.

Resumes a readable keep-alive connection on an application thread, avoiding a Ractor round trip for complete requests.

Parameters:

  • socket (TCPSocket) —

    the readable client socket

  • state (Hash) —

    current connection state



1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
# File 'lib/raptor/reactor.rb', line 1405

def resume_keepalive(socket, state)
  remove(state[:id])
  @thread_pool << proc do
    @http1.eager_keepalive(
      socket,
      state[:id],
      self,
      @thread_pool,
      state[:request_count],
      state[:remote_addr],
      state[:url_scheme],
      resumed: true
    )
  end
rescue AtomicThreadPool::EnqueuedWorkAfterShutdownError
  socket.close rescue nil
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



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/raptor/reactor.rb', line 261

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.



642
643
644
645
# File 'lib/raptor/reactor.rb', line 642

def shutdown
  @queue.close
  @selector.wakeup
end

#socket_for(id) ⇒ TCPSocket?

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

Parameters:

  • id (Integer) —

    unique connection identifier

Returns:

  • (TCPSocket, nil) —

    the socket, if found



386
387
388
# File 'lib/raptor/reactor.rb', line 386

def socket_for(id)
  @id_to_socket[id]
end

#stopped? ⇒ Boolean

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

Returns:

  • (Boolean)


664
665
666
667
# File 'lib/raptor/reactor.rb', line 664

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



1268
1269
1270
1271
1272
1273
# File 'lib/raptor/reactor.rb', line 1268

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



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

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_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



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 1161

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) —

    unique connection identifier



327
328
329
330
331
332
333
334
335
336
# File 'lib/raptor/reactor.rb', line 327

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



1148
1149
1150
1151
1152
# File 'lib/raptor/reactor.rb', line 1148

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.

Deregisters a readable socket and resumes its idle keep-alive connection or queues its bytes for parsing.

Parameters:

  • socket (TCPSocket) —

    the socket that became ready



1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
# File 'lib/raptor/reactor.rb', line 1384

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

  if state[:persisted] && !state.key?(:buffer)
    resume_keepalive(socket, state)
  else
    read_and_queue_for_parse(socket, state)
  end
end

#watch(id) ⇒ void

This method returns an undefined value.

Registers an attached socket for future reactor-driven reads.

Parameters:

  • id (Integer) —

    unique connection identifier



615
616
617
618
619
620
621
622
623
# File 'lib/raptor/reactor.rb', line 615

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



483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/raptor/reactor.rb', line 483

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) ⇒ Http2::Writer?

Returns the HTTP/2 frame writer registered by #attach_http2 for a connection.

Parameters:

  • id (Integer) —

    unique connection identifier

Returns:



397
398
399
# File 'lib/raptor/reactor.rb', line 397

def writer_for(id)
  @id_to_writer[id]
end