Class: Lich::Common::SynchronizedSocket

Inherits:
Object
  • Object
show all
Defined in:
documented/common/class_exts/synchronizedsocket.rb

Overview

Thread-safe socket wrapper with write-side resilience.

Wraps a delegate socket (typically TCPSocket) with a mutex to serialize writes and an internal liveness flag that transitions irreversibly to dead on any fatal write error.

When a fatal write error occurs the wrapper:

  1. Sets @alive to false
  2. Closes the delegate socket (unblocking any blocked readers)
  3. Logs the error via Lich.log

A WriteQueueOverflow additionally dumps every still-pending write to Lich.log, so a stalled frontend can be diagnosed from the queue contents rather than from the summary line alone.

When the pending-write budget is exhausted the queue is first compacted by discarding the oldest prompt-delimited groups; the session only ends if compaction cannot free space. Compaction drops display data the parser has already consumed, so a slow frontend costs a gap in its scrollback rather than the whole session.

Subsequent writes short-circuit without touching the delegate. Reads still delegate via method_missing so lifecycle threads can detect the closed socket through normal IOError propagation.

Frontend writes are queued through one socket-local writer thread so a slow frontend cannot block the game parser. Main-stream output is deferred while a frontend stream is open and released after the matching popStream or prompt has entered the queue.

Defined Under Namespace

Classes: WriteQueueOverflow

Constant Summary collapse

FATAL_WRITE_ERRORS =

Errors that indicate a permanently broken write path.

[
  Errno::ECONNRESET,
  Errno::EPIPE,
  Errno::ECONNABORTED,
  Errno::ENOTCONN,
  IOError,
].freeze
WRITER_INIT_MUTEX =

Global mutex protecting lazy initialization of the writer thread and its associated queue and stream state.

Serializes access to @writer_thread, @write_queue, @stream_stack, @stream_mutex, and @deferred_main_stream across concurrent calls to #ensure_writer! from different enqueue paths.

Mutex.new
DEFAULT_WRITE_QUEUE_CAPACITY =
4_096
OVERFLOW_KEEP_PROMPT_GROUPS =

Number of trailing prompt-delimited groups retained when the write queue is compacted. A <prompt> clears the stream stack, so a group boundary is a point where stream nesting is balanced and older output can be discarded without orphaning a pushStream in the frontend.

10
DROP_PREAMBLE_SIZE =

Items injected ahead of the retained groups on compaction: the replayed resync prompt and the client-visible notice. Kept in sync with drop_preamble, which never returns more than this many items.

2
PROMPT_TAG =

Regexp matching the start of a <prompt> tag (case-insensitive).

Used to detect prompt boundaries that demarcate output groups safe to drop during write queue compaction. A prompt clears the frontend's stream stack, so cutting at a prompt boundary preserves stream nesting invariants.

Examples:

"<prompt type=\"room state\">" =~ PROMPT_TAG #=> 0
"<Prompt>" =~ PROMPT_TAG #=> 0
"<other>" =~ PROMPT_TAG #=> nil
/<prompt\b/i
OVERFLOW_DUMP_MAX_BYTES_PER_ARG =

Per-argument byte cap applied when dumping pending writes after an overflow. Longer payloads are truncated with their full byte size noted.

1_024
OVERFLOW_DUMP_EDGE_ENTRIES =

Leading and trailing entries emitted per section by the overflow dump. Bounds a single log record at roughly 400 entries per section instead of the full queue capacity.

200
ROLES =

Valid socket roles controlling failure behavior.

:primary — socket failure ends the game session via ShutdownCoordinator. :detachable — socket failure only closes this connection; the session continues and the frontend can reconnect.

See Also:

%i[primary detachable].freeze
ATTACHMENT_STREAM_SENTINEL =

Sentinel object marking the initial state of a :detachable socket's stream stack.

A detachable frontend can reconnect after disconnection, potentially leaving the parser with an orphaned open stream. This sentinel in the stack indicates pre-connection state; if found during stream tracking, it is cleared rather than triggering an unbalanced popStream error.

Object.new.freeze

Instance Method Summary collapse

Constructor Details

#initialize(delegate, role: :primary, write_queue_capacity: DEFAULT_WRITE_QUEUE_CAPACITY) ⇒ SynchronizedSocket

Returns a new instance of SynchronizedSocket.

Parameters:

  • delegate (#puts, #write, #gets, #close) —

    the underlying socket

  • role (Symbol) (defaults to: :primary) —

    whether failure should end the session or only the detachable connection

  • write_queue_capacity (Integer) (defaults to: DEFAULT_WRITE_QUEUE_CAPACITY) —

    maximum pending writes

Raises:

  • (ArgumentError)


108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'documented/common/class_exts/synchronizedsocket.rb', line 108

def initialize(delegate, role: :primary, write_queue_capacity: DEFAULT_WRITE_QUEUE_CAPACITY)
  raise ArgumentError, "unknown socket role: #{role.inspect}" unless ROLES.include?(role)
  unless write_queue_capacity.is_a?(Integer) && write_queue_capacity.positive?
    raise ArgumentError, 'write_queue_capacity must be a positive Integer'
  end

  @delegate = delegate
  @mutex = Mutex.new
  @state_mutex = Mutex.new
  @alive = true
  @role = role
  @write_queue_capacity = write_queue_capacity
  @declared_capabilities = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

Delegates all non-write methods to the underlying socket.

Read-side errors propagate normally so that connection lifecycle threads can detect disconnects.



208
209
210
# File 'documented/common/class_exts/synchronizedsocket.rb', line 208

def method_missing(method, *args, &block)
  @delegate.__send__(method, *args, &block)
end

Instance Method Details

#alive? ⇒ Boolean

Whether the socket is usable for I/O.

Returns false once a fatal write error has occurred or the delegate has been closed by any means. This transition is one-way -- a dead socket cannot be revived.

Returns:

  • (Boolean)


130
131
132
# File 'documented/common/class_exts/synchronizedsocket.rb', line 130

def alive?
  @alive && !@delegate.closed?
end

#close(*args, &block) ⇒ Object

Marks the socket dead, closes the delegate, and stops the writer.



180
181
182
183
184
185
186
# File 'documented/common/class_exts/synchronizedsocket.rb', line 180

def close(*args, &block)
  @alive = false
  @delegate.close(*args, &block) unless @delegate.closed?
  @write_queue.push([:stop, [], nil], true) if @write_queue.is_a?(Queue)
rescue ThreadError
  nil
end

#declared_capabilities ⇒ Array<Symbol>?

The rich-stream capabilities this client declared with a SET_FRONTEND_CAPS line (see Lich::Common::ClientCapabilities), or nil when it has not declared any. Set by the client's reader thread and read by the game thread; the value is a frozen Array replaced whole, so a reader sees either the old set or the new one.

Returns:

  • (Array<Symbol>, nil)


195
196
197
# File 'documented/common/class_exts/synchronizedsocket.rb', line 195

def declared_capabilities
  @declared_capabilities
end

#declared_capabilities=(capabilities) ⇒ Object

Parameters:

  • capabilities (Array<Symbol>, nil)


200
201
202
# File 'documented/common/class_exts/synchronizedsocket.rb', line 200

def declared_capabilities=(capabilities)
  @declared_capabilities = capabilities.nil? ? nil : capabilities.dup.freeze
end

#puts(*args, &block) ⇒ nil

Queue a newline-terminated write for the writer thread.

Returns:

  • (nil) —

    the write happens asynchronously



137
138
139
# File 'documented/common/class_exts/synchronizedsocket.rb', line 137

def puts(*args, &block)
  enqueue_write(:puts, args, block)
end

#puts_if(*args) ⇒ Object

Compatibility alias for scripts using the historical name. Blocks were never part of the asynchronous contract and are intentionally ignored.



168
169
170
# File 'documented/common/class_exts/synchronizedsocket.rb', line 168

def puts_if(*args)
  puts_main_stream(*args)
end

#puts_main_stream(*args) ⇒ Boolean

Queue output for the next main-stream opportunity.

Returns:

  • (Boolean) —

    true if accepted, false if the socket is dead



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'documented/common/class_exts/synchronizedsocket.rb', line 144

def puts_main_stream(*args)
  return false unless @alive

  ensure_writer!
  queued_args = copy_args(args)

  @stream_mutex.synchronize do
    return false unless alive?

    if stream_open?
      ensure_pending_capacity!
      @deferred_main_stream << queued_args
    else
      queue_puts_locked(queued_args)
    end
  end
  true
rescue StandardError => e
  handle_enqueue_error('puts_main_stream', e)
  false
end

#respond_to_missing?(method, include_private = false) ⇒ Boolean

Returns whether the delegate responds to method.

Returns:

  • (Boolean) —

    whether the delegate responds to method



213
214
215
# File 'documented/common/class_exts/synchronizedsocket.rb', line 213

def respond_to_missing?(method, include_private = false)
  @delegate.respond_to?(method, include_private) || super
end

#write(*args, &block) ⇒ nil

Queue a raw write for the writer thread.

Returns:

  • (nil) —

    the write happens asynchronously



175
176
177
# File 'documented/common/class_exts/synchronizedsocket.rb', line 175

def write(*args, &block)
  enqueue_write(:write, args, block)
end