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
19 changes: 17 additions & 2 deletions VisualPinball.Plugins.Test/PluginHostTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,23 @@
Assert.That(calls.Count(call => call.EndsWith(":dispose")), Is.EqualTo(2));
}

[TestCase("initialize")]
[TestCase("prepare")]
[Test]
public void FailedLifecycleLoggingDoesNotInterruptCleanup()
{
var calls = new List<string>();
var factory = new TestFactory("test.logging", calls);
var log = new TextPluginLog(message => {
if (message.Contains("Stop")) throw new IOException("The diagnostic sink is unavailable.");
});
var host = new PluginHost(new[] { factory }, new PluginConfigurationStore(_directory), new OwnerScheduler(),
new PluginCapabilities(), new PluginResourceRegistry(), "windows", pluginLog: _ => log);
Run(host, host.PrepareAndStartAsync(_game, "test", "Test", "controller", 1, default));
Run(host, host.StopGameAsync());
Assert.That(calls, Does.Contain("test.logging:stop").And.Contain("test.logging:dispose"));
}

[TestCase("initialize")]
[TestCase("prepare")]
[TestCase("start")]
public void ProviderFailureBlocksDependentsWhileIndependentPluginRuns(string failAt)
{
Expand Down Expand Up @@ -295,7 +310,7 @@
internal int FocusThread;
internal bool AsyncInitialize;
internal bool CleanupWasCanceled;
internal bool NeverFinishStop;

Check warning on line 313 in VisualPinball.Plugins.Test/PluginHostTests.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Field 'TestFactory.NeverFinishStop' is never assigned to, and will always have its default value false

Check warning on line 313 in VisualPinball.Plugins.Test/PluginHostTests.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Field 'TestFactory.NeverFinishStop' is never assigned to, and will always have its default value false

Check warning on line 313 in VisualPinball.Plugins.Test/PluginHostTests.cs

View workflow job for this annotation

GitHub Actions / test (macos-latest)

Field 'TestFactory.NeverFinishStop' is never assigned to, and will always have its default value false

Check warning on line 313 in VisualPinball.Plugins.Test/PluginHostTests.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Field 'TestFactory.NeverFinishStop' is never assigned to, and will always have its default value false

Check warning on line 313 in VisualPinball.Plugins.Test/PluginHostTests.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Field 'TestFactory.NeverFinishStop' is never assigned to, and will always have its default value false
internal Task? StopCompletion;
internal Task? InitializeCompletion;
internal Task<PluginActionResult>? ApplyCompletion;
Expand Down
6 changes: 6 additions & 0 deletions VisualPinball.Plugins/Api/PluginLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ public interface IPluginLog
void Write(PluginLogLevel level, string message, Exception? exception = null);
}

/// <summary>Optionally persists the most recent lifecycle marker before a native hook runs.</summary>
public interface IPluginLifecycleLog : IPluginLog
{
void RecordLifecycle(string message);
}

public static class PluginLogExtensions
{
public static void Debug(this IPluginLog log, string message) => log.Write(PluginLogLevel.Debug, message);
Expand Down
31 changes: 27 additions & 4 deletions VisualPinball.Plugins/Runtime/PluginHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ private sealed class Instance
{
internal readonly IPlayerPluginFactory Factory;
internal readonly IPlayerPlugin Plugin;
internal readonly IPluginLog Log;
internal readonly ResourceScope ApplicationScope;
internal readonly ResourceScope GameScope = new ResourceScope();
internal bool Prepared;
Expand All @@ -90,7 +91,7 @@ internal void Track(Task hook)
/// <summary>Completes when every hook running now has finished.</summary>
internal Task RunningHooks() { lock (_hooks) return _hooks.Count == 0 ? Task.CompletedTask : Task.WhenAll(_hooks.ToArray()); }
internal PluginSettingsSnapshot? Settings;
internal Instance(IPlayerPluginFactory factory, IPlayerPlugin plugin, ResourceScope applicationScope) { Factory = factory; Plugin = plugin; ApplicationScope = applicationScope; }
internal Instance(IPlayerPluginFactory factory, IPlayerPlugin plugin, ResourceScope applicationScope, IPluginLog log) { Factory = factory; Plugin = plugin; ApplicationScope = applicationScope; Log = log; }
}
private readonly Dictionary<string, IPlayerPluginFactory> _factories;
private readonly Dictionary<string, PluginStatus> _statuses;
Expand Down Expand Up @@ -340,8 +341,10 @@ public async Task PrepareAndStartAsync(GameIdentity identity, string packagePath
var issues = factory.Schema.Validate(settings).Concat(factory.SettingsProvider?.Validate(new PluginChoiceRequest(identity, settings, Platform) { Package = new PluginPackageReference(packagePath, title) }) ?? Array.Empty<PluginValidationIssue>()).ToArray();
if (issues.Length > 0) throw new PluginConfigurationException(string.Join("; ", issues.Select(issue => issue.Field + ": " + issue.Message)));
if (Configuration.Read(descriptor, factory.Schema).SchemaVersion > factory.Schema.Version || Configuration.Read(descriptor, factory.Schema, identity).SchemaVersion > factory.Schema.Version) throw new PluginConfigurationException("Configuration requires a newer plugin version.");
var plugin = factory.Create(new PluginApplicationContext(descriptor, Configuration, Scheduler, Capabilities, Resources, application, _pluginLog(descriptor)));
var entry = new Instance(factory, plugin, application);
var log = _pluginLog(descriptor);
RecordLifecycle(log, "Creating plugin instance.");
var plugin = factory.Create(new PluginApplicationContext(descriptor, Configuration, Scheduler, Capabilities, Resources, application, log));
var entry = new Instance(factory, plugin, application, log);
_entered.Add(entry);
await InvokeAsync(entry, PluginPhase.Initialize, token => plugin.InitializeAsync(token), gameToken).ConfigureAwait(false);
await Scheduler.Switch();
Expand Down Expand Up @@ -455,14 +458,30 @@ private async Task InvokeAsync(Instance entry, PluginPhase phase, Func<Cancellat
SetStatus(entry.Factory.Descriptor.Id, PluginState.Starting, phase.ToString(), phase);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
deadline.CancelAfter(StartupTimeout);
RecordLifecycle(entry.Log, $"Entering plugin hook {phase}.");
try { await AwaitHookAsync(entry, invoke(deadline.Token), deadline.Token).ConfigureAwait(false); }
catch (HookDeadlineException error) {
await Scheduler.Switch(); Abandon(entry, error.Hook);
if (cancellation.IsCancellationRequested) throw new OperationCanceledException(cancellation);
throw;
}
await Scheduler.Switch();
RecordLifecycle(entry.Log, $"Completed plugin hook {phase}.");
}

private static void RecordLifecycle(IPluginLog log, string message)
{
try {
if (log is IPluginLifecycleLog lifecycle) {
lifecycle.RecordLifecycle(message);
} else {
log.Info(message);
}
} catch (Exception) {
// Diagnostics must not keep a plugin from starting or releasing resources.
}
}

private async Task AwaitHookAsync(Instance entry, Task hook, CancellationToken deadline)
{
entry.Track(hook);
Expand Down Expand Up @@ -630,6 +649,7 @@ private async Task CleanupAsync(Instance entry, CancellationToken cleanup)
if (entry.Prepared) {
using var stopDeadline = CancellationTokenSource.CreateLinkedTokenSource(cleanup);
stopDeadline.CancelAfter(CleanupTimeout);
RecordLifecycle(entry.Log, "Entering plugin hook Stop.");
try { await AwaitHookAsync(entry, entry.Plugin.StopGameAsync(stopDeadline.Token), stopDeadline.Token).ConfigureAwait(false); await Scheduler.Switch(); }
catch (HookDeadlineException error) { await Scheduler.Switch(); Abandon(entry, error.Hook); return; }
catch (OperationCanceledException) when (stopDeadline.IsCancellationRequested) {
Expand All @@ -640,11 +660,14 @@ private async Task CleanupAsync(Instance entry, CancellationToken cleanup)
SafeDispose(entry.GameScope);
using var shutdownDeadline = CancellationTokenSource.CreateLinkedTokenSource(cleanup);
shutdownDeadline.CancelAfter(CleanupTimeout);
RecordLifecycle(entry.Log, "Entering plugin hook Shutdown.");
try { await AwaitHookAsync(entry, entry.Plugin.ShutdownAsync(shutdownDeadline.Token), shutdownDeadline.Token).ConfigureAwait(false); await Scheduler.Switch(); }
catch (HookDeadlineException error) { await Scheduler.Switch(); Abandon(entry, error.Hook); return; }
catch (OperationCanceledException) { await Scheduler.Switch(); }
catch (Exception error) { await Scheduler.Switch(); _error(id + " / Shutdown", error); }
SafeDispose(entry.ApplicationScope); SafeDispose(entry.Plugin);
RecordLifecycle(entry.Log, "Disposing plugin and application resources.");
SafeDispose(entry.ApplicationScope); SafeDispose(entry.Plugin);
RecordLifecycle(entry.Log, "Disposed plugin and application resources.");
if (!keepDiagnostic) SetStatus(id, PluginState.Available, "Stopped");
}
private void RebuildDispatch()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,23 @@ namespace VisualPinball.Unity.Test
/// </summary>
public class CabinetPhysicsTests
{
[Test]
public void LateInputDoesNotCreatePhysicsStateAfterEventQueueDisposal()
{
var playfield = new GameObject("Late input test");
playfield.SetActive(false);
try {
var engine = playfield.AddComponent<PhysicsEngine>();
var field = typeof(PhysicsEngine).GetField("_ctx", BindingFlags.Instance | BindingFlags.NonPublic);
var context = (PhysicsEngineContext)field.GetValue(engine);
context.EventQueue.Ref.Dispose();

engine.MutateState((ref PhysicsState _) => Assert.Fail("Late input ran after physics disposal."));
} finally {
Object.DestroyImmediate(playfield);
}
}

[Test]
public void OscillatorTracksAnalyticStepResponse()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,25 @@ namespace VisualPinball.Unity
/// <summary>
/// A plugin's log, written to NLog under the logger "Plugin.&lt;plugin id&gt;".
/// </summary>
public sealed class NLogPluginLog : IPluginLog
public sealed class NLogPluginLog : IPluginLifecycleLog
{
private readonly Logger _logger;
private readonly string _pluginId;

public NLogPluginLog(PluginDescriptor plugin)
{
_logger = LogManager.GetLogger("Plugin." + plugin.Id);
_pluginId = plugin.Id;
_logger = LogManager.GetLogger("Plugin." + _pluginId);
}

void IPluginLifecycleLog.RecordLifecycle(string message)
{
var data = new DiagnosticsWriter();
data.Add("plugin", _pluginId);
data.Add("state", message);
data.Add("utc", DateTime.UtcNow.ToString("O"));
// Diagnostics listeners save the current snapshot before this call returns.
DiagnosticsContext.Set("Plugin hook", data);
}

public bool IsEnabled(PluginLogLevel level) => _logger.IsEnabled(Map(level));
Expand Down
10 changes: 8 additions & 2 deletions VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,14 @@ internal void MutateState(InputAction action)
return;
}

var state = _ctx.CreateState();
action(ref state);
lock (_ctx.PhysicsLock) {
// Input System callbacks can outlive the native state during table teardown.
if (!_ctx.EventQueue.Ref.IsCreated) {
return;
}
var state = _ctx.CreateState();
action(ref state);
}
}

/// <summary>
Expand Down
Loading