Class ServerBehaviour
- Namespace
- FishMMO.Server.Implementation
- Assembly
- FishMMO.Server.dll
Currency bookkeeping every system that takes or pays currency shares: the immediate attribute save a spend is conditioned on, and the economy ledger row written once it has happened.
public abstract class ServerBehaviour : ScriptableObject, IServerBehaviour<INetworkManagerWrapper, ServerManager, NetworkConnection, IServerBehaviour>, IServerBehaviour, IServerComponent<INetworkManagerWrapper, ServerManager, NetworkConnection, IServerBehaviour>, IServerComponent
- Inheritance
-
ObjectScriptableObjectServerBehaviour
- Implements
- Derived
- Inherited Members
-
ScriptableObject.SetDirty()ScriptableObject.CreateInstance<T>()Object.GetEntityId()Object.MemberwiseClone()Object.GetInstanceID()Object.GetHashCode()Object.InstantiateAsync<T>(T)Object.InstantiateAsync<T>(T, Transform)Object.InstantiateAsync<T>(T, Vector3, Quaternion)Object.InstantiateAsync<T>(T, Transform, Vector3, Quaternion)Object.Instantiate(Object, Vector3, Quaternion)Object.Instantiate(Object, Vector3, Quaternion, Transform)Object.Instantiate(Object)Object.Instantiate(Object, Scene)Object.Instantiate<T>(T, InstantiateParameters)Object.Instantiate<T>(T, Vector3, Quaternion, InstantiateParameters)Object.Instantiate(Object, Transform)Object.Instantiate<T>(T)Object.Instantiate<T>(T, Vector3, Quaternion)Object.Instantiate<T>(T, Vector3, Quaternion, Transform)Object.Instantiate<T>(T, Transform)Object.Destroy(Object)Object.DestroyImmediate(Object)Object.DontDestroyOnLoad(Object)Object.DestroyObject(Object)Object.FindObjectsOfType<T>()Object.FindObjectsByType<T>(FindObjectsSortMode)Object.FindObjectsByType<T>(FindObjectsInactive, FindObjectsSortMode)Object.FindObjectOfType<T>()Object.FindFirstObjectByType<T>()Object.FindAnyObjectByType<T>()Object.FindFirstObjectByType<T>(FindObjectsInactive)Object.FindAnyObjectByType<T>(FindObjectsInactive)Object.FindObjectsByType<T>()Object.FindObjectsByType<T>(FindObjectsInactive)Object.ToString()Object.nameObject.hideFlags
Remarks
These were the merchant's (InteractableSystem.Merchant) and were borrowed by ability crafting and corpse looting; with merchants and loot in the Commerce module and crafting in the core, they live on the base so neither copies the other (2026-11-17).
Properties
Initialized
Indicates whether this behaviour has been initialized.
public bool Initialized { get; }
Property Value
Server
Reference to the server instance associated with this behaviour.
public IServer<INetworkManagerWrapper, NetworkConnection, IServerBehaviour> Server { get; }
Property Value
- IServer<INetworkManagerWrapper, NetworkConnection, IServerBehaviour>
ServerManager
Reference to the server manager instance associated with this behaviour.
public ServerManager ServerManager { get; }
Property Value
- ServerManager
Methods
ClaimsOf(CharacterSessionLeaseData)
One claim as the collection a batched owned write takes. Pure.
protected static IReadOnlyCollection<CharacterSessionLeaseData> ClaimsOf(CharacterSessionLeaseData claim)
Parameters
claimCharacterSessionLeaseDataThe claim.
Returns
- IReadOnlyCollection<CharacterSessionLeaseData>
A single-element collection.
Deinitialize()
Deinitializes this behaviour, calling OnDeinitialize and clearing references.
public void Deinitialize()
DisconnectWithNotice(NetworkConnection, DisconnectNoticeReason, bool)
Closes conn after telling it why.
protected void DisconnectWithNotice(NetworkConnection conn, DisconnectNoticeReason reason, bool terminal = false)
Parameters
connNetworkConnectionConnection to close.
reasonDisconnectNoticeReasonWhat to tell the client.
terminalboolTrue when reconnecting cannot help, so the client abandons its retry loop instead of spending it on an outcome that cannot change. See Terminal.
Remarks
Use this instead of NetworkConnection.Kick for any disconnect the server
decides on. FishNet does not deliver a kick reason to the client, so a plain kick
drops the player back at the login screen with nothing to go on — unable to tell a
transient routing hiccup from a character they will never be able to log in to.
Disconnect(false) rather than Kick is load-bearing: Kick stops
the transport immediately and throws away everything still queued for this tick,
including the notice written on the line above. Disconnect(false) flushes the
tick first, marks the connection invalid so nothing further is sent or received on
it, and closes roughly 100ms later — so the notice arrives and the connection is
still shut out of the server just as promptly.
DrainMainThreadQueue<TQueue>(int, bool)
Drain the specified main-thread queue for this server behaviour.
protected void DrainMainThreadQueue<TQueue>(int maxActions, bool drainAll) where TQueue : class, IMainThreadQueueData
Parameters
Type Parameters
TQueue
EndInFlightRequest<TRuntime>(NetworkConnection, Action<TRuntime>)
Generic helper to release an in-flight slot from a runtime data container. Caller supplies an action that performs the remove/cleanup on the runtime data.
protected void EndInFlightRequest<TRuntime>(NetworkConnection conn, Action<TRuntime> onEnd) where TRuntime : class, IRuntimeDataContainer
Parameters
connNetworkConnectiononEndAction<TRuntime>
Type Parameters
TRuntime
EnqueuePersistence(Func<Task>, long, string)
Enqueues persistence work through the async worker, which never refuses it for being over its backpressure threshold. Only when the worker is not running at all does the work run on the thread pool instead, through a small bounded gate.
Use this instead of TryEnqueueAsyncWork(Func<Task>, long, string) for post-processing persistence where in-memory state has already been committed and the database write must not be silently dropped.
protected bool EnqueuePersistence(Func<Task> work, long entityKey = 0, string callerName = null)
Parameters
Returns
- bool
trueif admitted within the worker's threshold;falseif it was admitted over it or had to use the fallback. Either way the work WILL run: false means "the server is saturated", which is what callers tell the client.
Remarks
The over-threshold path used to be Task.Run, outside the worker's concurrency cap.
During a database stall — exactly when the queue fills — every further write started at
once, the connection pool ran dry, the timeouts filed repair snapshots, and those queued
more writes. It also broke the per-entity FIFO that item writes rely on. Over-threshold work
now waits its turn in the worker like everything else; see
EnqueueRequired(Func<Task>, long, string).
The remaining fallback — the worker not running, which in practice means teardown — is bounded by FishMMO.Server.Implementation.ServerBehaviour.PersistenceFallbackGate for the same reason.
InitializeOnce()
Called once to initialize the behaviour. Must be implemented by derived classes.
public abstract ServerComponentInitializationStatus InitializeOnce()
Returns
Remarks
Behaviours that need to await I/O (database registration, for example) must override InitializeOnceAsync(CancellationToken) instead of blocking in here. The Unity main thread must never block on I/O: it is the thread that drains async continuations, so blocking it can deadlock startup before the transport ever binds.
InitializeOnceAsync(CancellationToken)
Asynchronous initialization hook. The default implementation simply runs the synchronous InitializeOnce(), so behaviours with no I/O need not change.
public virtual Task<ServerComponentInitializationStatus> InitializeOnceAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenCancelled when the server shuts down mid-startup.
Returns
- Task<ServerComponentInitializationStatus>
The initialization status.
Remarks
Overrides are invoked on the Unity main thread. Awaiting without
ConfigureAwait(false) resumes on the main thread, so Unity APIs remain safe to
touch after an await.
IsClaimRefusal(DatabaseResult)
Whether an owned write failed because the claim it quoted is no longer this server's. Pure.
public static bool IsClaimRefusal(DatabaseResult result)
Parameters
resultDatabaseResultThe failed write.
Returns
- bool
True for a refusal by the ownership gate.
Remarks
Final: the character belongs to another session now — or to none, after a release — and retrying would only be refused again. It is also rare, since only a lost claim produces it, and the row save and the lease refresh evict such a character within one interval.
IsClaimRefusal<T>(DatabaseResult<T>)
Whether an owned write failed because the claim it quoted is no longer this server's. Pure.
public static bool IsClaimRefusal<T>(DatabaseResult<T> result)
Parameters
resultDatabaseResult<T>The failed write.
Returns
- bool
True for a refusal by the ownership gate.
Type Parameters
T
Remarks
Final: the character belongs to another session now — or to none, after a release — and retrying would only be refused again. It is also rare, since only a lost claim produces it, and the row save and the lease refresh evict such a character within one interval.
OnDeinitialize()
Called when the behaviour is being deinitialized. Must be implemented by derived classes.
public abstract void OnDeinitialize()
OnLateUpdate(float)
Called by the Server's LateUpdate to provide mutable data and perform per-frame logic. Performs a guard check to ensure the behaviour is initialized and the server reference is valid, then delegates to OnUpdate(float) for subclass-specific logic.
public void OnLateUpdate(float deltaTime)
Parameters
deltaTimefloatTime elapsed since last frame.
OnRemoteConnectionStopped(NetworkConnection)
Called when a remote connection stops. Override in derived classes to perform
per-connection cleanup (e.g. clearing in-flight requests, caches, queue entries).
The connection still resolves to its account here (Server.AccountManager.GetAccountNameByConnection):
the authenticator forgets it only after every behaviour has run.
Systems must call SubscribeToConnectionEvents() in InitializeOnce()
and UnsubscribeFromConnectionEvents() in OnDeinitialize() to use this.
protected virtual void OnRemoteConnectionStopped(NetworkConnection conn)
Parameters
connNetworkConnection
OnUpdate(float)
Override this method in derived classes that need per-frame updates. Guaranteed to run only when the behaviour is initialized and Server is non-null.
protected virtual void OnUpdate(float deltaTime)
Parameters
deltaTimefloatTime elapsed since last frame.
RecordCurrencyMovement(long, long, CurrencyMovementReason, bool)
Appends a completed currency movement to the economy ledger.
protected void RecordCurrencyMovement(long characterID, long amount, CurrencyMovementReason reason, bool absorbed)
Parameters
characterIDlongThe character whose balance moved.
amountlongAmount moved. Non-positive amounts are not recorded.
reasonCurrencyMovementReasonWhich sink the movement belongs to.
absorbedboolTrue when the currency left the economy, false when it was given back.
Remarks
Call this only once the movement has actually happened AND its balance change has been persisted. The row carries its outcome, so nothing revisits it and nothing infers a balance from it — which is what keeps a lost row a reporting gap rather than an economic one.
This is NOT an escrow and must not be reasoned about as one. Writing the row before the deduction is durable, or writing it without the outcome, would recreate the window where a later pass has to guess whether currency was taken. There is no such pass, deliberately: the two guesses available to it are paying out money that was never taken and refunding a purchase that completed, and both create currency.
Recording is fire-and-forget and nothing waits on it. A player never pays latency for bookkeeping.
SendServerBusy(NetworkConnection)
Sends a ServerBusyBroadcast to the connection, informing the client that the server cannot process the request right now. Uses Unreliable channel to avoid amplifying server-side send-queue pressure.
protected void SendServerBusy(NetworkConnection conn)
Parameters
connNetworkConnection
SubscribeToConnectionEvents()
Dispatches disconnects to OnRemoteConnectionStopped(NetworkConnection), before the connection's account is forgotten.
protected void SubscribeToConnectionEvents()
Remarks
Through ConnectionStopping, which the authenticator raises ahead of its
own teardown, so Server.AccountManager.GetAccountNameByConnection still answers inside
OnRemoteConnectionStopped(NetworkConnection). Subscribing to FishNet.Managing.Server.ServerManager.OnRemoteConnectionState
directly put every behaviour after the authenticator, which FishNet initialises first, and so after the
account was gone. Any other authenticator falls back to FishNet's event.
TryBeginInFlightRequest<TRuntime>(NetworkConnection, Func<TRuntime, bool>)
Generic helper to attempt acquiring an in-flight slot from a runtime data container. Caller supplies a lambda that performs the actual add (e.g. runtimeData.InFlightRequests.TryAdd(conn.ClientId, 0)).
protected bool TryBeginInFlightRequest<TRuntime>(NetworkConnection conn, Func<TRuntime, bool> tryAdd) where TRuntime : class, IRuntimeDataContainer
Parameters
Returns
Type Parameters
TRuntime
TryBeginPlayerRequest(NetworkConnection, out PlayerRequestContext, PlayerRequestGate)
Resolves the acting player behind a client request and applies the character-state gate. The single entry point every player-initiated broadcast handler should open with.
protected bool TryBeginPlayerRequest(NetworkConnection conn, out PlayerRequestContext context, PlayerRequestGate gate = PlayerRequestGate.RequireCanAct)
Parameters
connNetworkConnectionThe connection the broadcast arrived on. May be null.
contextPlayerRequestContextThe acting player, or
defaultwhen the request is refused.gatePlayerRequestGateLeave at RequireCanAct unless the request is not an action and something downstream gates the action it leads to.
Returns
- bool
True when the handler may proceed.
Remarks
Usage:
if (!TryBeginPlayerRequest(conn, out PlayerRequestContext request))
{
return;
}
The ingress guard, and whatever this handler answers a refused guard with, stay at the call site — see PlayerRequestContext for why.
The checks here are exactly the ones the hand-written preambles ran, in the order they
ran them, and nothing more. In particular a MISSING character refuses silently rather
than through CanAct(ICharacter), which logs its refusals: the
inline copies returned without a word, and this replaces them rather than changing what
they do. That is also why this does not delegate to
CharacterStateValidation.TryGetPlayerAndValidate, the Shared-assembly cousin that
declares itself canonical and has no callers — it folds the null-character case into
CanAct, and it cannot express SkipCanAct.
conn.FirstObject, not the character mapping table, because that is what the
handlers being replaced used. CharacterSystem's own handlers resolve through
ICharacterMappingData.ConnectionCharacters instead and are NOT interchangeable
with this: the two disagree for a connection mid-hand-off, whose network object exists
before the mapping entry does.
TryCaptureSessionClaim(long, out CharacterSessionLeaseData)
Captures the session claim this server holds for a character, for a write made on that character's behalf. Main thread only.
protected bool TryCaptureSessionClaim(long characterID, out CharacterSessionLeaseData claim)
Parameters
characterIDlongThe character the write is for.
claimCharacterSessionLeaseDataThe claim, when this server holds one.
Returns
- bool
True when a usable claim was captured.
Remarks
Every per-character write quotes the claim it was captured under — the services'
owned writes (PersistOwnedAsync, DeleteAbilityOwnedAsync,
DeleteQuestOwnedAsync) admit a row only while that claim is still held, under the
character's share lock (CharacterWriteGate). A write captured by a session that is
released a moment later therefore cannot land over the next owner's state, an offline
debit, or a trade's last settlement.
Captured here, at the request, and carried with the write. Looked up later, on the
worker, it could be a later session's claim — the character left and came back — and the
write would land under a claim it was never made under. The departure paths take the
claim out of SessionTokens before anything else runs, so a character on its way
out has none: its own rows travel inside the save-and-release, which carries the claim
explicitly (CharacterSystem.SaveAndDespawnCharacter).
A resident character — connected, or a combat-logout body — always holds one, so false means the character is not ours to write: it has left, is leaving, or was evicted. The caller refuses the request rather than change memory it could not persist.
TryEnqueueAsyncWork(Func<Task>, NetworkConnection, long, string)
Enqueues async work and sends ServerBusyBroadcast to the client on failure. Use this for broadcast handlers where the client expects a response.
protected bool TryEnqueueAsyncWork(Func<Task> work, NetworkConnection conn, long entityKey = 0, string callerName = null)
Parameters
workFunc<Task>The async work to enqueue.
connNetworkConnectionThe client connection to notify on failure.
entityKeylongOptional entity key for consistent hashing.
callerNamestringCaller name for diagnostics.
Returns
- bool
True if the work was enqueued successfully.
TryEnqueueAsyncWork(Func<Task>, long, string)
Enqueue a unit of asynchronous work to the centralized AsyncWorker. Returns false when rejected. Logs warnings using the concrete behaviour name for diagnostics.
protected bool TryEnqueueAsyncWork(Func<Task> work, long entityKey = 0, string callerName = null)
Parameters
Returns
TryEnqueueGuardedAsyncWork(Func<Task>, Action<long>, long, long, string)
Enqueues async work that guarantees an ingress guard is released (via releaseGuard)
when the work completes, even if it throws.
protected bool TryEnqueueGuardedAsyncWork(Func<Task> work, Action<long> releaseGuard, long guardKey, long entityKey = 0, string callerName = null)
Parameters
Returns
TryEnqueueMainThread<TQueue>(Action)
Enqueue an action to the specified main-thread queue.
protected bool TryEnqueueMainThread<TQueue>(Action action) where TQueue : class, IMainThreadQueueData
Parameters
actionAction
Returns
Type Parameters
TQueue
TryGetDbService<T>(out T)
Attempts to resolve a database service from the server's database service registry. Encapsulates the null-check on Server.Database.ServiceRegistry and the TryGet call.
protected bool TryGetDbService<T>(out T service) where T : class
Parameters
serviceT
Returns
Type Parameters
T
TryPersistCharacterAttributes(IPlayerCharacter)
Enqueues character attribute data (including currency) persistence for a spend or a payout. Called BEFORE in-memory deduction to ensure the DB reflects the change even if the server crashes before the in-memory state is updated.
protected bool TryPersistCharacterAttributes(IPlayerCharacter character)
Parameters
characterIPlayerCharacter
Returns
- bool
True if the persist was successfully enqueued, false otherwise.
Remarks
The rows quote the session claim held for the character now, captured here, and land only
while it is still held (the service's PersistOwnedAsync). With no claim nothing is
queued and false is returned — the answer every caller already has for a persist that
could not be queued (CharacterCurrency.TrySpend refunds). A refused write clears no
dirty mark: this path clears none at all, so the periodic save carries the values again.
UnsubscribeFromConnectionEvents()
Unsubscribes from whichever source SubscribeToConnectionEvents() chose.
protected void UnsubscribeFromConnectionEvents()