Skip to content

Server Architecture

pinjinx edited this page Oct 23, 2026 · 2 revisions

Rein uses a lightweight Node.js HTTP server attached via Vite middleware in development or running inside standalone Nitro in production. It powers all backend functionality, including WebRTC REST/SSE signaling, input dispatching, authentication, configuration, log streaming, clipboard synchronization, bidirectional file sharing, and screen and audio capture management.


Server Entry Point & Lifecycle

The server routes and background engines are mounted by calling attachSignalingRoutes(server) from src/server/signalling/server.ts.

Development Mode (Vite Plugin)

In vite.config.ts, a custom plugin hooks into Vite's dev and preview servers:

// vite.config.ts (simplified)
{
  name: "rein-server",
  async configureServer(server) {
    attachSignalingRoutes(server)
  },
  async configurePreviewServer(server) {
    attachSignalingRoutes(server)
  }
}

Vite injects Rein's handleApiRequest directly into server.middlewares.

Production Mode (Nitro Plugin)

In production, TanStack Start compiles with Nitro. Rein includes a Nitro runtime plugin (src/server/nitro-plugin.ts) that intercepts the HTTP server's initial listen() call:

// src/server/nitro-plugin.ts
export default function (_nitroApp: any) {
  const origListen = net.Server.prototype.listen
  net.Server.prototype.listen = function (this: any, ...args: any[]) {
    net.Server.prototype.listen = origListen
    attachSignalingRoutes(this)
    return origListen.apply(this, args)
  }
}

This attaches all /api/* route handlers, starts the WebRTCManager, and spawns the GstManager automatically when the compiled server launches.


Modular Directory Structure

The server implementation is structured into focused modules under src/server/:

src/server/
├── signalling/
│   ├── server.ts              # HTTP route router, middleware attachment, lifecycle
│   ├── webRTC.ts              # werift WebRTCManager, track setup, session coordinator
│   ├── utils.ts               # requireAuth, parseJsonBody, json response helpers
│   └── handlers/
│       ├── rtc.ts             # REST signaling handlers (offer, answer, ice, session-sse)
│       ├── udpSocket.ts       # UdpSocketManager: dual sockets on 5004 (video) & 5006 (audio)
│       ├── sessionStore.ts    # ClientSession map, disconnect grace timers, session events
│       ├── fileShare.ts       # Directory browser, multipart file uploads, downloads, SSE
│       └── debug.ts           # Session snapshots, RTT latency reporting, SSE logs
├── drivers/                   # Cross-platform native input injectors powered by @imxade/inject (Linux, macOS, Windows)
├── gstreamer/                 # GstManager, CaptureProviders, D-Bus portal integration
├── clipboard.ts               # Host OS clipboard read/write (pbcopy/pbpaste, PS, wl-clipboard)
├── InputHandler.ts            # Input validation, 8ms throttle, acceleration, driver dispatch
├── tokenStore.ts              # Cryptographic tokens, timing-safe compare, tokens.json persistence
├── nitro-plugin.ts            # Production Nitro HTTP server listener patch
├── constants.ts               # Server port, throttle, buffer, and packet constants
└── types.ts                   # Core input message and driver interface types

API Routes Reference

Category Method Endpoint Purpose Authentication
Host GET /api/host/ip Returns host LAN IP address Token or localhost
POST /api/host/start Starts the GStreamer capture engine Token or localhost
POST /api/host/stop Stops the GStreamer capture engine Token or localhost
POST /api/host/restart Full engine restart (GStreamer + WebRTC) Token or localhost
GET /api/host/status Current host engine status (stopped, starting, running, error) Token or localhost
Auth POST /api/auth/token Returns or generates active authentication token Localhost only (403 for remote)
RTC Signaling POST /api/rtc/offer Initiates session, creates tracks/channels, returns SDP offer Token or localhost
POST /api/rtc/answer Applies viewer SDP answer to session Token or localhost
POST /api/rtc/ice Submits viewer ICE candidate Token or localhost
GET /api/rtc/session-sse SSE stream for host ICE candidates and errors Token or localhost
DELETE /api/rtc/session Closes and cleans up an active session Token or localhost
Config GET /api/config Reads current server configuration Token or localhost
POST /api/config Updates runtime input & persisted server config Token or localhost
Clipboard POST /api/clipboard/copy Triggers copy on host and returns host clipboard text Token or localhost (active session required)
POST /api/clipboard/paste Writes text to host clipboard and triggers paste Token or localhost (active session required)
Files GET /api/files/browse Lists host directories and files at ?path= Token or localhost
POST /api/files/upload Uploads file to host uploadDir Token or localhost
GET /api/files/list Returns list of uploaded shared files Token or localhost
GET /api/files/download Streams file bytes by ?path= or ?fileId= Token or localhost
DELETE /api/files Deletes shared file by ?fileId= Token or localhost
GET /api/files/events SSE stream for file events (incoming-file, file-deleted) Token or localhost
Debug GET /api/debug/sessions Returns active session snapshots & telemetry Token or localhost
POST /api/debug/report-latency Receives client RTT latency telemetry Token or localhost
GET /api/debug/logs SSE stream for live Winston server logs Token or localhost

UDP Socket Manager (UdpSocketManager)

The UdpSocketManager (src/server/signalling/handlers/udpSocket.ts) owns the local loopback UDP sockets that receive RTP streams from GStreamer:

  1. Video Socket: Binds to 127.0.0.1:5004 (RTP_PORT) with a 4 MB socket receive buffer. Incoming H.264 RTP packets are broadcast to client.videoTrack.writeRtp(msg) across all active sessions.
  2. Audio Socket: Binds to 127.0.0.1:5006 (RTP_PORT_AUDIO) with a 512 KB socket receive buffer. Incoming Opus RTP packets are broadcast to client.audioTrack.writeRtp(msg) across all active sessions.
  3. Resilience & Rebind: Both sockets are marked .unref() so they do not block clean process exit. If a socket errors, onFailure() triggers a rebind loop with exponential backoff (500ms to 10s) until successfully rebound.

Log Streaming (SseTransport)

Rein includes a custom Winston stream transport (SseTransport) in src/server/signalling/server.ts that captures log output and streams it via Server-Sent Events (SSE) to clients connected to /api/debug/logs.

class SseTransport extends winston.transports.Stream {
  constructor() {
    // Intercepts log chunks, formats SSE payloads, maintains a 500-entry replay buffer,
    // and writes to all active sseClients connections.
  }
}

When the Debug Dashboard (/debug) opens, connecting to /api/debug/logs immediately replays historical log entries before streaming live log events.


Configuration & Persistence

Rein distinguishes between read-only application defaults and user-writable configuration:

  • Template Defaults: src/server-config.json stores initial defaults.
  • User Writable Config: Located in a user-owned writable path resolved via src/utils/configHelper.ts:
    1. REIN_DATA_DIR environment variable (if set, e.g. Electron app.getPath('userData'))
    2. $XDG_CONFIG_HOME/rein/server-config.json
    3. ~/.config/rein/server-config.json

When updates are posted to POST /api/config:

  • Input settings (sensitivity, invertScroll) are applied immediately in memory to all active InputHandler instances via webrtcManager.updateConfig().
  • Pipeline settings (framerate, streamQuality, uploadDir) are persisted to the user config file. If GStreamer settings changed (framerate or streamQuality), the server automatically triggers restartServer() so the GStreamer pipeline takes effect with the new parameters.

Host Lifecycle & Error Recovery

Host status represents the combined health of the GStreamer capture engine and the UDP WebRTC relay:

stopped ──► starting ──► running
               │            │
               ▼            ▼
             error ◄── (UDP or GStreamer failure)

getEffectiveHostStatus() returns "error" if GStreamer fails to spawn or if UdpSocketManager encounters an unrecoverable socket bind failure.

POST /api/host/restart coordinates a clean restart:

  1. Stops the active GStreamer process gracefully.
  2. Shuts down active WebRTC peer connections.
  3. Pauses 200ms to ensure the OS releases bound UDP ports (5004, 5006).
  4. Creates fresh WebRTCManager and GstManager instances and starts the pipeline.

Clone this wiki locally