Table of Contents

Login Server System

View this file on GitHub

Short description: Manages login-server database registration, HMAC signing-key provisioning, authenticator configuration, and periodic heartbeat liveness reporting for a FishMMO login server instance.

Table of Contents

Overview

The Login Server system manages the full lifecycle of a FishMMO login server instance inside the database. On startup it resolves the server's identity (name + public address), registers a login-server row in the database, generates an HMAC signing key for authentication token issuance, persists that key, and configures the ServerAuthenticator so it can sign tokens. A periodic heartbeat pulse is then scheduled to keep the server's liveness timestamp current.

Initialization is asynchronous: InitializeOnceAsync awaits its database work rather than blocking, and Server starts the transport from the completion callback. The Unity main thread is what drains async continuations, so blocking it there would stall the very work being awaited — the failure mode was a live LoginServer that never bound its port. If registration fails, Server retries with backoff (5 attempts by default) and then exits the process so a supervisor can restart it. Heartbeat pulses are dispatched through AsyncWorkerData so the main update loop stays non-blocking.

On shutdown the system performs an orderly cleanup: it zeros the in-memory signing key, deletes the signing-key row from the database, deregisters the login-server record, and resets runtime state.

Supported Platforms

Platform Supported Notes
Windows Yes Fully supported as a server host
Linux Yes Fully supported as a server host
WebGL N/A Server-only component; not applicable to browser builds

Engine: Unity 6.6 (6000.6.8f1)
Scripting backend: IL2CPP

Features

  • Database registration — Persists a login-server row (name, address, port) by awaiting ILoginServerService.PersistAsync; Server bounds the whole attempt and retries with backoff.
  • HMAC signing-key generation — Generates a cryptographically random HMAC key (CryptoHelper.GenerateKey) and persists it via ILoginServerSigningKeyService.UpsertAsync.
  • Authenticator configuration — Injects the HMAC key and login-server ID into the ServerAuthenticator so it can issue signed authentication tokens.
  • Periodic heartbeat — Schedules OnPeriodicPulse through IPeriodicUpdateSystem at a configurable cadence (default 5 s).
  • Async heartbeat dispatch — Heartbeat database calls are enqueued to AsyncWorkerData via TryEnqueueAsyncWork, keeping the main thread free.
  • One heartbeat in flight — ILoginServerRuntimeData.TryBeginPulse gates the pulse; the gate is released when the pulse finishes (or at once if it could not be queued). While the database is stalled a pulse can outlast the interval, and each new one used to start regardless, piling identical writes onto a database that was not keeping up; a skipped pulse is covered by the one still running.
  • Signing-key rotation — When the active key has been in use for signingKeyRotationHours (default 24), the next pulse rotates it on the async worker, guarded against re-entry. The key's age is measured on MonotonicClock, so a stepped host clock neither rotates early nor postpones rotation. The previous key is kept for verifying tokens already issued.
  • Bandwidth recording — Starts a ServerBandwidthRecorder once initialised (one row per minute to server_bandwidth_minute, for the Control Panel) and stops it last on deinitialise, after deregistration has had the shutdown budget.
  • Graceful shutdown — Zeros the in-memory signing key with CryptographicOperations.ZeroMemory, deletes the signing-key DB row, deregisters the login-server DB row, and resets runtime data.
  • Non-blocking initialization — Startup database work is awaited, never blocked on. Shutdown cleanup, which runs in OnDeinitialize where Unity cannot yield, uses UnitySyncOverAsync for a bounded, cancellable wait.
  • Structured error logging — Every failure path logs contextual error/warning messages through FishMMO.Logging.Log.

Prerequisites

  • Unity 6.6 (6000.6.8f1) (IL2CPP scripting backend)
  • FishNet networking framework (for ServerManager / ServerAuthenticator)
  • FishMMO server core assemblies (FishMMO.Server.Core, FishMMO.Server.Core.LoginServer)
  • FishMMO database layer (FishMMO.Database, FishMMO.Database.Npgsql) with a reachable PostgreSQL instance
  • ILoginServerService and ILoginServerSigningKeyService registered in the database service registry
  • A valid server address provider (IServerAddressProvider) and configuration entry for ServerName

Installation / Build

This is an integrated module within the FishMMO Unity project. No separate installation is required.

  1. Ensure the FishMMO Unity project is open in the Unity Editor.
  2. The LoginServerSystem ScriptableObject asset can be created via Assets → Create → FishMMO → Server → LoginServer → Login Server System.
  3. Add the created asset to the login server's behaviour list so it is initialized during server startup.
  4. Ensure LoginServerRuntimeData and AsyncWorkerData runtime data containers are registered in the server's DataContainerRegistry.

Quick Start Guides

Running a Login Server Locally

  1. Configure ServerName in the server configuration file (e.g., "LoginServer-Dev").
  2. Ensure the address provider returns a valid IP and port for the login server.
  3. Verify the database is reachable and ILoginServerService / ILoginServerSigningKeyService are registered.
  4. Start the server — LoginServerSystem.InitializeOnceAsync() will register in the DB, generate the HMAC key, and begin heartbeating.
  5. Confirm initialization by checking the debug log for: Initialized (ServerID=<id>, Address=<addr>:<port>, PulseRate=5s).

Verifying Heartbeat

  1. After startup, query the login-server table in the database.
  2. The LastPulse (or equivalent timestamp column) should update every PulseRate seconds.
  3. If heartbeat stops, check logs for "Failed to enqueue pulse work item" or "Pulse failed" warnings.

Configuration

Field Type Default Source Purpose
pulseRate float 5.0f [SerializeField] on LoginServerSystem Interval in seconds between database heartbeat pulses
signingKeyRotationHours float 24.0f [SerializeField] on LoginServerSystem Age at which the active token-signing key is rotated; 0 disables rotation
ServerName string — Server configuration (IServerConfiguration) Display name registered in the database for this login server
Server address / port ServerAddress — IServerAddressProvider Public network endpoint registered in the database

PulseRate is exposed as a read-only property backed by [SerializeField] private float pulseRate.

Inspector Fields

Inspector Field Type Default Description
Pulse Rate float 5.0 How often (in seconds) the server sends a heartbeat to the database

Login Queue

LoginQueueSystem (LoginServer/LoginQueueSystem.cs, one folder up) is the login server's admission queue, and it is listed in LoginServer.unity's behaviours beside this system. It engages only when a completed handshake would push the authenticator past its pending cap (AuthMaxPendingConnections; unset, the SRP verify and proof channel capacities added, 500 + 500 = 1,000). ServerAuthenticator.OnHandshakeDeferred looks the system up in the behaviour registry and hands it the connection; without the system, or with the queue full, the handshake is answered ServerBusy and dropped.

  • Held on the live connection. A queued client stays connected at the QUIC layer, unauthenticated. The handshake-timeout sweep leaves it alone while it is queued and for 15 s after it is admitted (IsAwaitingAdmission).
  • Told its place. Every LoginQueueUpdateRateSeconds (default 2 s) each queued client gets a LoginQueuePositionBroadcast with its position, the queue's length and an estimate (position ÷ admission rate). Positions go Unreliable; admission (0) and cancellation (-1) go Reliable.
  • Admitted at a rate. LoginQueueAdmissionRatePerSecond (default 50) accrues as credit, capped at one second's worth while clients wait, so several can be admitted in one frame and the rate holds at any frame rate. Dead entries are skipped without spending credit. An admitted client is sent 0 and re-handshakes on the same connection (OnRehandshakeRequired, which keeps its credentials).
  • Not sent to the back twice. A client admitted in the last 15 s whose re-handshake still finds the cap full is re-admitted at once instead of queued again.
  • Bounded. At most LoginQueueMaxSize (default 500) wait at once, each for at most LoginQueueTimeoutSeconds (default 300), timed on the monotonic clock from the first time that client was queued, so a re-queue does not restart it. A timed-out client is sent -1 and disconnected without discarding that notice.

The client shows the wait on its queue panel; see Client Connection → Waiting is not disconnecting.

Usage Examples

Accessing the Login Server ID at Runtime

if (Server.DataContainerRegistry.TryGet<ILoginServerRuntimeData>(out var runtimeData))
{
    long loginServerId = runtimeData.ID;
    // Use loginServerId for cross-server identification, token signing, etc.
}

Creating the ScriptableObject Asset

Assets → Create → FishMMO → Server → LoginServer → Login Server System

The asset menu path is defined by:

[CreateAssetMenu(fileName = "LoginServerSystem",
                 menuName = "FishMMO/Server/LoginServer/Login Server System",
                 order = 1)]

Operational Checks

Check How to Verify Expected Result
DB registration Query login-server table after startup Row exists with correct name, address, port
HMAC key persistence Query signing-key table for login-server ID Row exists with a non-null key blob
Authenticator configured Inspect ServerAuthenticator.TokenSigningKey at runtime Non-null byte array matching generated key
Heartbeat active Monitor login-server table timestamp Updates every ~5 s (or configured PulseRate)
Graceful shutdown — key zeroed Breakpoint or log after OnDeinitialize TokenSigningKey is null, memory zeroed
Graceful shutdown — DB cleanup Query login-server and signing-key tables after stop Both rows deleted
Registration failure Block DB access and start server Server logs "Behaviour initialization failed on attempt N/5: ..." and "Retrying behaviour initialization in ..."; after the last attempt the process exits rather than idling unbound
One pulse at a time Stall the database longer than PulseRate No second pulse starts until the first finishes; heartbeats resume at the normal rate afterwards
Pulse failure logging Simulate DB error during heartbeat Warning: "Pulse failed: <error>"

Flow Diagram

High-Level Overview

flowchart LR
    Client[Unity Client] -->|authenticate| Auth[LoginServer.Authentication]
    Auth -->|account lookup| DB[(PostgreSQL)]
    Auth -->|token issued| Sys[LoginServerSystem]
    Sys --> AC[AccountCreation]
    Sys --> CC[CharacterCreate]
    Sys --> CS[CharacterSelect]
    Sys --> SS[ServerSelect]
    Sys -->|hand off| World[WorldServer]
┌─────────────────────────────────────────────────────────────────────┐
│                    LoginServerSystem Lifecycle                      │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  InitializeOnceAsync(cancellationToken)                             │
│  ┌────────────────────────────────────────────────────────────────┐ │
│  │ 1. Validate Server + DataContainerRegistry                    │ │
│  │ 2. Resolve server address (IServerAddressProvider)            │ │
│  │ 3. Read ServerName from IServerConfiguration                  │ │
│  │ 4. Resolve ILoginServerService from DB service registry       │ │
│  │ 5. await PersistAsync(name, address, port, ct)                │ │
│  │ 6. Store returned DB ID → ILoginServerRuntimeData.ID         │ │
│  │ 7. Resolve ILoginServerSigningKeyService                      │ │
│  │ 8. CryptoHelper.GenerateKey(HmacKeyLength)                   │ │
│  │ 8b. await SigningKeyKekProvider.LoadFromDatabaseAsync(ct)     │ │
│  │ 9. await UpsertAsync(serverId, wrappedHmacKey, ct)            │ │
│  │ 10. Configure ServerAuthenticator (TokenSigningKey, ID)       │ │
│  │ 11. Register periodic callback (PulseRate, OnPeriodicPulse)   │ │
│  │ 12. ServerBandwidthRecorder.TryStart(Server, Login)           │ │
│  └────────────────────────────────────────────────────────────────┘ │
│                              │                                      │
│                              ▼                                      │
│  OnPeriodicPulse(deltaTime)  ── every PulseRate seconds ──         │
│  ┌────────────────────────────────────────────────────────────────┐ │
│  │ Guard: Initialized && Server != null && State == Started      │ │
│  │ TryBeginPulse() — skip if a pulse is still in flight          │ │
│  │ TryEnqueueAsyncWork → PulseAsync(runtimeData)                 │ │
│  │   └─► ILoginServerService.PulseAsync(serverId)               │ │
│  │       └─► Updates liveness timestamp in DB                   │ │
│  │   finally: EndPulse()                                         │ │
│  │ Key older than signingKeyRotationHours → RotateSigningKeyAsync│ │
│  └────────────────────────────────────────────────────────────────┘ │
│                              │                                      │
│                              ▼                                      │
│  OnDeinitialize()                                                   │
│  ┌────────────────────────────────────────────────────────────────┐ │
│  │ 1. Unregister periodic callback                               │ │
│  │ 2. Zero authenticator signing key (CryptographicOperations)   │ │
│  │ 3. Set TokenSigningKey = null                                 │ │
│  │ 4. Delete signing-key row from DB [5s timeout]                │ │
│  │ 5. Delete login-server row from DB [5s timeout]               │ │
│  │ 6. Reset ILoginServerRuntimeData.ID = 0                      │ │
│  │ 7. Stop the bandwidth recorder (bounded final sample)         │ │
│  └────────────────────────────────────────────────────────────────┘ │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Project Structure

Directory Tree

LoginServer/
├── LoginServerSystem.cs         # Login server lifecycle behaviour (register, key gen, heartbeat)
├── LoginServerRuntimeData.cs    # Runtime container storing login server DB ID
└── README.md                    # This file
Server/Core/LoginServer/LoginServer/
├── ILoginServerSystem.cs        # Interface: IServerBehaviour marker for login server system
└── ILoginServerRuntimeData.cs   # Interface: long ID { get; set; }, TryBeginPulse / EndPulse

Server/Core/RuntimeData/
└── IAsyncWorkerData.cs          # Async worker queue for off-thread DB operations

Inheritance Hierarchies

Behaviour

ServerBehaviour
└── LoginServerSystem : ILoginServerSystem

Runtime Data

RuntimeDataContainer
└── LoginServerRuntimeData : ILoginServerRuntimeData

Runtime Data Dependencies

LoginServerSystem declares:

  • [RequiresDataContainer(typeof(LoginServerRuntimeData))]
  • [RequiresDataContainer(typeof(AsyncWorkerData))]
Container Responsibility
LoginServerRuntimeData Holds the persistent runtime login-server ID assigned by the database, and the pulse in-flight gate
AsyncWorkerData Executes heartbeat pulse tasks without blocking main/update threads

Threading Model

Thread Work
Main / server update Initialization, callback registration, pulse scheduling
Async workers (AsyncWorkerData) Database heartbeat calls (PulseAsync), signing-key persistence

External Integration Points

Dependency Interface Role
Address Provider IServerAddressProvider Resolves public network address and port for DB registration
Configuration IServerConfiguration Supplies ServerName config key
Database Service Registry ILoginServerService Login-server CRUD and heartbeat pulse
Database Service Registry ILoginServerSigningKeyService HMAC signing-key upsert and delete
Periodic Update System IPeriodicUpdateSystem Drives fixed-rate heartbeat scheduling
Network Authenticator ServerAuthenticator Receives HMAC key and login-server ID for token signing
Runtime Data Registry ILoginServerRuntimeData, IAsyncWorkerData Server-scoped state containers

License

This module is part of the FishMMO project and is subject to the FishMMO project license.