Skip to content

Architecture and Internals

buntatoes edited this page Nov 28, 2026 · 1 revision

Architecture and Internals

RubyLock RPC is engineered as a zero-dependency pure-Ruby runtime (Ruby >= 3.2.0) paired with a minimal optional native C host launcher for clean desktop integration on Windows and Linux. Every subsystem — TOML parsing, Steam library inspection, Win32 process snapshots, Windows tray menus, Linux D-Bus wire protocol serialization, Discord IPC framing, and GitHub Release tar extraction — uses only the Ruby standard library.

Runtime Architecture & Threading Model

When started in normal daemon mode, RubylockRpc::Application#run acquires the single-instance loopback socket lock, loads and migrates config.toml, initializes RpcLogger, optionally launches Deadlock, and coordinates up to five concurrent execution contexts sharing a mutex-protected GameState and SharedBools:

flowchart TD
    Entry["bin/rubylock-rpc or Native Host Wrapper"] --> App["RubylockRpc::Application"]
    App --> Lock["Single-Instance TCP Lock (localhost:47782)"]
    App --> Cfg["ConfigManager + Toml (config.toml)"]
    App --> Steam["Steam Auto-Detection (libraryfolders.vdf / Registry)"]
    App --> Launch["Launcher (Steam -applaunch 1422450 -condebug)"]

    App --> T1["Thread: LogWatcher (tails console.log every 500ms)"]
    App --> T2["Thread: ProcessWatcher (polls deadlock.exe every 3s)"]
    App --> T3["Thread: Tray (Win32 Message Loop or Linux D-Bus Loop)"]
    App --> T4["Thread: Updater (one-shot GitHub Release check)"]
    App --> Main["Main Thread: RPC Loop (every 5s)"]

    T1 -->|Mutex| State["GameState"]
    T2 -->|Mutex| State
    T3 -->|Mutex| Shared["SharedBools"]
    T3 -.->|ConfigManager.set_config_value| Cfg
    Main -->|Reads| State
    Main -->|Reads| Shared
    Main --> Hero["HeroCache (Deadlock API + Static Fallback)"]
    Main --> IPC["DiscordIpcClient (Named Pipe / UNIX Socket)"]
    Main -.->|update_status| T3
Loading

Thread Breakdown

Thread Module Cadence Responsibility
Main Thread Application#run_rpc_loop discord_update_interval_s (default 5s, min 1s) Snapshots GameState and SharedBools, detects game close, fetches/caches hero portraits, builds Discord Rich Presence payloads, sends SET_ACTIVITY over IPC, and updates tray tooltip/status.
Log Watcher LogWatcher#run game_log_poll_interval_ms (default 500ms, min 50ms) Waits for console.log, performs up to 10 MiB initial catch-up resync, tails appended lines, handles log truncation and 300-second crash staleness, and updates GameState.
Process Watcher ProcessWatcher.run 3s (POLL_INTERVAL_S) Enumerates OS processes (CreateToolhelp32Snapshot on Windows, /proc on Linux) for deadlock.exe to transition NOT_RUNNING -> MAIN_MENU and reset state on game exit.
System Tray WindowsTray / LinuxDbusTray Event-driven (50ms PeekMessageW loop on Windows; blocking UNIXSocket read on Linux) Renders persistent tray icon, live status tooltip, and context menu actions (dispatched on short-lived worker threads).
Background Updater Updater.check_and_apply Once on startup (unless --no-update-check) Checks api.github.com/repos/buntatoes/rubylock-rpc/releases/latest, prompts or auto-installs newer releases, and invokes clean shutdown before Windows installer handoff.

Module Map

The core codebase lives in bin/rubylock-rpc and 13 Ruby files under lib/:

File Primary Types / Modules Role
bin/rubylock-rpc CLI entrypoint Invokes RubylockRpc::Application.new(ARGV).run and exits with its return code.
lib/rubylock_rpc.rb RubylockRpc, Application Version (1.3.0), default Discord App ID, CLI flag dispatch, single-instance lock, thread orchestration, signal traps (INT/TERM), and main RPC update loop.
lib/rubylock_rpc/config.rb HeroPortraitStyle, GeneralConfig, StatusStrings, PresenceConfig, ImagesConfig, Config, SharedBools, ConfigManager Config structs, default TOML generation, schema migration (CURRENT_CONFIG_VERSION = 6), thread-safe live toggle store (SharedBools), and {var} template substitution.
lib/rubylock_rpc/toml.rb Toml Zero-dependency TOML parser and serializer supporting [section] and [nested.section] tables, double- and single-quoted strings, escapes (\", \\, \n, \t, \r), booleans, signed integers, and # comments.
lib/rubylock_rpc/logger.rb RpcLogger Thread-safe logger (debug, info, warn, error) writing ISO-8601 UTC timestamps (iso8601(7)) to both $stdout and <data_dir>/logs/rubylock-rpc.log, plus data directory resolution.
lib/rubylock_rpc/game_state.rb MatchMode, GamePhase, GameState In-memory Deadlock state machine, monotonic match timer (CLOCK_MONOTONIC), hero lock-in guard, party headcount reconciliation (capped at 6), and Discord status line formatting.
lib/rubylock_rpc/log_watcher.rb LogWatcher Regex-based -condebug console log parser, 10 MiB initial resync, truncation recovery, stale-match crash detector, and match mode inference.
lib/rubylock_rpc/hero_api.rb HeroData, HeroCache Deadlock API HTTPS client (api.deadlock-api.com), in-memory per-hero cache (cleared when portrait style changes), and 52-entry offline hero fallback mapping.
lib/rubylock_rpc/discord_ipc.rb DiscordIpcClient Pure-Ruby Discord Rich Presence IPC client over Windows Named Pipes and Linux UNIX Domain Sockets, binary framing, and activity payload builder.
lib/rubylock_rpc/steam.rb Steam Cross-platform Steam root discovery, libraryfolders.vdf + appmanifest_1422450.acf parsing, game/citadel validation, and steam executable resolution.
lib/rubylock_rpc/process_watcher.rb ProcessWatcher, Win32Snapshot Native zero-subprocess process detection (kernel32.dll via Fiddle on Windows; /proc/[0-9]*/comm and cmdline on Linux).
lib/rubylock_rpc/launcher.rb Launcher Launches Deadlock either via Steam (-applaunch 1422450 -condebug) or via --launch-with-command -- %command% (ensuring -condebug is appended).
lib/rubylock_rpc/tray.rb Tray, NullTray, DbusWire, LinuxDbusTray, WindowsTray Persistent native system tray icons and popup menus for Windows (Shell_NotifyIconW) and Linux (pure-Ruby D-Bus StatusNotifierItem + DBusMenu).
lib/rubylock_rpc/updater.rb Updater, ReleaseInfo, Win32Dialog Verified GitHub Releases updater with HTTPS host allowlist, magic-byte validation, path-traversal-safe tar extraction, and native GUI dialogs.

Standard Library Only — Zero External Gems

rubylock-rpc.gemspec declares zero runtime gem dependencies. Every external library call is part of Ruby's bundled standard library:

  • Networking & JSON: socket, net/http, uri, json, securerandom
  • Archives & Filesystem: zlib, rubygems/package, fileutils, tmpdir, open3
  • OS & Native Interop: fiddle, fiddle/import, win32/registry (Windows only)
  • Data & Time: set, time

Native Host Wrapper (packaging/host/rubylock_rpc_host.c)

Prebuilt packages include a small C host binary compiled from packaging/host/rubylock_rpc_host.c so desktop launchers and shortcuts behave like native applications without console flicker:

  • Windows (rubylock-rpc.exe, compiled with -mwindows):
    • Resolves its own directory via GetModuleFileNameA.
    • Inspects argv to distinguish CLI flags (--help, -h, --version, -v, --generate-config, --check-update, --update, --uninstall) from normal GUI/tray launches.
    • Normal launch: searches <app_dir>\ruby\bin\rubyw.exe, PATH, and C:\Ruby*-x64\bin\rubyw.exe (falling back to ruby.exe), spawns <ruby> "<app_dir>\bin\rubylock-rpc" ... with CREATE_NO_WINDOW, and returns immediately so no terminal window flashes.
    • CLI launch: searches for ruby.exe, spawns without CREATE_NO_WINDOW, waits with WaitForSingleObject, and propagates the Ruby process's exit code.
    • Shows a MessageBoxA error if Ruby 3.2+ cannot be located.
  • Linux (rubylock-rpc ELF binary):
    • Resolves its real location via readlink("/proc/self/exe", ...) (following symlinks from $HOME/.local/bin/rubylock-rpc into $HOME/.local/share/rubylock-rpc).
    • Builds <dir>/bin/rubylock-rpc and calls execvp("ruby", ...) to replace the wrapper process cleanly with Ruby.

Custom TOML Engine (lib/rubylock_rpc/toml.rb)

Rather than depending on a third-party TOML gem, RubylockRpc::Toml provides a focused, round-trip-safe parser and serializer:

  • Comment stripping (strip_comment): Tracks single-quoted, double-quoted, and backslash-escaped string states so # inside quoted values is preserved while trailing comments are stripped.
  • Nested tables: Splits [a.b] headers on . to build nested Ruby hashes.
  • Windows path safety: When serializing strings containing backslashes (\) and no single quotes ('), format_value emits single-quoted TOML literal strings ('C:\Path\To\Deadlock') so Windows paths round-trip cleanly without double-escaping.

Thread Synchronization & Dirty Signaling (SharedBools)

Settings toggled live from the system tray (exit_when_game_closes, auto_update, as well as presence fields exposed via SharedBools) are guarded by a dedicated Mutex. Every setter updates the value and sets @settings_dirty = true.

On each iteration of the main RPC loop, if last_state == current && !shared.consume_dirty!, the loop skips redundant SET_ACTIVITY calls to Discord. When a setting changes, consume_dirty! returns true and forces an immediate presence refresh on the next cycle.


Logging (RpcLogger)

RpcLogger.init creates <data_dir>/logs/rubylock-rpc.log in write mode ("w:UTF-8", sync = true) on each run, truncating the previous session's log so logs stay compact and bounded. Every log entry is written atomically under a mutex to both $stdout and the log file in the format:

2026-01-15T18:42:10.1234567Z [INFO] [rpc] phase=in_match hero=hero_haze details="Playing as Haze" state="Standard Match - 05:10" party=1 account=12345678 statlocker=disabled