Skip to content

Commit

Permalink
Improved logs and parents handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Pogromca-SCP committed Oct 26, 2023
1 parent 8107183 commit 48147e1
Show file tree
Hide file tree
Showing 7 changed files with 198 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using SLCommandScript.FileScriptsLoader.Helpers;
using SLCommandScript.FileScriptsLoader.Commands;
using FluentAssertions;
using SLCommandScript.Core;
using SLCommandScript.Core.Permissions;
using Moq;
using PluginAPI.Enums;
Expand Down Expand Up @@ -63,6 +64,44 @@ public void InitScriptsLoader_ShouldNotInitialize_WhenProvidedPluginHandlerIsNul
FileScriptCommandBase.ConcurrentExecutionsLimit.Should().Be(0);
}

[TestCase(-9)]
[TestCase(9)]
[TestCase(1)]
public void InitScriptsLoader_ShouldNotInitialize_WhenAnInstanceIsAlreadyInitialized(int execsLimit)
{
// Arrange
var config = new ScriptsLoaderConfig()
{
CustomPermissionsResolver = null,
ScriptExecutionsLimit = execsLimit,
AllowedScriptCommandTypes = 0,
EnableScriptEventHandlers = false
};

HelpersProvider.FileSystemHelper = null;
HelpersProvider.FileSystemWatcherHelperFactory = null;
FileScriptCommandBase.PermissionsResolver = null;
FileScriptCommandBase.ConcurrentExecutionsLimit = 0;
using var loader = new FileScriptsLoader();
var plugin = new TestPlugin();
loader.InitScriptsLoader(plugin, new(_testDirectory, plugin, plugin.GetType(), _emptyTypesArray), config);
var fileSystemHelper = HelpersProvider.FileSystemHelper;
var fileSystemWatcherFactory = HelpersProvider.FileSystemWatcherHelperFactory;
var permissionsResolver = FileScriptCommandBase.PermissionsResolver;
var executionsLimit = FileScriptCommandBase.ConcurrentExecutionsLimit;
var secondLoader = new FileScriptsLoader();
config.ScriptExecutionsLimit *= 2;

// Act
secondLoader.InitScriptsLoader(plugin, new(_testDirectory, plugin, plugin.GetType(), _emptyTypesArray), config);

// Assert
HelpersProvider.FileSystemHelper.Should().Be(fileSystemHelper);
HelpersProvider.FileSystemWatcherHelperFactory.Should().Be(fileSystemWatcherFactory);
FileScriptCommandBase.PermissionsResolver.Should().Be(permissionsResolver);
FileScriptCommandBase.ConcurrentExecutionsLimit.Should().Be(executionsLimit);
}

[TestCase(3)]
[TestCase(7)]
[TestCase(0)]
Expand All @@ -73,7 +112,7 @@ public void InitScriptsLoader_ShouldInitialize_WhenNoDirectoriesAreEnabled(int e
HelpersProvider.FileSystemWatcherHelperFactory = null;
FileScriptCommandBase.PermissionsResolver = null;
FileScriptCommandBase.ConcurrentExecutionsLimit = 0;
var loader = new FileScriptsLoader();
using var loader = new FileScriptsLoader();
var plugin = new TestPlugin();

// Act
Expand Down Expand Up @@ -103,7 +142,7 @@ public void InitScriptsLoader_ShouldLoadCustomPermissionsLoader(int execsLimit)
HelpersProvider.FileSystemWatcherHelperFactory = null;
FileScriptCommandBase.PermissionsResolver = null;
FileScriptCommandBase.ConcurrentExecutionsLimit = 0;
var loader = new FileScriptsLoader();
using var loader = new FileScriptsLoader();
var plugin = new TestPlugin();

// Act
Expand Down Expand Up @@ -133,7 +172,7 @@ public void InitScriptsLoader_ShouldInitialize_WhenEventsAreEnabled()
HelpersProvider.FileSystemWatcherHelperFactory = _testWatcherFactory;
FileScriptCommandBase.PermissionsResolver = null;
FileScriptCommandBase.ConcurrentExecutionsLimit = 0;
var loader = new FileScriptsLoader();
using var loader = new FileScriptsLoader();
var plugin = new TestPlugin();

// Act
Expand Down Expand Up @@ -168,7 +207,7 @@ public void InitScriptsLoader_ShouldInitialize_WhenCommandsAreEnabled(CommandTyp
HelpersProvider.FileSystemWatcherHelperFactory = _testWatcherFactory;
FileScriptCommandBase.PermissionsResolver = null;
FileScriptCommandBase.ConcurrentExecutionsLimit = 0;
var loader = new FileScriptsLoader();
using var loader = new FileScriptsLoader();
var plugin = new TestPlugin();

// Act
Expand Down Expand Up @@ -201,7 +240,7 @@ public void InitScriptsLoader_ShouldInitialize_WhenLoaderConfigIsNull()
HelpersProvider.FileSystemWatcherHelperFactory = _testWatcherFactory;
FileScriptCommandBase.PermissionsResolver = null;
FileScriptCommandBase.ConcurrentExecutionsLimit = 0;
var loader = new FileScriptsLoader();
using var loader = new FileScriptsLoader();
var plugin = new TestPlugin();

// Act
Expand Down Expand Up @@ -242,6 +281,31 @@ public void Dispose_ShouldProperlyCleanupResources()
fileSystemMock.VerifyAll();
fileSystemMock.VerifyNoOtherCalls();
}

[Test]
public void Dispose_ShouldNotCleanupHelpers_WhenAnInstanceIsStillActive()
{
// Arrange
var plugin = new TestPlugin();
var fileSystemMock = new Mock<IFileSystemHelper>(MockBehavior.Strict);
fileSystemMock.Setup(x => x.DirectoryExists(It.IsAny<string>())).Returns(true);
HelpersProvider.FileSystemHelper = fileSystemMock.Object;
HelpersProvider.FileSystemWatcherHelperFactory = _testWatcherFactory;
using var loader = new FileScriptsLoader();
loader.InitScriptsLoader(plugin, new(_testDirectory, plugin, plugin.GetType(), _emptyTypesArray), null);
var secondLoader = new FileScriptsLoader();

// Act
secondLoader.Dispose();

// Assert
FileScriptCommandBase.ConcurrentExecutionsLimit.Should().Be(10);
FileScriptCommandBase.PermissionsResolver.Should().NotBeNull();
HelpersProvider.FileSystemHelper.Should().NotBeNull();
HelpersProvider.FileSystemWatcherHelperFactory.Should().NotBeNull();
fileSystemMock.VerifyAll();
fileSystemMock.VerifyNoOtherCalls();
}
#endregion
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ private static Mock<IFileSystemWatcherHelper> MakeWatcherMock()
watcherMock.SetupAdd(x => x.Changed += It.IsAny<FileSystemEventHandler>());
watcherMock.SetupAdd(x => x.Deleted += It.IsAny<FileSystemEventHandler>());
watcherMock.SetupAdd(x => x.Renamed += It.IsAny<RenamedEventHandler>());
watcherMock.SetupAdd(x => x.Error += It.IsAny<ErrorEventHandler>());
return watcherMock;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ private static Mock<IFileSystemWatcherHelper> MakeWatcherMock()
watcherMock.SetupAdd(x => x.Created += It.IsAny<FileSystemEventHandler>());
watcherMock.SetupAdd(x => x.Deleted += It.IsAny<FileSystemEventHandler>());
watcherMock.SetupAdd(x => x.Renamed += It.IsAny<RenamedEventHandler>());
watcherMock.SetupAdd(x => x.Error += It.IsAny<ErrorEventHandler>());
return watcherMock;
}

Expand Down
78 changes: 55 additions & 23 deletions SLCommandScript.FileScriptsLoader/FileScriptsLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
using System.Collections.Generic;
using SLCommandScript.FileScriptsLoader.Loader;
using SLCommandScript.Core;
using SLCommandScript.Core.Permissions;
using SLCommandScript.Core.Reflection;
using SLCommandScript.FileScriptsLoader.Commands;
using PluginAPI.Enums;
using System;
using SLCommandScript.Core.Permissions;
using SLCommandScript.Core.Reflection;

namespace SLCommandScript.FileScriptsLoader;

Expand All @@ -22,6 +22,11 @@ public class FileScriptsLoader : IScriptsLoader
/// </summary>
private const string LoaderPrefix = "FileScriptsLoader: ";

/// <summary>
/// Contains a reference to initialized instance.
/// </summary>
private static FileScriptsLoader _instance = null;

/// <summary>
/// Prints a message to server log.
/// </summary>
Expand Down Expand Up @@ -73,37 +78,24 @@ public void InitScriptsLoader(object plugin, PluginHandler handler, ScriptsLoade
return;
}

loaderConfig ??= new();
IPermissionsResolver permissionsResolver;

if (string.IsNullOrWhiteSpace(loaderConfig.CustomPermissionsResolver))
if (_instance is not null)
{
PrintLog("Using default permissions resolver.");
permissionsResolver = new VanillaPermissionsResolver();
}
else
{
permissionsResolver = CustomTypesUtils.MakeCustomTypeInstance<IPermissionsResolver>(loaderConfig.CustomPermissionsResolver, out var message);

if (permissionsResolver is null)
{
PrintError(message);
permissionsResolver = new VanillaPermissionsResolver();
}
else
{
PrintLog("Custom permissions resolver loaded successfully.");
}
PrintError("Only one instance of FileScriptsLoader can be initialized.");
return;
}

FileScriptCommandBase.PermissionsResolver = permissionsResolver;
_instance = this;
PrintLog("Initializing scripts loader...");
loaderConfig ??= new();
FileScriptCommandBase.PermissionsResolver = LoadPermissionsResolver(loaderConfig.CustomPermissionsResolver);
FileScriptCommandBase.ConcurrentExecutionsLimit = loaderConfig.ScriptExecutionsLimit;
HelpersProvider.FileSystemHelper ??= new FileSystemHelper();
HelpersProvider.FileSystemWatcherHelperFactory ??= CreateWatcher;
LoadDirectory(plugin, $"{handler.PluginDirectoryPath}/scripts/events/", loaderConfig.EnableScriptEventHandlers ? CommandType.Console : 0);
LoadDirectory(null, $"{handler.PluginDirectoryPath}/scripts/ra/", loaderConfig.AllowedScriptCommandTypes & CommandType.RemoteAdmin);
LoadDirectory(null, $"{handler.PluginDirectoryPath}/scripts/server/", loaderConfig.AllowedScriptCommandTypes & CommandType.Console);
LoadDirectory(null, $"{handler.PluginDirectoryPath}/scripts/client/", loaderConfig.AllowedScriptCommandTypes & CommandType.GameConsole);
PrintLog("Scripts loader is initialized.");
}

/// <summary>
Expand All @@ -125,6 +117,8 @@ public void Dispose()
/// </summary>
protected void PerformCleanup()
{
PrintLog("Disabling scripts loader...");

foreach (var dir in _registeredDirectories)
{
dir.Dispose();
Expand All @@ -133,10 +127,46 @@ protected void PerformCleanup()
_registeredDirectories.Clear();
_eventsDirectory?.Dispose();
_eventsDirectory = null;

if (!ReferenceEquals(_instance, this))
{
PrintLog("Scripts loader is disabled but static helpers are still active.");
return;
}

FileScriptCommandBase.ConcurrentExecutionsLimit = 0;
FileScriptCommandBase.PermissionsResolver = null;
HelpersProvider.FileSystemHelper = null;
HelpersProvider.FileSystemWatcherHelperFactory = null;
_instance = null;
PrintLog("Scripts loader is disabled.");
}

/// <summary>
/// Loads permissions resolver instance to use.
/// </summary>
/// <param name="resolverToUse">Custom type of resolver to use.</param>
/// <returns>Loaded permissions resolver instance.</returns>
private IPermissionsResolver LoadPermissionsResolver(string resolverToUse)
{
if (string.IsNullOrWhiteSpace(resolverToUse))
{
PrintLog("Using default permissions resolver.");
return new VanillaPermissionsResolver();
}

var permissionsResolver = CustomTypesUtils.MakeCustomTypeInstance<IPermissionsResolver>(resolverToUse, out var message);

if (permissionsResolver is null)
{
PrintError(message);
return new VanillaPermissionsResolver();
}
else
{
PrintLog("Custom permissions resolver loaded successfully.");
return permissionsResolver;
}
}

/// <summary>
Expand All @@ -159,10 +189,12 @@ private void LoadDirectory(object plugin, string directory, CommandType handlerT

if (plugin is null)
{
PrintLog($"Initializing commands directory for {handlerType}...");
_registeredDirectories.Add(new CommandsDirectory(HelpersProvider.FileSystemWatcherHelperFactory(directory, null, true), handlerType));
}
else
{
PrintLog("Initializing events directory...");
_eventsDirectory = new EventsDirectory(plugin, HelpersProvider.FileSystemWatcherHelperFactory(directory, EventsDirectory.ScriptFilesFilter, false));
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System;
using System.IO;

using PluginAPI.Core;

namespace SLCommandScript.FileScriptsLoader.Helpers;

/// <summary>
Expand Down Expand Up @@ -34,6 +32,11 @@ public interface IFileSystemWatcherHelper : IDisposable
/// Event invoked on file deletion.
/// </summary>
event FileSystemEventHandler Deleted;

/// <summary>
/// Event invoked on error.
/// </summary>
event ErrorEventHandler Error;
}

/// <summary>
Expand Down Expand Up @@ -71,6 +74,11 @@ public class FileSystemWatcherHelper : IFileSystemWatcherHelper
/// </summary>
public event FileSystemEventHandler Deleted { add => _watcher.Deleted += value; remove => _watcher.Deleted -= value; }

/// <summary>
/// Event invoked on error.
/// </summary>
public event ErrorEventHandler Error { add => _watcher.Error += value; remove => _watcher.Error -= value; }

/// <summary>
/// Initializes new file system watcher.
/// </summary>
Expand All @@ -86,11 +94,6 @@ public FileSystemWatcherHelper(string path, string filter, bool includeSubdirect
IncludeSubdirectories = includeSubdirectories,
EnableRaisingEvents = true
};

_watcher.Created += (obj, args) => Log.Debug($"Created: {args.Name}", "FilesWatcher: ");
_watcher.Changed += (obj, args) => Log.Debug($"Changed: {args.Name}", "FilesWatcher: ");
_watcher.Renamed += (obj, args) => Log.Debug($"Renamed: {args.OldName} -> {args.Name}", "FilesWatcher: ");
_watcher.Deleted += (obj, args) => Log.Debug($"Deleted: {args.Name}", "FilesWatcher: ");
}

/// <summary>
Expand Down
Loading

0 comments on commit 48147e1

Please sign in to comment.