Table of Contents

Class WorldServerService

Namespace
FishMMO.Database.Npgsql.Services
Assembly
FishMMO-DB.dll

Base class for database services that execute EF Core operations with consistent execution behavior (transactional and read-only), retry behavior for transient failures, and standardized error mapping into DatabaseResult.

public sealed class WorldServerService : BaseService<WorldServerEntity>, IWorldServerService, IFetchByKeyAction<long, WorldServerData>
Inheritance
WorldServerService
Implements
Inherited Members

Remarks

This base type provides three primary execution paths:

  • ExecuteTransactionAsync(Func<Task>, CancellationToken) and ExecuteTransactionAsync<TResult>(Func<Task<TResult>>,string,CancellationToken) create a fresh NpgsqlDbContext, begin an explicit transaction, execute the delegate, then call SaveChangesAsync(CancellationToken) and commit.
  • ExecuteWriteAsync(Func<Task>,string,CancellationToken) and ExecuteWriteAsync<TResult>(Func<Task<TResult>>,string,CancellationToken) create a fresh NpgsqlDbContext, execute the delegate, then call SaveChangesAsync(CancellationToken) without starting an explicit transaction.
  • ExecuteReadAsync(Func<Task>,string,CancellationToken) and ExecuteReadAsync<TResult>(Func<Task<TResult>>,string,CancellationToken) create a fresh NpgsqlDbContext but do not start an explicit transaction and do not call SaveChanges.

Standalone Execution (no ambient scope): A new context is created per attempt to avoid EF change-tracker state leaking across retries. Transient database failures are retried with exponential backoff. Optimistic concurrency conflicts (Version-based authority) and StaleStateException are never retried; they are returned as non-transient failures so the caller can re-read and decide how to proceed.

Ambient Scope Execution (inside an existing Unit of Work): When an operation detects an active FishMMO.Database.Npgsql.Services.DatabaseExecutionScope, it reuses the ambient NpgsqlDbContext and does NOT retry on transient failures. This is by design for the following reasons:

  1. Transaction State Corruption: PostgreSQL aborts the entire transaction on most transient failures. The connection and transaction become unusable, making retry with the same context impossible.
  2. Context State Pollution: The DbContext's change tracker accumulates state. Retrying with a polluted change tracker can cause duplicate key violations or incorrect updates.
  3. Semantic Correctness: If operation A succeeded and operation B failed transiently, retrying B alone without re-evaluating A's preconditions could violate business invariants.

When a transient failure occurs inside an ambient scope, the failure is returned immediately so the caller can restart the entire unit of work with fresh state. Savepoints are used for nested atomicity but cannot recover from connection-level failures.

Constructors

WorldServerService(INpgsqlDbContextFactory)

Initializes a new instance of WorldServerService.

public WorldServerService(INpgsqlDbContextFactory dbContextFactory)

Parameters

dbContextFactory INpgsqlDbContextFactory

DbContext factory for creating contexts.

Exceptions

ArgumentNullException

Thrown when dbContextFactory is null.

Methods

DeleteAsync(long, CancellationToken)

public Task<DatabaseResult> DeleteAsync(long serverId, CancellationToken cancellationToken = default)

Parameters

serverId long
cancellationToken CancellationToken

Returns

Task<DatabaseResult>

FetchActiveAsync(float, CancellationToken)

Fetches active world servers that have pulsed within the timeout window. Filters servers by last_pulse timestamp to return only servers that are currently online.

public Task<DatabaseResult<List<WorldServerData>>> FetchActiveAsync(float idleTimeoutSeconds = 60, CancellationToken cancellationToken = default)

Parameters

idleTimeoutSeconds float

Idle timeout in seconds before server considered inactive (default 60).

cancellationToken CancellationToken

Cancellation token for async operation.

Returns

Task<DatabaseResult<List<WorldServerData>>>

DatabaseResult containing List of active WorldServerData ordered by name; empty list if no active servers.

Remarks

Operation: LINQ query filtering by last_pulse >= (UtcNow - timeout), ordered by name.

Execution Strategy: BaseService handles retries and centralized exception mapping; explicit transactions are used only when a write requires multiple database statements.

FetchAsync(long, CancellationToken)

Fetches an entity for the given key.

public Task<DatabaseResult<WorldServerData>> FetchAsync(long serverId, CancellationToken cancellationToken = default)

Parameters

serverId long
cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<DatabaseResult<WorldServerData>>

FetchControlStateAsync(long, CancellationToken)

Reads a world server's lock and shutdown state without writing a pulse.

public Task<DatabaseResult<ServerControlState>> FetchControlStateAsync(long serverId, CancellationToken cancellationToken = default)

Parameters

serverId long

World server row to read.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult<ServerControlState>>

The control state, with the time left before any scheduled shutdown measured by the database clock, or NotFound when the row is gone.

Remarks

For scene servers, which host scenes on behalf of a world but do not pulse its row. A world-wide shutdown has to reach them so they can warn their players and clear the world's characters out on the same deadline.

PersistAsync(string, string, ushort, int, bool, CancellationToken)

Persists a world server registration (insert or update). Uses an insert-first approach and falls back to update on unique constraint conflicts.

public Task<DatabaseResult<(long ServerId, WorldServerData ServerData, ServerControlState Control)>> PersistAsync(string name, string address, ushort port, int characterCount, bool locked, CancellationToken cancellationToken = default)

Parameters

name string

Server name (unique identifier for conflict resolution).

address string

Server IP address or hostname.

port ushort

Server port number.

characterCount int

Current character count on server.

locked bool

Whether server is locked from accepting new connections.

cancellationToken CancellationToken

Cancellation token for async operation.

Returns

Task<DatabaseResult<(long ServerId, WorldServerData ServerData, ServerControlState Control)>>

DatabaseResult containing (ServerId, ServerData, Control) if successful. Control is the row's operator state — the lock and any scheduled shutdown — read in the same statement, the same state PulseAsync(long, int, CancellationToken) returns, so a server adopts it from the moment it registers rather than from its first heartbeat.

Remarks

Operation: Attempts INSERT; on unique violation, loads the existing row and updates it.

Returns: The returned ServerId is populated after SaveChanges completes inside the BaseService execution wrapper.

Returns: Failure if name/address empty or operation fails; Success with (ServerId, ServerData, Control) on success.

PulseAsync(long, int, CancellationToken)

public Task<DatabaseResult<ServerControlState>> PulseAsync(long serverId, int characterCount, CancellationToken cancellationToken = default)

Parameters

serverId long
characterCount int
cancellationToken CancellationToken

Returns

Task<DatabaseResult<ServerControlState>>

SetLockedAsync(long, bool, CancellationToken)

Opens or closes this world server to new connections.

public Task<DatabaseResult> SetLockedAsync(long serverId, bool locked, CancellationToken cancellationToken = default)

Parameters

serverId long

World server row to update.

locked bool

True to close it to new arrivals.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult>

Success, or NotFound when the row is gone.

Remarks

The row is the authority; the server adopts it on its next pulse. Locking drains rather than evicts — see Locked.

SetShutdownAsync(long, DateTime?, CancellationToken)

Schedules or cancels this world server's shutdown.

public Task<DatabaseResult> SetShutdownAsync(long serverId, DateTime? shutdownAtUtc, CancellationToken cancellationToken = default)

Parameters

serverId long

World server row to update.

shutdownAtUtc DateTime?

Absolute UTC stop time, or null to cancel.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult>

Success, or NotFound when the row is gone.

Remarks

Scheduling also locks the server, in the same statement. Cancelling does not unlock it: halting a shutdown and reopening to players are separate decisions.

For a caller that already holds an absolute instant shared by several rows, such as a maintenance window stopping every target at one deadline. A request phrased as "in N seconds" belongs on SetShutdownInAsync(long, int, CancellationToken): turning it into an instant here means adding the seconds to the caller's own clock, which moves the deadline by that clock's skew from the database the servers count down against.

SetShutdownInAsync(long, int, CancellationToken)

Schedules this world server's shutdown a number of seconds from now by the database clock, and locks it.

public Task<DatabaseResult<DateTime>> SetShutdownInAsync(long serverId, int seconds, CancellationToken cancellationToken = default)

Parameters

serverId long

World server row to update.

seconds int

Delay in seconds. Zero means now; negative is refused.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult<DateTime>>

The UTC deadline written, or NotFound when the row is gone.

Remarks

The deadline is the database's own time plus seconds, taken inside the statement that writes it. Every server counts a shutdown down against the database clock (ShutdownInSeconds), so the delay asked for is the delay that elapses, whatever the requesting host's clock says. Locks in the same statement, as SetShutdownAsync(long, DateTime?, CancellationToken) does.

A retry after a connection lost past the commit writes the deadline again from the retry's own instant: later by the reconnect, never earlier, and the returned deadline is the one the row holds.