Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ jobs:
with:
repository: HosihikariFramework/PluginAbstractions
path: Plugin.Abstractions
ref: 2e2c8fc1d794bb3ba78f73b3f90fbe338f5a0a30
ref: 59461a7d261050b82c43f009b062651050503984

- uses: actions/setup-dotnet@v4
with:
Expand Down
115 changes: 110 additions & 5 deletions src/Hosihikari.Carrier.Endstone/PluginEnableGate.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Hosihikari;
using Hosihikari.Binding.Endstone;
using Microsoft.Extensions.Logging;

Expand All @@ -8,11 +9,12 @@ namespace Hosihikari.Carrier.Endstone;
/// Carrier components start during the carrier's <c>onLoad</c>, but Endstone rejects both
/// listener registration and scheduler submissions until the plugin is enabled — neither call
/// fails loudly, so a component that touched them early would end up "started" with nothing
/// attached. This gate polls the enable flag and then hops to the server thread through the
/// scheduler, which is accepted from that point on.
/// attached.
/// <para>
/// Only the enable flag is read from the polling thread; every call that touches carrier state
/// happens inside the callback, on the server thread.
/// The enable is normally observed through <see cref="CarrierEnableSignal"/>, which the carrier
/// raises from its own <c>onEnable</c> on the server thread; <see cref="RunNow"/> then runs the
/// callback right there, during enable. The poll timer is only a fallback (and the timeout), for
/// the case where the signal never arrives.
/// </para>
/// </remarks>
public sealed class PluginEnableGate : IDisposable
Expand Down Expand Up @@ -53,12 +55,76 @@ private PluginEnableGate(Plugin plugin, Action onEnabled, ILogger? logger, TimeS
return null;
}

var gate = new PluginEnableGate(plugin, onEnabled, logger, timeout ?? TimeSpan.FromSeconds(30));
// Generous on purpose: the wait spans the carrier's whole startup. A server with a large
// world loads for well over a minute before plugins are enabled, and giving up early
// leaves the capability dead for the rest of the session — far worse than a late start.
var gate = new PluginEnableGate(plugin, onEnabled, logger, timeout ?? TimeSpan.FromMinutes(5));

gate._timer = new Timer(static state => ((PluginEnableGate)state!).Poll(), gate,
PollInterval, PollInterval);
CarrierEnableSignal.Subscribe(gate.OnCarrierEnabled);

// The signal may have been raised between the isEnabled check above and this
// subscription, which would leave the gate waiting for an event already past. Take the
// same path the signal takes, not Poll: this lands inside the enable, where the thread
// check in Poll is known to answer wrong.
if (CarrierEnableSignal.HasRaised)
{
gate.RunNow();
}

return gate;
}

/// <summary>The carrier announced its own enable; settle immediately.</summary>
/// <remarks>
/// Runs on whatever thread raised the signal, which is the carrier's <c>onEnable</c> — the
/// one instant the enabled flag is already set. The thread check is deliberately skipped
/// here: during <c>EndstoneServer::init</c> the server thread id is not recorded yet, so
/// <c>isPrimaryThread()</c> answers false and the callback would be queued onto a tick that
/// runs only after every child <c>OnEnable</c> has already returned.
/// </remarks>
private void OnCarrierEnabled() => RunNow();

/// <summary>Settles the gate on the calling thread, without a thread check.</summary>
/// <remarks>
/// Only correct when the caller already knows it is on the server thread — the signal, and
/// the late-subscription backstop in <see cref="RunWhenEnabled"/>. The check is skipped
/// because <c>isPrimaryThread()</c> answers false during <c>EndstoneServer::init</c>: the
/// server thread id is not recorded yet, so it falls through to comparing <c>mainThread()</c>
/// (server.cpp:693-705), and the callback would be queued onto a tick that runs only after
/// every child <c>OnEnable</c> has already returned.
/// </remarks>
private void RunNow()
{
if (Interlocked.Exchange(ref _claimed, 1) != 0)
{
return;
}

Interlocked.Exchange(ref _timer, null)?.Dispose();

if (_disposed)
{
return;
}

try
{
_onEnabled();
}
catch (Exception exception)
{
_logger?.LogError(exception, "The deferred start threw on the carrier enable.");
}
}

/// <summary>The poll path: the timeout, and a timer that beat the signal.</summary>
/// <remarks>
/// Reached from a timer thread. Its claim has to be released again by running synchronously
/// whenever the signal has already been raised — see the branch below for why handing that
/// case to the scheduler loses the race.
/// </remarks>
private void Poll()
{
if (_disposed)
Expand Down Expand Up @@ -92,6 +158,29 @@ private void Poll()
return;
}

// Run it here when this really is the server thread, and also whenever the signal has
// already been raised: in that case the carrier is genuinely enabled, and the timer can
// otherwise steal the claim from the signal just before it fires — it would then hand the
// work to a tick that runs after every child OnEnable has already returned. The thread
// check cannot be relied on to tell those apart: during EndstoneServer::init it answers
// false even on the server thread (server.cpp:693-705).
if (IsServerThread() || CarrierEnableSignal.HasRaised)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve server-thread execution when the timer wins the claim

If the timer observes isEnabled() and claims the gate immediately before the carrier raises its signal, the signal handler returns because _claimed is already set. The timer can then observe HasRaised == true and execute _onEnabled() directly on its ThreadPool thread. A raised signal establishes that enable occurred, not that the current thread is the server thread. This violates the gate's thread-affinity contract and causes EventPublisherComponent.Register to register native listeners from a background thread, potentially concurrently with child plugin enable callbacks. Keep direct execution on the signal's server thread; a timer-owned callback must retain server-thread dispatch rather than bypassing it based on HasRaised.

Useful? React with 👍 / 👎.

{
try
{
if (!_disposed)
{
_onEnabled();
}
}
catch (Exception exception)
{
_logger?.LogError(exception, "The deferred start threw on the server thread.");
}

return;
}

try
{
// The carrier accepts scheduler work now that the plugin is enabled; the callback
Expand All @@ -110,10 +199,26 @@ private void Poll()
}
}

private bool IsServerThread()
{
try
{
return _plugin.Interop.getServer()?.isPrimaryThread() ?? false;
}
catch
{
// A probe failure must not lose the start; falling back to the scheduler is correct
// on every thread, only slower.
return false;
}
}

/// <inheritdoc/>
public void Dispose()
{
_disposed = true;

CarrierEnableSignal.Unsubscribe(OnCarrierEnabled);
Interlocked.Exchange(ref _timer, null)?.Dispose();
}
}
Loading