Class: Lich::GameBase::Game

Inherits:
Object
  • Object
show all
Defined in:
documented/games.rb

Overview

Base Game class with common functionality

Direct Known Subclasses

DragonRealms::Game, Lich::Gemstone::Game

Defined Under Namespace

Classes: ServerQueueOverflow

Constant Summary collapse

READ_TIMEOUT_SECONDS =

Seconds to wait for readable game socket data before one read timeout.

100
MAX_CONSECUTIVE_READ_TIMEOUTS =

Consecutive read timeouts allowed before treating the game link as dead.

3
READ_TIMEOUT =

Sentinel returned when the game socket has no readable data before timeout.

Object.new.freeze
SERVER_QUEUE_CAPACITY =

A full queue means the parser cannot preserve the game stream. Dropping records or blocking the socket reader would both make recovery unsafe.

4_096

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

._buffer ⇒ Object (readonly)

Returns the value of attribute _buffer.



541
542
543
# File 'documented/games.rb', line 541

def _buffer
  @_buffer
end

.buffer ⇒ Object (readonly)

Returns the value of attribute buffer.



541
542
543
# File 'documented/games.rb', line 541

def buffer
  @buffer
end

.game_instance ⇒ Object (readonly)

Returns the value of attribute game_instance.



541
542
543
# File 'documented/games.rb', line 541

def game_instance
  @game_instance
end

.reader_thread ⇒ Object (readonly)

Returns the value of attribute reader_thread.



541
542
543
# File 'documented/games.rb', line 541

def reader_thread
  @reader_thread
end

.server_queue ⇒ Object (readonly)

Returns the value of attribute server_queue.



541
542
543
# File 'documented/games.rb', line 541

def server_queue
  @server_queue
end

.thread ⇒ Object (readonly)

Returns the value of attribute thread.



541
542
543
# File 'documented/games.rb', line 541

def thread
  @thread
end

Class Method Details

._gets ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Reads one raw server line from the internal buffer (testing only).

Returns:

  • (String, nil) —

    a line as the server sent it, or nil if buffer is exhausted



927
928
929
# File 'documented/games.rb', line 927

def _gets
  @_buffer.gets
end

._puts(str) ⇒ true?

Writes a string to the game server socket.

Thread-safe via mutex. Silently absorbs fatal connection errors so callers (scripts) are not killed by a broken server link. A calling script's execution guard receives an immutable copy of the exact wire command: puts has already added $cmd_prefix, while direct _puts callers supply their own prefix. Checks run under the write lock and are charged once here, never again in puts.

Parameters:

  • str (String) —

    the raw command to send upstream

Returns:

  • (true, nil) —

    true when written; nil on connection error

Raises:



854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
# File 'documented/games.rb', line 854

def _puts(str)
  # Raw callers may hold other shared locks (e.g. Inventory.refresh).
  # Preserve their pause-free sends while still resolving their guard.
  script = Script.current_without_pause
  # A guard callback must not reenter the socket. Let Script's guard
  # recursion check reject it before Ruby attempts to relock the mutex.
  if @mutex.owned? && script.respond_to?(:check_execution_guard!) &&
     script.respond_to?(:execution_guard_active?) && script.execution_guard_active?
    script.check_execution_guard!(command: str.to_s.dup.freeze)
  end
  @mutex.synchronize do
    # Recheck the captured owner's current policy here
    # after lock contention; do not retain an earlier permission result.
    guarded = script.respond_to?(:check_execution_guard!) &&
              script.respond_to?(:execution_guard_active?) && script.execution_guard_active?
    command = guarded ? str.to_s.dup.freeze : str
    script.check_execution_guard!(command: command) if guarded
    begin
      @socket.puts(command)
      true
    rescue Errno::EPIPE, Errno::ECONNRESET, Errno::ECONNABORTED, IOError, OpenSSL::SSL::SSLError => e
      Lich.log "error: _puts: #{e}\n\t#{e.backtrace.first}"
      nil
    end
  end
end

.autostarted? ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns whether the autostart script has run.

Returns:

  • (Boolean)


559
560
561
# File 'documented/games.rb', line 559

def autostarted?
  @@autostarted
end

.check_stream_desync!(parse_errors) ⇒ Object

Promote truncation-class Ox parse errors to GameStreamDesyncError so a desynced stream still hits the log + reset recovery path instead of being silently absorbed (see the GameStreamDesyncError comment). parse_errors is XMLData's collected Ox error-callback messages for the fragment just parsed.



1460
1461
1462
1463
1464
1465
# File 'documented/games.rb', line 1460

def check_stream_desync!(parse_errors)
  desync = parse_errors.find do |message|
    STREAM_DESYNC_ERRORS.any? { |pattern| pattern.match?(message) }
  end
  raise GameStreamDesyncError, desync if desync
end

.client_write_targets ⇒ Array

The clients that receive game output: every attached detachable client, else the primary client. While a detachable client is attached, the primary gets none.

Returns:

  • (Array) —

    a snapshot; the registry may change while it is used



1664
1665
1666
1667
1668
1669
1670
# File 'documented/games.rb', line 1664

def client_write_targets
  detachable_clients = $_DETACHABLE_CLIENT_REGISTRY_&.snapshot || []
  detachable_clients = [$_DETACHABLE_CLIENT_] if detachable_clients.empty? && $_DETACHABLE_CLIENT_
  return detachable_clients unless detachable_clients.empty?

  $_CLIENT_ ? [$_CLIENT_] : []
end

.close ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Closes the game socket and stops reader/parser threads.



833
834
835
836
837
838
839
# File 'documented/games.rb', line 833

def close
  if @socket
    @socket.close rescue nil
    @reader_thread.kill rescue nil
    @thread.kill rescue nil
  end
end

.closed? ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns whether the game socket is closed or nil.

Returns:

  • (Boolean)


725
726
727
# File 'documented/games.rb', line 725

def closed?
  @socket.nil? || @socket.closed?
end

.connection_disruption_log_message(error) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Formats an error as a one-line log message for connection disruptions.

Extracts the first line of desync-error messages; for other errors, returns "ClassName: message".

Parameters:

  • error (StandardError) —

    the exception

Returns:

  • (String) —

    a short log line



1829
1830
1831
1832
1833
# File 'documented/games.rb', line 1829

def connection_disruption_log_message(error)
  return "GameStreamDesyncError: #{error.message.lines.first&.strip}" if error.is_a?(GameStreamDesyncError)

  "#{error.class}: #{error.message}"
end

.current_ingress_time ⇒ Numeric?

Timestamp already attached by the socket reader before queueing. Available only during this exact parser thread's current dispatch; delayed subscribers and legacy direct calls cannot mint provenance.

Returns:

  • (Numeric, nil) —

    monotonic receipt time, or nil outside a valid socket-origin parser dispatch



548
549
550
551
552
553
# File 'documented/games.rb', line 548

def current_ingress_time
  return nil unless Thread.current.equal?(@thread)

  value = Thread.current.thread_variable_get(:lich_game_ingress_time)
  value if value.is_a?(Numeric) && value.real? && value.finite? && value >= 0
end

.display_ruby_warning ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Displays a formatted warning if the Ruby version is below the recommended threshold.

Renders a bordered table with the current and recommended versions and a link to the game-specific installation guide. Uses the game instance's #get_documentation_url.



1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
# File 'documented/games.rb', line 1344

def display_ruby_warning
  ruby_warning = Terminal::Table.new
  ruby_warning.title = "Ruby Recommended Version Warning"
  ruby_warning.add_row(["Please update your Ruby installation."])
  ruby_warning.add_row(["You're currently running Ruby v#{Gem::Version.new(RUBY_VERSION)}!"])
  ruby_warning.add_row(["It's recommended to run Ruby v#{Gem::Version.new(RECOMMENDED_RUBY)} or higher!"])
  ruby_warning.add_row(["Future Lich5 releases will soon require this newer version."])
  ruby_warning.add_row([" "])
  ruby_warning.add_row(["Visit the following link for info on updating:"])

  # Use instance to get the appropriate documentation URL
  if @game_instance
    ruby_warning.add_row([@game_instance.get_documentation_url])
  else
    ruby_warning.add_row(["Unknown game type detected."])
    ruby_warning.add_row(["Unsure of proper documentation, please seek assistance via discord!"])
  end

  ruby_warning.to_s.split("\n").each do |row|
    Lich::Messaging.mono(Lich::Messaging.monsterbold(row))
  end
end

.enqueue_server_string(server_string, enqueued_monotonic_at, ingress_monotonic_at: enqueued_monotonic_at) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Pushes a parsed server string into the processing queue.

Records the enqueue time (monotonic, for wait-time stats) and ingress time (when the socket reader first received it). Raises ServerQueueOverflow if the queue is at capacity; this should not occur in normal operation.

Parameters:

  • server_string (String) —

    the line to process

  • enqueued_monotonic_at (Numeric) —

    monotonic timestamp of enqueue

  • ingress_monotonic_at (Numeric) (defaults to: enqueued_monotonic_at) —

    monotonic timestamp of socket receipt

Raises:



973
974
975
976
977
978
# File 'documented/games.rb', line 973

def enqueue_server_string(server_string, enqueued_monotonic_at, ingress_monotonic_at: enqueued_monotonic_at)
  @server_queue.push([server_string, enqueued_monotonic_at, ingress_monotonic_at], true)
  record_server_queue_enqueue
rescue ThreadError
  raise ServerQueueOverflow, "game parser queue exceeded #{SERVER_QUEUE_CAPACITY} records"
end

.finish_client_line(alt_string) ⇒ String

The steps that follow the session's front end ($frontend), whatever the client's capabilities: room-number display, the Genie and Frostbite subtitle edits, Wizard's GSL conversion and the origin sentinel.

Parameters:

  • alt_string (String) —

    a rewritten server string (may be modified in place)

Returns:

  • (String) —

    the bytes to write to the client



1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
# File 'documented/games.rb', line 1602

def finish_client_line(alt_string)
  process_room_information(alt_string)

  # Handle frontend-specific modifications
  if Frontend.client.eql?('genie') && alt_string =~ /^<streamWindow id='room' title='Room' subtitle=" - \[.*\] \((?:\d+|\*\*)\)"/
    alt_string.sub!(/] \((?:\d+|\*\*)\)/) { "]" }
  end

  if Frontend.client.eql?('frostbite') && alt_string =~ /^<streamWindow id='main' title='Story' subtitle=" - \[.*\] \((?:\d+|\*\*)\)"/
    alt_string.sub!(/] \((?:\d+|\*\*)\)/) { "]" }
  end

  # Handle room number display
  if @room_number_after_ready && alt_string =~ /<prompt /
    alt_string = @game_instance ? @game_instance.process_room_display(alt_string) : alt_string
    @room_number_after_ready = false
  end

  # Handle frontend-specific conversions
  if Frontend.supports_gsl?
    alt_string = sf_to_wiz(alt_string)
  end
  # Handle prefix origin sentinel if FE supports it
  alt_string = prefix_origin_sentinel(alt_string) if Frontend.supports_sentinel?
  alt_string
end

.fix_invalid_settings_info(server_string) ⇒ Object

The server sends a malformed <settingsInfo ... space not found .../> (an attribute with no '=') to characters that have never connected with the Wrayth/StormFront client. REXML raised on it (the rescue repaired it); Ox tolerates it and emits "no attribute value", so it is repaired from repair_malformed_attributes_and_reparse. @@settings_init_needed makes gameloader's PostLoad seed a valid client record (see settings_init_needed? and lib/common/gameloader.rb).



1504
1505
1506
1507
1508
1509
1510
1511
# File 'documented/games.rb', line 1504

def fix_invalid_settings_info(server_string)
  return unless server_string =~ /<settingsInfo .*?space not found /

  Lich.log "Invalid settingsInfo XML tags detected: #{server_string.inspect}"
  server_string.sub!(/\s\bspace not found\b\s/, " client='1.0.1.28' ")
  Lich.log "Invalid settingsInfo XML tags fixed to: #{server_string.inspect}"
  @@settings_init_needed = true
end

.gets ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Reads one stripped server line from the main buffer.

Returns:

  • (String, nil) —

    a line from the parsed stream, or nil if buffer is exhausted



919
920
921
# File 'documented/games.rb', line 919

def gets
  @buffer.gets
end

.handle_autostart ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Runs autostart initialization: version checks, core updates, script syncs, and the autostart script.

Compares LICH_VERSION to Lich.core_updated_with_lich_version; if a newer version is detected, updates core scripts. Spawns a background thread to sync all script repositories (to avoid blocking the parser while XMLData.name is populated). Starts the 'autostart' script if it exists. Sets @@autostarted to true and optionally displays a Ruby-version warning.

Called when the first tag arrives (login complete).



1303
1304
1305
1306
1307
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
# File 'documented/games.rb', line 1303

def handle_autostart
  if defined?(LICH_VERSION) && defined?(Lich.core_updated_with_lich_version) &&
     Gem::Version.new(LICH_VERSION) > Gem::Version.new(Lich.core_updated_with_lich_version)
    Lich::Messaging.mono(Lich::Messaging.monsterbold("New installation or updated version of Lich5 detected!"))
    Lich::Messaging.mono(Lich::Messaging.monsterbold("Installing newest core scripts available to ensure you're up-to-date!"))
    Lich::Messaging.mono("")
    Lich::Util::Update.update_core_data_and_scripts
  end

  # Sync script repositories on login for both DR and GS.
  # MUST run in a background thread -- sync_all_repos makes HTTP calls
  # that block the game thread, preventing process_xml_data from setting
  # XMLData.name. If Vars is accessed before XMLData.name is set, it
  # loads/saves under scope "DR:" instead of "DR:CharName", overwriting
  # real data with an empty session.
  Thread.new do
    # Wait for XMLData.name to be populated by process_xml_data
    # before touching Vars. 200 x 50ms = 10s max wait.
    200.times do
      break if !XMLData.name.nil? && !XMLData.name.empty?

      sleep 0.05
    end
    Lich::Util::Update.sync_all_repos if !XMLData.name.nil? && !XMLData.name.empty?
  rescue StandardError => e
    Lich.log "repo_sync(login): #{e.class}: #{e.message}"
  end

  Script.start('autostart') if defined?(Script) && Script.respond_to?(:exists?) && Script.exists?('autostart')
  @@autostarted = true

  display_ruby_warning if defined?(RECOMMENDED_RUBY) && Gem::Version.new(RUBY_VERSION) < Gem::Version.new(RECOMMENDED_RUBY)
end

.handle_thread_error(error) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Determines whether the reader thread should retry after an error.

Classifies the error (timeout, connection, protocol, queue overflow, desync, or unknown) and returns true (retry) or false (exit). Fatal errors (connection reset, protocol violation, desync) always return false. Timeouts after consecutive-retry exhaustion return false. Unknown errors check socket/client state; if both are alive, retry is allowed. Logs all errors.

Parameters:

  • error (StandardError) —

    the exception caught by the reader thread

Returns:

  • (Boolean) —

    true if the thread should retry, false to exit



1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
# File 'documented/games.rb', line 1683

def handle_thread_error(error)
  if recognized_connection_disruption?(error)
    shutdown_log.info("server_thread: #{connection_disruption_log_message(error)}")
    shutdown_log.debug("server_thread backtrace: #{error.backtrace.join("\n\t")}") if error.backtrace
  else
    shutdown_log.error("server_thread: #{error}\n\t#{Array(error.backtrace).join("\n\t")}")
  end
  sleep 0.2

  case error
  when Errno::ETIMEDOUT, Errno::EWOULDBLOCK, IO::TimeoutError
    # Timeout errors reach this outer handler only after the inner
    # reader loop has exhausted its consecutive-timeout threshold.
    shutdown_log.info("game timeout - will not retry")
    return false
  when Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED, OpenSSL::SSL::SSLError
    # Connection errors are fatal
    shutdown_log.info("connection error - will not retry")
    return false
  when Lich::Common::WebSocket::Frame::ProtocolError
    # A framing violation leaves the offending bytes stuck at the
    # front of Stream's internal buffer (raised before they're
    # consumed), so every retry would just hit the same error again
    # on the same bytes -- not a transient condition.
    shutdown_log.info("WebSocket protocol error - will not retry")
    return false
  when GameStreamDesyncError
    shutdown_log.info("game stream desync detected - will not retry")
    return false
  when ServerQueueOverflow
    shutdown_log.info("game parser queue overflow - will not retry")
    return false
  else
    # Check if socket/client are closed or if it's a known fatal error
    if !$_CLIENT_.alive? || @socket.closed?
      shutdown_log.info("client or socket closed - will not retry")
      return false
    elsif error.to_s =~ /invalid argument|A connection attempt failed|An existing connection was forcibly closed|An established connection was aborted by the software in your host machine./i
      shutdown_log.info("fatal error pattern detected - will not retry")
      return false
    else
      shutdown_log.debug("unknown server thread error - will attempt retry")
      return true
    end
  end
end

.initialize_buffers ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Initializes or resets Game thread state and buffers.

Clears socket, mutexes, queues, and buffers; sets thread references to nil; resets autostart and CLI-script flags. Called at startup and on reconnect/reset. Also clears the global strip_xml multiline carry-over so a fragment left open before a disconnect does not bleed into the next session.



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# File 'documented/games.rb', line 595

def initialize_buffers
  @socket = nil
  @mutex = Mutex.new
  @last_recv = nil
  @thread = nil
  @reader_thread = nil
  @remote_eof = false
  @server_queue = SizedQueue.new(SERVER_QUEUE_CAPACITY)
  reset_server_queue_stats!
  @buffer = Lich::Common::SharedBuffer.new
  @_buffer = Lich::Common::SharedBuffer.new
  @_buffer.max_size = 1000
  @@autostarted = false
  @@settings_init_needed = false
  @cli_scripts = false
  @room_number_after_ready = false
  @last_id_shown_room_window = 0
  @game_instance = nil
  # strip_xml's multiline carry is a process-global; clear it here so a
  # fragment left open before a reconnect/session reset does not bleed
  # into the next session.
  $strip_xml_multiline = {}
end

.intentional_shutdown_close_error?(error) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Detects whether an error is the result of an orderly user-initiated shutdown.

Returns true only if a shutdown is in progress, the socket is closed, and the error is a file-descriptor or stream-closure error (EBADF, stream closed, etc.).

Parameters:

  • error (StandardError) —

    the exception

Returns:

  • (Boolean)


1792
1793
1794
1795
1796
1797
1798
1799
# File 'documented/games.rb', line 1792

def intentional_shutdown_close_error?(error)
  return false unless defined?(Lich::Common::ShutdownCoordinator)
  return false unless Lich::Common::ShutdownCoordinator.orderly_user_exit?
  return false unless @socket&.closed?

  error.is_a?(Errno::EBADF) ||
    error.to_s =~ /stream closed in another thread|closed stream|bad file descriptor/i
end

.log_error(message, error) ⇒ Object (protected)



1837
1838
1839
# File 'documented/games.rb', line 1837

def log_error(message, error)
  Lich.log "#{message}: #{error}\n\t#{error.backtrace.join("\n\t")}"
end

.open(host, port, transport: Lich::Common::GameTransport::DIRECT, **transport_opts) ⇒ Socket, Lich::Common::WebSocket::Stream

Note:

Connection errors propagate to the caller. Use open_with_timeout to bound how long the connect may block.

Opens the connection to the game server and starts the socket's wrap and main reader threads.

Parameters:

  • host (String) —

    game server hostname

  • port (Integer) —

    game server port

  • transport (Symbol) (defaults to: Lich::Common::GameTransport::DIRECT) —

    Lich::Common::GameTransport::DIRECT (default, a raw TCP socket -- the connection method Lich has always used) or ::WEBSOCKET (opt-in; the browser WebSocket-to-TCP shim over TLS on 443 -- see Genie5#356 phase 2). Socket-level tuning (keepalive, linger, timeouts, TCP_NODELAY) is applied for both.

  • transport_opts (Hash) —

    forwarded to Lich::Common::GameTransport.open (WEBSOCKET-only knobs: shim_port, path, origin, subprotocol, user_agent, extra_headers, connect_timeout)

Returns:

See Also:



650
651
652
653
654
655
656
657
658
659
# File 'documented/games.rb', line 650

def open(host, port, transport: Lich::Common::GameTransport::DIRECT, **transport_opts)
  @remote_eof = false
  @socket = Lich::Common::GameTransport.open(host, port, mode: transport, **transport_opts)
  @socket.sync = true

  start_wrap_thread
  start_main_thread

  @socket
end

.open_with_timeout(host, port, timeout = 30, transport: Lich::Common::GameTransport::DIRECT, **transport_opts) ⇒ void

This method returns an undefined value.

Connects to the game server on a background thread, enforcing a connect timeout that a bare open cannot. Surfaces a stuck or failed connect instead of letting startup proceed with a dead socket.

Parameters:

  • host (String) —

    game server hostname

  • port (Integer) —

    game server port

  • timeout (Integer, Float) (defaults to: 30) —

    seconds to wait for the connect to complete

  • transport (Symbol) (defaults to: Lich::Common::GameTransport::DIRECT) —

    see open

  • transport_opts (Hash) —

    see open

Raises:

  • (RuntimeError) —

    if the connect does not complete within timeout

  • (StandardError) —

    re-raises whatever open raises (e.g. Errno::ECONNREFUSED) so the caller's rescue runs

See Also:



675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
# File 'documented/games.rb', line 675

def open_with_timeout(host, port, timeout = 30, transport: Lich::Common::GameTransport::DIRECT, **transport_opts)
  connect_thread = Thread.new {
    # report_on_exception off: a failed open is surfaced by the join below
    # (which re-raises it), not by an auto-printed thread warning.
    Thread.current.report_on_exception = false
    self.open(host, port, transport: transport, **transport_opts)
  }
  # join returns nil on timeout, the thread on success, and re-raises the
  # thread's exception on failure -- so a Game.open that errors (e.g.
  # connection refused) propagates to the caller's rescue instead of being
  # silently swallowed (the old `if connect_thread.status` could not tell a
  # thread that died with an exception, status nil, from a normal finish,
  # status false).
  if connect_thread.join(timeout).nil?
    connect_thread.kill rescue nil
    raise "error: timed out connecting to #{host}:#{port}"
  end
end

.prefix_origin_sentinel(string) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Prepends the origin sentinel to every line in a multi-line string.

Used for front ends that support the origin-sentinel feature; each line receives the sentinel prefix so the client can tag output as game-sourced.

Parameters:

  • string (String) —

    a server string with one or more \r\n-delimited lines

Returns:

  • (String) —

    the same string with Frontend::ORIGIN_SENTINEL prepended to each line



571
572
573
# File 'documented/games.rb', line 571

def prefix_origin_sentinel(string)
  string.gsub(/^.+$/) { |line| "#{Frontend::ORIGIN_SENTINEL}#{line}" }
end

.process_downstream_hooks(server_string) ⇒ Object

Sends one server string to every client, after the downstream hooks (which, like XMLParser and scripts, see the stream as the server sent it). Each client gets the rich-stream rewrites its capabilities call for (Lich::Common::ClientCapabilities): the string is rewritten once per distinct capability set, then finished once per distinct result, so clients that share a set (the usual case: one set for all) cost one pass, as before per-client capabilities.



1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
# File 'documented/games.rb', line 1520

def process_downstream_hooks(server_string)
  dragonrealms = XMLData.game =~ /^DR/
  # Followed before the hooks, so a hook that squelches the game's
  # reply to FLAG DESCRIPTION or the FLAG listing (DRInfomon's quiet
  # startup query) does not hide it from the filter, and whatever the
  # setting, so turning it on applies at once.
  Lich::Common::RoomDescriptionFilter.observe(server_string) if dragonrealms
  return unless (alt_string = DownstreamHook.run(server_string))

  # DragonRealms ignores FLAG DESCRIPTION OFF in the Saga-identity
  # stream's <room> block (a game bug). Opted in, every client gets the
  # character's room without its description, before the per-client
  # rewrites so both layouts come out as the legacy stream sends them.
  if dragonrealms && Lich::Common::RoomDescriptionFilter.descriptions_off? &&
     alt_string.include?('<room>') && Lich.follow_description_flag
    alt_string = Lich::Common::RoomDescriptionFilter.apply(alt_string, room_id: XMLData.room_id, room_exits: XMLData.room_exits)
  end

  outputs = []
  Lich::Common::ClientCapabilities.group(client_write_targets).each do |capabilities, clients|
    line = rich_stream_rewrite(alt_string, capabilities)
    same = outputs.find { |output| output[:line] == line }
    same ? same[:clients].concat(clients) : outputs << { line: line, clients: clients }
  end

  # Every result starts the finishing steps from the same room-number
  # state; they make the same decision for each, since no rewrite adds
  # or removes the room-name start or the prompt they look for. So with
  # N distinct results on a prompt line, process_room_display runs N
  # times: its Map.current lookups and any StringProc timeto in
  # room_stringproc_entries are evaluated once per result.
  room_number_after_ready = @room_number_after_ready
  outputs.each do |output|
    @room_number_after_ready = room_number_after_ready
    send_to_client(finish_client_line(output[:line]), output[:clients])
  end
end

.process_room_information(alt_string) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Detects room-display lines and queues them for formatting.

Matches the legacy roomName style or the Saga-identity block. If display_lichid, display_uid, or hide_uid_flag is on, calls the game instance's #modify_room_display to edit the line in place, then sets #process_room_display when the next prompt arrives.

Parameters:

  • alt_string (String) —

    the server line

Returns:

  • (String) —

    the (possibly modified) string



1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
# File 'documented/games.rb', line 1640

def process_room_information(alt_string)
  # The legacy roomName style, or the Saga-identity <room> block (see
  # Lich::Common::RoomBlock); the room-number rewrites work on either.
  if alt_string =~ /^(<pushStream id="familiar" ifClosedStyle="watching"\/>)?(?:<resource picture="\d+"\/>|<popBold\/>)?(?:<style id="roomName"\s+\/>|<room>)/
    if (Lich.display_lichid == true || Lich.display_uid == true || Lich.hide_uid_flag == true)
      @game_instance ? @game_instance.modify_room_display(alt_string) : alt_string
    end
    @room_number_after_ready = true
    alt_string
  end
end

.process_server_string(server_string) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Main entry point for processing one raw server line.

Detects game identity from XML, instantiates the game handler if needed, cleans and buffers the line, handles autostart and CLI scripts, parses XML, observes inventory if tracked, and runs downstream hooks. Called once per server string by the parser thread.

Parameters:

  • server_string (String) —

    one line from the game socket



1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
# File 'documented/games.rb', line 1244

def process_server_string(server_string)
  $cmd_prefix = String.new if server_string =~ /^\034GSw/

  # Load game-specific modules if needed
  unless (XMLData.game.nil? || XMLData.game.empty?)
    unless Module.const_defined?(:GameLoader)
      require_relative 'common/gameloader'
      GameLoader.load!
    end
  end

  # Set instance if not already set
  if @game_instance.nil? && !XMLData.game.nil? && !XMLData.game.empty?
    set_game_instance(XMLData.game)
  end

  # Clean server string based on game type
  if @game_instance
    server_string = @game_instance.clean_serverstring(server_string)
    return if server_string.nil? # A game's cleanup can drop a line
  end

  # Debug output if needed
  pp server_string if defined?($deep_debug) && $deep_debug

  # Push to server buffer
  $_SERVERBUFFER_.push(server_string)

  # Handle autostart
  handle_autostart if !@@autostarted && server_string =~ /<app char/

  # Handle CLI scripts
  if !@cli_scripts && @@autostarted && !XMLData.name.nil? && !XMLData.name.empty?
    start_cli_scripts
  end

  # Process XML data
  process_xml_data(server_string) unless server_string =~ /^<settings /

  # Passively capture the inventoryManager extended feed (read-only tap;
  # returns the string unchanged and never raises -- see
  # Lich::Common::Inventory.observe). Runs on this parser thread.
  Lich::Common::Inventory.observe(server_string) if defined?(Lich::Common::Inventory)

  # Run downstream hooks
  process_downstream_hooks(server_string)
end

.process_xml_data(server_string) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Parses one server string as XML and updates game state.

Uses Ox SAX parsing in permissive mode (tolerates unescaped ampersands, missing end tags, bare text). Repairs nested quotes and malformed attributes before parsing; if truncation/desync is detected, logs the error, resets XMLData, and returns early. On success, strips tags, splits lines, and dispatches downstream to Script and Inventory observers.

Skips parsing for blocks (those come raw).

Parameters:

  • server_string (String) —

    one server line



1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
# File 'documented/games.rb', line 1400

def process_xml_data(server_string)
  begin
    # Ox is a permissive parser: it handles Simu's not-quite-XML stream
    # without the clean/retry dance REXML required (nested quotes, missing
    # 'd' end tags, etc. are tolerated rather than raised). XMLData itself
    # implements the Ox::Sax interface, so Ox parses straight into it. No
    # <root> wrapper needed: that was a REXML requirement (single root); Ox
    # handles multiple top-level elements and bare text directly.
    XMLData.sax_parse_errors.clear
    # convert_special: false keeps Ox in bytes-land: it never decodes a
    # numeric entity (e.g. &#8217;) into UTF-8. The five standard XML
    # entities are decoded by XMLData#attr/#text instead. Values are left
    # in Ox's native (ASCII-8BIT) encoding -- REXML effectively produced
    # ASCII for this (high-byte-scrubbed) stream, so retagging to
    # Windows-1252 was a divergence and caused entity corruption.
    Ox.sax_parse(XMLData, server_string, convert_special: false, symbolize: false, skip: :skip_none)
    # Repair first: a nested quote can also make Ox report desync-class
    # errors ("document not terminated", "element not closed" -- e.g. an
    # inventoryManager long value of a sleek black book titled "Style: Do
    # you have it?"), so the desync check judges the repaired parse,
    # never the junk one.
    unrepaired = repair_malformed_attributes_and_reparse(server_string)
    check_stream_desync!(XMLData.sax_parse_errors)
  rescue GameStreamDesyncError => e
    # A truncated/desynced fragment. Ox never raises on malformed stream
    # content -- it reports via the error callback, and check_stream_desync!
    # promotes truncation-class errors to this exception. Log and reset
    # rather than killing the server thread. A repair didn't save the
    # line, so undo it: the log, Inventory.observe and the clients get
    # the fragment as the server sent it. Say so, since the repair has
    # already logged a "fixed to" line for the edit being undone.
    server_string.replace(unrepaired) if unrepaired
    undone = unrepaired ? ' (repair logged above undone)' : ''
    Lich.log "warning: stream desync (#{e.message}); resetting XMLData#{undone}: #{server_string.inspect}"
    XMLData.reset
    return
  end

  stripped_server = strip_xml(server_string, type: "main")

  # Process game-specific data using instance
  if @game_instance && Module.const_defined?(:GameLoader)
    @game_instance.process_game_specific_data(server_string, stripped_server)
  end

  # Process downstream XML
  Script.new_downstream_xml(server_string) if defined?(Script)

  # Process stripped server string
  stripped_server.split("\r\n").each do |line|
    @buffer.update(line) if defined?(TESTING) && TESTING
    Script.new_downstream(line) if defined?(Script) && !line.empty?
  end
end

.puts(str) ⇒ String

Send a prefixed command and record its script-labelled client display. Guarded callers pass policy checks before a command is displayed.

Parameters:

  • str (String) —

    command without the client prefix

Returns:

  • (String) —

    upstream display record; not proof of game acceptance

Raises:



887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'documented/games.rb', line 887

def puts(str)
  script = Script.current
  if script&.file_name
    script_name = "#{script.custom? ? 'custom/' : ''}#{script.name}"
  else
    script_name = script&.name || '(unknown script)'
  end

  guarded = script.respond_to?(:check_execution_guard!) &&
            script.respond_to?(:execution_guard_active?) && script.execution_guard_active?
  if guarded
    # Rejected guarded commands must not appear as sent. Snapshot both
    # display and wire strings so callback edits cannot change history.
    str = str.to_s.dup.freeze
    wire_command = "#{$cmd_prefix}#{str}".freeze
    _puts wire_command
  end

  $_CLIENTBUFFER_.push "[#{script_name}]#{$SEND_CHARACTER}#{guarded ? wire_command : "#{$cmd_prefix}#{str}"}\r\n"

  unless script&.silent
    respond "[#{script_name}]#{$SEND_CHARACTER}#{str}\r\n"
  end

  _puts "#{$cmd_prefix}#{str}" unless guarded
  $_LASTUPSTREAM_ = "[#{script_name}]#{$SEND_CHARACTER}#{str}"
end

.read_server_string(read_timeout: READ_TIMEOUT_SECONDS) ⇒ String, ...

Reads one game-server line after an explicit readiness wait.

Ruby does not reliably surface SO_RCVTIMEO through TCPSocket#gets on every supported platform. Waiting on #wait_readable first makes the reader's no-data timeout deterministic while preserving gets-based EOF handling. #wait_readable rather than a bare IO.select call so this works unchanged whether @socket is a direct-mode Socket (where it's equivalent to IO.select on a single descriptor -- both trigger on EOF too) or a Lich::Common::WebSocket::Stream (WEBSOCKET transport), whose #wait_readable also reports readiness for a line already sitting fully decoded in its buffer -- something a select on the raw, TLS-wrapped socket underneath it cannot see.

Parameters:

  • read_timeout (Numeric) (defaults to: READ_TIMEOUT_SECONDS) —

    seconds to wait for game socket data

Returns:

  • (String, nil, Object) —

    a server line, nil for EOF, or READ_TIMEOUT



1222
1223
1224
1225
1226
# File 'documented/games.rb', line 1222

def read_server_string(read_timeout: READ_TIMEOUT_SECONDS)
  return READ_TIMEOUT unless @socket.wait_readable(read_timeout)

  @socket.gets
end

.recognized_connection_disruption?(error) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns whether the error is a known connection or stream condition.

Recognized errors: timeouts, connection resets/aborts/pipe errors, TLS errors, WebSocket protocol errors, and game-stream desync. Used for logging classification.

Parameters:

  • error (StandardError) —

    the exception

Returns:

  • (Boolean)


1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
# File 'documented/games.rb', line 1809

def recognized_connection_disruption?(error)
  error.is_a?(Errno::ETIMEDOUT) ||
    error.is_a?(Errno::EWOULDBLOCK) ||
    error.is_a?(IO::TimeoutError) ||
    error.is_a?(Errno::ECONNRESET) ||
    error.is_a?(Errno::EPIPE) ||
    error.is_a?(Errno::ECONNABORTED) ||
    error.is_a?(OpenSSL::SSL::SSLError) ||
    error.is_a?(Lich::Common::WebSocket::Frame::ProtocolError) ||
    error.is_a?(GameStreamDesyncError)
end

.record_server_parser_timing(parse_time) ⇒ nil

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Records timing for one parse/dispatch cycle.

Parameters:

  • parse_time (Numeric) —

    elapsed seconds for this cycle

Returns:

  • (nil)


1035
1036
1037
1038
1039
1040
# File 'documented/games.rb', line 1035

def record_server_parser_timing(parse_time)
  @server_parser_last = parse_time
  @server_parser_total = @server_parser_total.to_f + parse_time.to_f
  @server_parser_max = parse_time if parse_time.to_f > @server_parser_max.to_f
  nil
end

.record_server_queue_dequeue(enqueued_monotonic_at = nil) ⇒ nil

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Records a dequeue event and computes queue wait time.

Increments @server_queue_dequeued, updates depth and timestamp, and if enqueued_monotonic_at is provided, calculates and records the wait time (from enqueue to dequeue) for averaging.

Parameters:

  • enqueued_monotonic_at (Numeric, nil) (defaults to: nil) —

    monotonic enqueue timestamp

Returns:

  • (nil)


1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
# File 'documented/games.rb', line 1014

def record_server_queue_dequeue(enqueued_monotonic_at = nil)
  @server_queue_dequeued = @server_queue_dequeued.to_i + 1
  depth = @server_queue&.length.to_i
  @server_queue_last_depth = depth
  @server_queue_last_dequeue_at = Time.now
  if enqueued_monotonic_at
    wait = Process.clock_gettime(Process::CLOCK_MONOTONIC) - enqueued_monotonic_at.to_f
    if wait >= 0.0
      @server_queue_last_wait = wait
      @server_queue_total_wait = @server_queue_total_wait.to_f + wait
      @server_queue_max_wait = wait if wait > @server_queue_max_wait.to_f
    end
  end
  nil
end

.record_server_queue_enqueue ⇒ nil

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Records an enqueue event in queue statistics.

Increments @server_queue_enqueued, updates depth tracking and timestamp.

Returns:

  • (nil)


952
953
954
955
956
957
958
959
# File 'documented/games.rb', line 952

def record_server_queue_enqueue
  @server_queue_enqueued = @server_queue_enqueued.to_i + 1
  depth = @server_queue&.length.to_i
  @server_queue_last_depth = depth
  @server_queue_max_depth = depth if depth > @server_queue_max_depth.to_i
  @server_queue_last_enqueue_at = Time.now
  nil
end

.record_server_reader_timing(hook_time:, enqueue_time:, process_time:) ⇒ nil

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Records timing samples from the socket-reader thread.

Captures elapsed seconds for hook execution, enqueue, and total reader-process time. Updates running max and total for average calculation.

Parameters:

  • hook_time (Numeric) —

    seconds spent in SocketReadHook.run

  • enqueue_time (Numeric) —

    seconds spent enqueuing to the parser queue

  • process_time (Numeric) —

    seconds elapsed from reader start to enqueue finish

Returns:

  • (nil)


990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
# File 'documented/games.rb', line 990

def record_server_reader_timing(hook_time:, enqueue_time:, process_time:)
  @server_reader_hook_last = hook_time
  @server_reader_hook_total = @server_reader_hook_total.to_f + hook_time.to_f
  @server_reader_hook_max = hook_time if hook_time.to_f > @server_reader_hook_max.to_f

  @server_reader_enqueue_last = enqueue_time
  @server_reader_enqueue_total = @server_reader_enqueue_total.to_f + enqueue_time.to_f
  @server_reader_enqueue_max = enqueue_time if enqueue_time.to_f > @server_reader_enqueue_max.to_f

  @server_reader_process_last = process_time
  @server_reader_process_total = @server_reader_process_total.to_f + process_time.to_f
  @server_reader_process_max = process_time if process_time.to_f > @server_reader_process_max.to_f
  nil
end

.record_shutdown_reason(reason, source:, detail: nil) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Records a shutdown event via the ShutdownCoordinator.

Parameters:

  • reason (Symbol) —

    the shutdown reason code

  • source (Symbol) —

    which thread/component initiated (e.g., :game_reader)

  • detail (Class, nil) (defaults to: nil) —

    optional error class for context



1768
1769
1770
1771
1772
1773
1774
# File 'documented/games.rb', line 1768

def record_shutdown_reason(reason, source:, detail: nil)
  return unless defined?(Lich::Common::ShutdownCoordinator)

  Lich::Common::ShutdownCoordinator.request(reason: reason, source: source, detail: detail)
rescue StandardError => e
  shutdown_log.warning("failed to record shutdown reason #{reason.inspect}: #{e.class}: #{e.message}")
end

.remote_eof? ⇒ Boolean

Returns whether the game server closed its side of the socket.

Returns:

  • (Boolean) —

    whether the game server closed its side of the socket



730
731
732
# File 'documented/games.rb', line 730

def remote_eof?
  @remote_eof == true
end

.repair_malformed_attributes_and_reparse(server_string) ⇒ String?

Ox reports "no attribute value" for two repairable malformations that scatter a tag into junk attributes: the settingsInfo space-not-found server bug, and a same-quote inside a quoted value (Simu's dynamic dialogs, e.g. title='Tsetem's Items'). Both raised in REXML and were repaired in the rescue; Ox tolerates them, so drive the repair off its error report -- only the rare flagged line pays the cost. Apply the repairs; if any changed the line, drop the junk the first parse committed and parse once more (never again, so it can't loop). The repair runs before the desync check, which then judges this second parse's errors: a line the repair fixes is kept, a truncated one still resets (and process_xml_data restores it from the returned original). Escaped '/" round-trip back to the literal char via XmlEntities.decode and the front-end's own entity decoding.

Parameters:

  • server_string (String) —

    the line, repaired in place

Returns:

  • (String, nil) —

    the line as received when a repair changed it, else nil



1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
# File 'documented/games.rb', line 1483

def repair_malformed_attributes_and_reparse(server_string)
  return unless XMLData.sax_parse_errors.any? { |message| NO_ATTRIBUTE_VALUE_ERROR.match?(message) }

  before = server_string.dup
  fix_invalid_settings_info(server_string)
  XMLCleaner.clean_nested_quotes(server_string)
  return if server_string == before # nothing to repair (e.g. a genuine valueless attribute)

  XMLData.reset
  XMLData.sax_parse_errors.clear
  Ox.sax_parse(XMLData, server_string, convert_special: false, symbolize: false, skip: :skip_none)
  before
end

.reset_server_queue_stats! ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Zeroes queue and timing statistics.

Clears counters for enqueue/dequeue events, queue depth tracking, hook/enqueue/ parse timings, and reader/parser thread status. Called at startup and when explicitly requested via server_queue_stats(reset: true).



742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File 'documented/games.rb', line 742

def reset_server_queue_stats!
  @server_queue_enqueued = 0
  @server_queue_dequeued = 0
  @server_queue_last_depth = @server_queue&.length.to_i
  @server_queue_max_depth = @server_queue_last_depth
  @server_queue_last_enqueue_at = nil
  @server_queue_last_dequeue_at = nil
  @server_queue_last_wait = nil
  @server_queue_max_wait = 0.0
  @server_queue_total_wait = 0.0
  @server_reader_hook_last = nil
  @server_reader_hook_max = 0.0
  @server_reader_hook_total = 0.0
  @server_reader_enqueue_last = nil
  @server_reader_enqueue_max = 0.0
  @server_reader_enqueue_total = 0.0
  @server_reader_process_last = nil
  @server_reader_process_max = 0.0
  @server_reader_process_total = 0.0
  @server_parser_last = nil
  @server_parser_max = 0.0
  @server_parser_total = 0.0
  nil
end

.rich_stream_rewrite(alt_string, capabilities) ⇒ String

The rewrites that depend on a client's capabilities.

The Saga-identity stream's inline block reaches only front ends that render it (:room_element, Saga); every other front end gets the legacy roomName/roomDesc layout it already handles. Rewritten after DownstreamHook.run, so script hooks see the block as the server sent it, and before the Wizard conversion (sf_to_wiz), which keys on that layout; the room-number display (process_room_information) handles either. They also get the legacy line the Saga-identity stream dropped, except Wizard/Avalon (GSL), which get exits from XMLParser's GSL codes and would see the line as a blank one.

Then the game's own rewrites (GameInstance#adapt_for_frontend): DragonRealms' links and creature bold go only to front ends that handle them (:game_links, :double_bold); the rest get the legacy line. After the rewrite, which keeps the parts' markup, and before sf_to_wiz, which turns each bold into a GSL code. GemStone keeps the base no-op.

Never modifies alt_string: the other capability sets start from it.

Parameters:

  • alt_string (String) —

    the server string after the downstream hooks

  • capabilities (Array<Symbol>) —

    the client's rich-stream capabilities

Returns:

  • (String) —

    alt_string itself when nothing applies, else a new string



1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
# File 'documented/games.rb', line 1583

def rich_stream_rewrite(alt_string, capabilities)
  if alt_string.include?('<room>') && !capabilities.include?(:room_element)
    alt_string = if Frontend.supports_gsl?
                   Lich::Common::RoomBlock.legacy_shape(alt_string)
                 else
                   Lich::Common::RoomBlock.legacy_shape_with_compass(alt_string)
                 end
  end
  alt_string = @game_instance.adapt_for_frontend(alt_string, capabilities) if @game_instance
  alt_string
end

.send_to_client(alt_string, clients = client_write_targets) ⇒ Object

Writes one string to each live client in clients.

Parameters:

  • alt_string (String) —

    the finished bytes

  • clients (Array) (defaults to: client_write_targets) —

    defaults to every client that receives game output



1655
1656
1657
# File 'documented/games.rb', line 1655

def send_to_client(alt_string, clients = client_write_targets)
  clients.each { |client| client.write(alt_string) if client.alive? }
end

.server_queue_stats(reset: false) ⇒ Hash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a snapshot of server-stream queue and timing statistics.

Computes averages from totals, converts timings to milliseconds, and reports thread status. Useful for monitoring parser performance and diagnosing stalls. Can optionally reset counters after collection.

Parameters:

  • reset (Boolean) (defaults to: false) —

    whether to zero statistics after this snapshot

Returns:

  • (Hash) —

    keys include depth, max_depth, enqueued, dequeued, *_wait_ms, *_max_ms, *_avg_ms, reader_status, parser_status



777
778
779
780
781
782
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# File 'documented/games.rb', line 777

def server_queue_stats(reset: false)
  depth = @server_queue&.length.to_i
  dequeued = @server_queue_dequeued.to_i
  last_wait = @server_queue_last_wait
  max_wait = @server_queue_max_wait.to_f
  avg_wait = dequeued.positive? ? @server_queue_total_wait.to_f / dequeued : 0.0
  enqueued = @server_queue_enqueued.to_i
  hook_last = @server_reader_hook_last
  hook_max = @server_reader_hook_max.to_f
  hook_avg = enqueued.positive? ? @server_reader_hook_total.to_f / enqueued : 0.0
  enqueue_last = @server_reader_enqueue_last
  enqueue_max = @server_reader_enqueue_max.to_f
  enqueue_avg = enqueued.positive? ? @server_reader_enqueue_total.to_f / enqueued : 0.0
  process_last = @server_reader_process_last
  process_max = @server_reader_process_max.to_f
  process_avg = enqueued.positive? ? @server_reader_process_total.to_f / enqueued : 0.0
  parser_last = @server_parser_last
  parser_max = @server_parser_max.to_f
  parser_avg = dequeued.positive? ? @server_parser_total.to_f / dequeued : 0.0
  stats = {
    depth: depth,
    last_depth: @server_queue_last_depth.to_i,
    max_depth: [@server_queue_max_depth.to_i, depth].max,
    enqueued: enqueued,
    dequeued: dequeued,
    last_wait: last_wait,
    max_wait: max_wait,
    avg_wait: avg_wait,
    last_wait_ms: last_wait ? (last_wait * 1000.0).round(3) : nil,
    max_wait_ms: (max_wait * 1000.0).round(3),
    avg_wait_ms: (avg_wait * 1000.0).round(3),
    reader_hook_last_ms: hook_last ? (hook_last * 1000.0).round(3) : nil,
    reader_hook_max_ms: (hook_max * 1000.0).round(3),
    reader_hook_avg_ms: (hook_avg * 1000.0).round(3),
    reader_enqueue_last_ms: enqueue_last ? (enqueue_last * 1000.0).round(3) : nil,
    reader_enqueue_max_ms: (enqueue_max * 1000.0).round(3),
    reader_enqueue_avg_ms: (enqueue_avg * 1000.0).round(3),
    reader_process_last_ms: process_last ? (process_last * 1000.0).round(3) : nil,
    reader_process_max_ms: (process_max * 1000.0).round(3),
    reader_process_avg_ms: (process_avg * 1000.0).round(3),
    parser_process_last_ms: parser_last ? (parser_last * 1000.0).round(3) : nil,
    parser_process_max_ms: (parser_max * 1000.0).round(3),
    parser_process_avg_ms: (parser_avg * 1000.0).round(3),
    last_enqueue_at: @server_queue_last_enqueue_at,
    last_dequeue_at: @server_queue_last_dequeue_at,
    reader_status: @reader_thread&.status,
    parser_status: @thread&.status
  }
  reset_server_queue_stats! if reset
  stats
end

.set_game_instance(game_type) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Instantiates the game-specific handler for the identified game.

Called after the server identifies itself (via XMLData.game). Dispatches to GameInstanceFactory.create, which returns the appropriate subclass (Gemstone::GameInstance or DragonRealms::GameInstance).

Parameters:

  • game_type (String) —

    the game identifier ("GS" or "DR")



628
629
630
# File 'documented/games.rb', line 628

def set_game_instance(game_type)
  @game_instance = GameInstanceFactory.create(game_type)
end

.settings_init_needed? ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns whether the client settings record needs initialization.

Set to true when the settingsInfo XML is repaired from the space-not-found bug, signaling gameloader's PostLoad hook to seed a valid client entry.

Returns:

  • (Boolean)


582
583
584
# File 'documented/games.rb', line 582

def settings_init_needed?
  @@settings_init_needed
end

.shutdown_log ⇒ Lich::Common::ShutdownLog

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the ShutdownLog for thread-safe error recording.



1780
1781
1782
# File 'documented/games.rb', line 1780

def shutdown_log
  Lich::Common::ShutdownLog
end

.shutdown_reason_for_thread_exit(error) ⇒ Symbol

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Maps an error to a shutdown-coordinator reason code.

Used by the reader thread to record why it is exiting (timeout, connection error, protocol error, desync, queue overflow, etc.).

Parameters:

  • error (StandardError) —

    the exception

Returns:

  • (Symbol) —

    a reason key (e.g., :game_timeout, :connection_reset)



1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
# File 'documented/games.rb', line 1738

def shutdown_reason_for_thread_exit(error)
  case error
  when Errno::ETIMEDOUT, Errno::EWOULDBLOCK, IO::TimeoutError
    :game_timeout
  when Errno::ECONNRESET
    :connection_reset
  when Errno::EPIPE
    :connection_pipe
  when Errno::ECONNABORTED
    :connection_aborted
  when OpenSSL::SSL::SSLError
    :connection_tls_error
  when Lich::Common::WebSocket::Frame::ProtocolError
    :websocket_protocol_error
  when GameStreamDesyncError
    :game_stream_desync
  when ServerQueueOverflow
    :unrecoverable_game_thread_error
  else
    :unrecoverable_game_thread_error
  end
end

.start_cli_scripts ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Starts scripts specified via --start-scripts command-line argument.

Parses --start-scripts=script1,script2 and calls Script.start on each. Sets @cli_scripts to true after processing, so this runs only once. Logs the logged-in character and game.

Called when XMLData.name is populated (after autostart check).



1377
1378
1379
1380
1381
1382
1383
1384
1385
# File 'documented/games.rb', line 1377

def start_cli_scripts
  if (arg = ARGV.find { |a| a =~ /^\-\-start\-scripts=/ })
    arg.sub('--start-scripts=', '').split(',').each do |script_name|
      Script.start(script_name)
    end
  end
  @cli_scripts = true
  Lich.log("info: logged in as #{XMLData.game}:#{XMLData.name}")
end

.start_main_thread ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Initializes the server-stream queue and spawns reader and processor threads.

Creates a fresh SizedQueue and resets stats, then starts the socket-reader thread (which pulls raw lines from the game socket) and the server-processor thread (which parses and hooks into those lines). Both run until close or an error.



939
940
941
942
943
944
# File 'documented/games.rb', line 939

def start_main_thread
  @server_queue = SizedQueue.new(SERVER_QUEUE_CAPACITY)
  reset_server_queue_stats!
  start_socket_reader_thread
  start_server_processor_thread
end

.start_server_processor_thread ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Spawns the thread that dequeues, parses, and hooks server strings.

Pops items from @server_queue and calls process_server_string on each, recording timing and queue statistics. Exits cleanly on nil (end-of-queue signal from reader thread), or on unrecoverable error (logs and records shutdown reason).



1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
# File 'documented/games.rb', line 1179

def start_server_processor_thread
  @thread = Thread.new do
    begin
      loop do
        item = @server_queue.pop
        break if item.nil?

        server_string, enqueued_monotonic_at, ingress_monotonic_at = unwrap_server_queue_item(item)
        record_server_queue_dequeue(enqueued_monotonic_at)
        parse_started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
        begin
          Thread.current.thread_variable_set(:lich_game_ingress_time, ingress_monotonic_at)
          process_server_string(server_string)
        ensure
          Thread.current.thread_variable_set(:lich_game_ingress_time, nil)
        end
        record_server_parser_timing(Process.clock_gettime(Process::CLOCK_MONOTONIC) - parse_started)
      end
    rescue StandardError => e
      log_error("Error processing server string", e)
      record_shutdown_reason(:unrecoverable_game_thread_error, source: :game_parser, detail: e.class)
      @socket.close rescue nil
    end
  end
  @thread.name = 'game parser' if @thread.respond_to?(:name=)
  @thread.priority = 4
end

.start_socket_reader_thread ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Spawns the thread that reads raw game-server lines and enqueues them.

Runs read_server_string in a loop with timeout handling: up to MAX_CONSECUTIVE_READ_TIMEOUTS silent retries before treating the connection as dead. Detects EOF, connection errors, and truncated/desynced fragments. On error, records the shutdown reason and halts the thread. Passes each line through SocketReadHook (if defined) before enqueuing.



1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
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
1139
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
# File 'documented/games.rb', line 1070

def start_socket_reader_thread
  @reader_thread = Thread.new do
    consecutive_timeouts = 0
    max_consecutive_timeouts = MAX_CONSECUTIVE_READ_TIMEOUTS

    begin
      while true
        begin
          server_string = read_server_string

          if server_string.equal?(READ_TIMEOUT)
            raise IO::TimeoutError, "no game data for #{READ_TIMEOUT_SECONDS} seconds"
          end

          consecutive_timeouts = 0

          # Break if socket closed (gets returns nil)
          if server_string.nil?
            @remote_eof = true
            record_shutdown_reason(:game_eof, source: :game_reader)
            break
          end

          reader_process_started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
          received_at = Time.now
          monotonic_received_at = reader_process_started
          @last_recv = received_at
          @_buffer.update(server_string) if defined?(TESTING) && TESTING
          hook_started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
          Lich::Common::SocketReadHook.run(
            server_string,
            received_at: received_at,
            monotonic_received_at: monotonic_received_at
          ) if defined?(Lich::Common::SocketReadHook)
          hook_finished = Process.clock_gettime(Process::CLOCK_MONOTONIC)
          enqueue_started = hook_finished
          enqueue_server_string(
            server_string,
            enqueue_started,
            ingress_monotonic_at: monotonic_received_at
          )
          enqueue_finished = Process.clock_gettime(Process::CLOCK_MONOTONIC)
          record_server_reader_timing(
            hook_time: hook_finished - hook_started,
            enqueue_time: enqueue_finished - enqueue_started,
            process_time: enqueue_finished - reader_process_started
          )
        rescue Errno::ETIMEDOUT, Errno::EWOULDBLOCK, IO::TimeoutError
          consecutive_timeouts += 1

          shutdown_log.info("socket read timeout #{consecutive_timeouts}/#{max_consecutive_timeouts} (no game data for #{READ_TIMEOUT_SECONDS}s)")

          if consecutive_timeouts >= max_consecutive_timeouts
            total_timeout = total_read_timeout_seconds(max_consecutive_timeouts)
            shutdown_log.warning("game connection timed out after #{max_consecutive_timeouts} consecutive read timeouts (#{total_timeout}s)")
            raise IO::TimeoutError, "no game data for #{total_timeout} seconds"
          end

          # Check if socket is still alive
          if @socket.closed?
            shutdown_log.info("game socket is closed; exiting server thread")
            break
          end

          # Small sleep before retry
          sleep 0.1
          retry
        rescue Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED, OpenSSL::SSL::SSLError => conn_error
          # Connection was reset/broken - these are fatal
          shutdown_log.info("connection error: #{conn_error.class} - #{conn_error.message}")
          raise conn_error
        end
      end
    rescue StandardError => e
      if intentional_shutdown_close_error?(e)
        shutdown_log.info("server thread exiting after orderly user shutdown")
        next
      end

      # Handle any other errors
      should_continue = handle_thread_error(e)
      # Only retry if handle_thread_error says it's safe and socket is still open
      if should_continue && !@socket.closed? && $_CLIENT_.alive?
        shutdown_log.debug("retrying server thread after error")
        consecutive_timeouts = 0 # Reset counter on retry
        sleep 1 # Brief pause before retry
        retry
      else
        reason = shutdown_reason_for_thread_exit(e)
        record_shutdown_reason(reason, source: :game_reader, detail: e.class)
        shutdown_log.info("server thread exiting due to #{reason}")
      end
    ensure
      @server_queue << nil if @server_queue && @thread&.alive?
    end
  end
  @reader_thread.name = 'game socket reader' if @reader_thread.respond_to?(:name=)
  @reader_thread.priority = 5
end

.start_wrap_thread ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Starts a thread that sends 'look' if autostart takes too long.

Vacuum the database if due, then spawn a thread that waits up to 6 seconds for the autostart script to complete. If the script has not set @@autostarted by then, send 'look' to prompt for a room description. Ensures the player sees room data even if autostart hangs or fails.



703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
# File 'documented/games.rb', line 703

def start_wrap_thread
  begin
    Lich.db_vacuum_if_due!(months: 6)
  rescue => e
    Lich.log "db_maint(startup): #{e.class}: #{e.message}"
  end

  @wrap_thread = Thread.new do
    @last_recv = Time.now
    until @@autostarted || (Time.now - @last_recv >= 6)
      break if @@autostarted
      sleep 0.2
    end

    puts 'look' unless @@autostarted
  end
end

.total_read_timeout_seconds(timeout_count = MAX_CONSECUTIVE_READ_TIMEOUTS) ⇒ Integer

Returns total elapsed no-data seconds represented by count.

Parameters:

  • timeout_count (Integer) (defaults to: MAX_CONSECUTIVE_READ_TIMEOUTS) —

    number of consecutive read waits

Returns:

  • (Integer) —

    total elapsed no-data seconds represented by count



1230
1231
1232
# File 'documented/games.rb', line 1230

def total_read_timeout_seconds(timeout_count = MAX_CONSECUTIVE_READ_TIMEOUTS)
  READ_TIMEOUT_SECONDS * timeout_count
end

.unwrap_server_queue_item(item) ⇒ Array<(String, Numeric, Numeric)>, Array<(String, nil, nil)>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Normalizes a server-queue item into [server_string, enqueued_monotonic_at, ingress_monotonic_at].

Handles legacy 2-element tuples (assuming enqueue time is also ingress time), 3-element tuples, and bare strings. Returns a 3-tuple for uniform processing.

Parameters:

  • item (Array, String) —

    a queue entry

Returns:



1050
1051
1052
1053
1054
1055
1056
1057
1058
# File 'documented/games.rb', line 1050

def unwrap_server_queue_item(item)
  if item.is_a?(Array) && item.length == 3 && item[1].is_a?(Numeric)
    item
  elsif item.is_a?(Array) && item.length == 2 && item[1].is_a?(Numeric)
    [item[0], item[1], item[1]]
  else
    [item, nil, nil]
  end
end