diff --git a/VisualPinball.Plugins.Test/PluginHostTests.cs b/VisualPinball.Plugins.Test/PluginHostTests.cs index 463238e4ba..b209803846 100644 --- a/VisualPinball.Plugins.Test/PluginHostTests.cs +++ b/VisualPinball.Plugins.Test/PluginHostTests.cs @@ -53,8 +53,23 @@ public void RequiredProviderPrecedesConsumerAndCleanupReversesStart() Assert.That(calls.Count(call => call.EndsWith(":dispose")), Is.EqualTo(2)); } - [TestCase("initialize")] - [TestCase("prepare")] + [Test] + public void FailedLifecycleLoggingDoesNotInterruptCleanup() + { + var calls = new List(); + 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) { diff --git a/VisualPinball.Plugins/Api/PluginLog.cs b/VisualPinball.Plugins/Api/PluginLog.cs index 79c48c8183..b45533dd41 100644 --- a/VisualPinball.Plugins/Api/PluginLog.cs +++ b/VisualPinball.Plugins/Api/PluginLog.cs @@ -42,6 +42,12 @@ public interface IPluginLog void Write(PluginLogLevel level, string message, Exception? exception = null); } + /// Optionally persists the most recent lifecycle marker before a native hook runs. + 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); diff --git a/VisualPinball.Plugins/Runtime/PluginHost.cs b/VisualPinball.Plugins/Runtime/PluginHost.cs index ca4328d6a4..055313bfb6 100644 --- a/VisualPinball.Plugins/Runtime/PluginHost.cs +++ b/VisualPinball.Plugins/Runtime/PluginHost.cs @@ -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; @@ -90,7 +91,7 @@ internal void Track(Task hook) /// Completes when every hook running now has finished. 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 _factories; private readonly Dictionary _statuses; @@ -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()).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(); @@ -455,6 +458,7 @@ private async Task InvokeAsync(Instance entry, PluginPhase phase, Func public class CabinetPhysicsTests { + [Test] + public void LateInputDoesNotCreatePhysicsStateAfterEventQueueDisposal() + { + var playfield = new GameObject("Late input test"); + playfield.SetActive(false); + try { + var engine = playfield.AddComponent(); + 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() { diff --git a/VisualPinball.Unity/VisualPinball.Unity/Diagnostics/NLogPluginLog.cs b/VisualPinball.Unity/VisualPinball.Unity/Diagnostics/NLogPluginLog.cs index 628b7265d5..16d87ddd37 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/Diagnostics/NLogPluginLog.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/Diagnostics/NLogPluginLog.cs @@ -24,13 +24,25 @@ namespace VisualPinball.Unity /// /// A plugin's log, written to NLog under the logger "Plugin.<plugin id>". /// - 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)); diff --git a/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs b/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs index d423bb0318..c069207354 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs @@ -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); + } } ///