Table of Contents

Class ChatService

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 ChatService : BaseService<ChatEntity>, IChatService
Inheritance
ChatService
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

ChatService(INpgsqlDbContextFactory)

Initializes a new instance of ChatService.

public ChatService(INpgsqlDbContextFactory dbContextFactory)

Parameters

dbContextFactory INpgsqlDbContextFactory

DbContext factory for creating contexts.

Exceptions

ArgumentNullException

Thrown when dbContextFactory is null.

Fields

BridgedAccountName

Account name written on rows bridged in from Discord, which have no game account.

public const string BridgedAccountName = "Discord"

Field Value

string

MaxAuditAccountLength

Maximum stored length of an account name, matching chat.account_name.

public const int MaxAuditAccountLength = 50

Field Value

int

Remarks

Same reasoning as MaxAuditNameLength.

MaxAuditNameLength

Maximum stored length of a character name, matching chat.character_name.

public const int MaxAuditNameLength = 50

Field Value

int

Remarks

This must equal the column width, not some comfortable number above it. It was 256 against a varchar(50), which meant a name between 51 and 256 characters passed the guard untouched and then failed the INSERT with a 22001 — the truncation existed precisely to prevent that and did not. Latent today only because no character name can reach 51 characters; a guard that relies on nothing ever testing it is not a guard.

MaxMessageLength

Maximum allowed length for chat messages. This length should never be close to reached. Maximum server message should be 256 characters.

public const int MaxMessageLength = 4000

Field Value

int

MaxPumpPageSize

Most rows one pump page may ask for.

public const int MaxPumpPageSize = 1000

Field Value

int

MaxPumpPages

Most pages one pump read may walk.

public const int MaxPumpPages = 100

Field Value

int

PumpCommitWindowSeconds

How far behind its own progress the scene servers' chat pump reads, in seconds.

public const double PumpCommitWindowSeconds = 10

Field Value

double

Remarks

A row's stamp is not its commit. time_created is taken by the database clock when the INSERT runs (see FishMMO.Database.Npgsql.Services.ChatService.insertSql), and the row becomes visible only when its transaction commits, some time later. Two writers can therefore commit in the opposite order to their stamps: A stamps 100.00 and commits at 100.30, B stamps 100.10 and commits at 100.12. A reader that paged by a strict (time, id) cursor saw B at 100.15, moved past 100.10, and never saw A — whispers, party and guild lines lost for good (hot-path audit H5).

So the pump re-reads this far behind the newest point it has settled and skips the rows it has already handled by ID. A row is caught as long as it commits within this long of its stamp. One statement per chunk inside one transaction commits in milliseconds; ten seconds is a stall, not a slow write. It lives here rather than on the reader so the writer's side of the contract and the reader's are one number.

Methods

FetchPumpAsync(ChatPumpQuery, CancellationToken)

Reads the chat rows one scene server should relay: new, relevant to someone it hosts, and not its own echo.

public Task<DatabaseResult<ChatPumpPage>> FetchPumpAsync(ChatPumpQuery query, CancellationToken cancellationToken = default)

Parameters

query ChatPumpQuery

Where to start, what to skip, and what this server hosts.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult<ChatPumpPage>>

The rows in (time_created, id) order, the database clock at the start of the read, and whether the read caught up.

Remarks

This replaces a strict (time_created, id) cursor that lost rows for good whenever two writers committed out of stamp order, and read one 20-row page of the whole shard's chat per call however far behind it was (hot-path audit H5, H6).

The caller reads from a start held PumpCommitWindowSeconds behind what it has settled, and passes the IDs it has already handled in that window as ExcludeIds. Pages are read while they come back full, up to MaxPages, so a backlog is worked through instead of growing.

FetchRelayAsync(ChatRelayQuery, CancellationToken)

Reads the chat rows the Discord relay has not handled yet: every game row, never a row bridged in from Discord.

public Task<DatabaseResult<ChatPumpPage>> FetchRelayAsync(ChatRelayQuery query, CancellationToken cancellationToken = default)

Parameters

query ChatRelayQuery

Where to start and what to skip.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult<ChatPumpPage>>

The rows in (time_created, id) order, the database clock at the start of the read, and whether the read caught up.

Remarks

The same window as FetchPumpAsync(ChatPumpQuery, CancellationToken), read by a ChatReadWindow. The relay used to page by id > last id seen, and IDs are taken at the INSERT, not at the commit: a row that committed after a higher ID had been read was skipped for good. It also read everything past that ID in one unbounded query (hot-path audit H5).

A query with no FromUtc starts at the database's "now", so a relay that starts does not republish history.

PersistAsync(long, string, string, long, long, ChatChannel, string, DateTime, CancellationToken)

Persists a chat message with denormalized audit fields.

public Task<DatabaseResult> PersistAsync(long characterId, string characterName, string accountName, long worldServerId, long sceneServerId, ChatChannel channel, string message, DateTime serverReceivedTime, CancellationToken cancellationToken = default)

Parameters

characterId long

Character ID sending the message.

characterName string

Character name (denormalized for audit retention).

accountName string

Account name (denormalized for audit retention).

worldServerId long

World server ID.

sceneServerId long

Scene server ID.

channel ChatChannel

Chat channel.

message string

Message content.

serverReceivedTime DateTime

Timestamp when server received the message (for legal audit trail).

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult>

A DatabaseResult indicating success or containing a DatabaseException on failure.

Remarks

Chat audit fields are denormalized so logs can survive character deletion. Passing the names avoids a race where the character row is deleted between lookup and insert. Uses BaseService.ExecuteWriteAsync for:

  • Automatic transient failure retry
  • Centralized exception handling and mapping
  • Consistent DatabaseResult pattern

PersistBatchAsync(List<(long characterId, string characterName, string accountName, long worldServerId, long sceneServerId, ChatChannel channel, string message, DateTime serverReceivedTime)>, int, CancellationToken)

Persists multiple chat messages in ONE transaction: every message lands, or none does.

public Task<DatabaseResult> PersistBatchAsync(List<(long characterId, string characterName, string accountName, long worldServerId, long sceneServerId, ChatChannel channel, string message, DateTime serverReceivedTime)> messages, int maxBatchSize = 1000, CancellationToken cancellationToken = default)

Parameters

messages List<(long characterId, string characterName, string accountName, long worldServerId, long sceneServerId, ChatChannel channel, string message, DateTime serverReceivedTime)>

List of chat messages to persist. Each tuple contains: (characterId, characterName, accountName, worldServerId, sceneServerId, channel, message, serverReceivedTime).

maxBatchSize int

Messages per INSERT statement inside the transaction (clamped to 500–2500). It does not change atomicity.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult>

A DatabaseResult indicating success or failure.

Remarks

All-or-nothing is what makes a failed call safe to retry. The rows are the chat audit log and other scene servers deliver whatever new rows they find, so a call that had committed part of a list before failing would write — and deliver — that part twice when the caller retried it.

PersistBridgedAsync(long, long, string, string, DateTime, CancellationToken)

Persists one line bridged in from Discord, as a Discord row the scene servers relay to every player in worldServerId.

public Task<DatabaseResult> PersistBridgedAsync(long worldServerId, long sceneServerId, string authorName, string message, DateTime serverReceivedTime, CancellationToken cancellationToken = default)

Parameters

worldServerId long

World the Discord channel is bridged to.

sceneServerId long

Scene server the Discord channel is bridged to.

authorName string

The Discord author's (already sanitised) display name, for the audit columns.

message string

The line as players will see it.

serverReceivedTime DateTime

When the bridge received it, UTC.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult>

A DatabaseResult indicating success or failure.

Remarks

Through the same INSERT as every other chat row so it is stamped by the same clock: the bridge used to stamp time_created from its own host's clock, and the scene servers page the table by that column.

SearchAdminAsync(ChatAdminQuery, CancellationToken)

Searches persisted chat for an operator, newest message first.

public Task<DatabaseResult<ChatAdminPage>> SearchAdminAsync(ChatAdminQuery query, CancellationToken cancellationToken = default)

Parameters

query ChatAdminQuery

The filter to apply. Null is treated as an unfiltered query.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DatabaseResult<ChatAdminPage>>

A DatabaseResult<T> containing one page of ChatAdminData and the total row count on success, or a DatabaseException on failure.

Remarks

This is the read behind a harassment or abuse report, so it is separate from FetchPumpAsync(ChatPumpQuery, CancellationToken) in every respect: that one is a window the scene servers pull forward and it deliberately hides a server's own echo, while this one hides nothing and orders backwards from now.

A message-text filter supplied with no character name, no account name and no lower time bound is REFUSED with ValidationError rather than served. The reason is in the implementation; callers should surface the message rather than retrying, because a retry of the same query is refused identically.

Read-only: it uses AsNoTracking and writes nothing, including no audit row. Recording reads in the audit log would mean every listing of the log wrote a row of its own.