Skip to content

Commit

Permalink
fix: 插件总是会拦截事件
Browse files Browse the repository at this point in the history
test: 添加更多单元测试
  • Loading branch information
Zaitonn committed Nov 30, 2024
1 parent a1550e5 commit 0d4d4a0
Show file tree
Hide file tree
Showing 23 changed files with 545 additions and 39 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ jobs:
dotnet test src/Serein.Tests --logger "GitHubActions;summary.includePassedTests=true;summary.includeSkippedTests=true"

- name: Generate coverage
continue-on-error: true
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
id: coverage
if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && (failure() || success())
run: |
dotnet tool install --global JetBrains.dotCover.CommandLineTools
dotnet dotcover cover-dotnet --Output=AppCoverageReport.xml --ReportType=DetailedXML -- test --no-build
- name: Run codacy-coverage-reporter
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
if: steps.coverage.conclusion != 'skipped'
uses: codacy/[email protected]
with:
api-token: ${{ secrets.CODACY_API_TOKEN }}
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,4 @@ dotnet build

## 📄 License

[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FSereinDev%2FSerein.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FSereinDev%2FSerein?ref=badge_large)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FSereinDev%2FSerein.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FSereinDev%2FSerein?ref=badge_large)
3 changes: 2 additions & 1 deletion src/Serein.Core/AppType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ public enum AppType
Unknown,
Cli,
Lite,
Plus
Plus,
Tests,
}
17 changes: 16 additions & 1 deletion src/Serein.Core/Models/Plugins/Js/JsPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,22 @@ public void Dispose()
GC.SuppressFinalize(this);
}

public bool Invoke(Event @event, CancellationToken cancellationToken, params object[] args)
internal void SetListener(Event @event, Function? func)
{
lock (_eventHandlers)
{
if (func is null)
{
_eventHandlers.TryRemove(@event, out _);
}
else
{
_eventHandlers[@event] = func;
}
}
}

internal bool Invoke(Event @event, CancellationToken cancellationToken, params object[] args)
{
var entered = false;
try
Expand Down
2 changes: 1 addition & 1 deletion src/Serein.Core/Models/Plugins/Js/JsPluginConfig.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace Serein.Core.Models.Plugins.Js;

public class JsPluginConfig
public sealed class JsPluginConfig
{
public static readonly JsPluginConfig Default = new();

Expand Down
1 change: 1 addition & 0 deletions src/Serein.Core/SereinApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ static SereinApp()
"Serein.Cli" => AppType.Cli,
"Serein.Lite" => AppType.Lite,
"Serein.Plus" => AppType.Plus,
"Serein.Tests" => AppType.Tests,
_ => AppType.Unknown,
};

Expand Down
2 changes: 2 additions & 0 deletions src/Serein.Core/Services/CoreService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ public Task StartAsync(CancellationToken cancellationToken)
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("正在停止");
_updateChecker.Dispose();

return Task.CompletedTask;
}

Expand Down
8 changes: 7 additions & 1 deletion src/Serein.Core/Services/Network/UpdateChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

namespace Serein.Core.Services.Network;

public sealed class UpdateChecker
public sealed class UpdateChecker : IDisposable
{
private readonly ILogger _logger;
private readonly System.Timers.Timer _timer;
Expand Down Expand Up @@ -84,4 +84,10 @@ public async Task StartAsync()
await CheckAsync();
}
}

public void Dispose()
{
_timer.Stop();
_timer.Dispose();
}
}
6 changes: 5 additions & 1 deletion src/Serein.Core/Services/Plugins/EventDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ JsPluginLoader jsPluginLoader
private readonly NetPluginLoader _netPluginLoader = netPluginLoader;
private readonly JsPluginLoader _jsPluginLoader = jsPluginLoader;

/// <summary>
/// 分发事件
/// </summary>
/// <returns>如果此事件被拦截则返回false</returns>
internal bool Dispatch(Event @event, params object[] args)
{
_logger.LogDebug("分发事件:{}", @event);
Expand Down Expand Up @@ -61,7 +65,7 @@ internal bool Dispatch(Event @event, params object[] args)
}

cancellationTokenSource.Cancel();
return tasks.Select((t) => !t.IsCompleted || t.Result).Any((b) => !b);
return !tasks.Where((task) => task.IsCompleted).Any((task) => !task.Result);
}

private void DispatchToJsPlugins(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public Command Parse(string? command)
}
#pragma warning restore CA1822

public void SetVariable(string key, object? value)
public void SetVariable(string key, string? value)
{
_pluginManager.SetCommandVariable(key, value);
}
Expand Down
16 changes: 15 additions & 1 deletion src/Serein.Core/Services/Plugins/Js/ScriptInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
using Serein.Core.Services.Plugins.Js.Properties;

using Console = Serein.Core.Services.Plugins.Js.Properties.Console;
using Jint.Native.Function;
using Serein.Core.Models.Plugins;

namespace Serein.Core.Services.Plugins.Js;

Expand Down Expand Up @@ -100,7 +102,19 @@ public object GetService(string type)
var t = Type.GetType(type);
return t?.IsPublic == true
? _serviceProvider.GetRequiredService(t)
: throw new InvalidOperationException("无法获取指定的类型");
: throw new ArgumentException("无法获取指定的类型", nameof(type));
}

public void SetListener(string eventName, JsValue jsValue)
{
ArgumentException.ThrowIfNullOrEmpty(eventName);

if (!Enum.TryParse<Event>(eventName, true, out var @event))
{
throw new ArgumentException("无效的事件名称", nameof(eventName));
}

_jsPlugin.SetListener(@event, jsValue as Function);
}

public string Resolve(params string[] paths) => PluginManager.Resolve(_jsPlugin, paths);
Expand Down
45 changes: 30 additions & 15 deletions src/Serein.Core/Services/Plugins/PluginManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

using Microsoft.Extensions.Logging;
Expand All @@ -20,7 +21,7 @@

namespace Serein.Core.Services.Plugins;

public sealed class PluginManager(
public sealed partial class PluginManager(
ILogger<PluginManager> logger,
IPluginLogger pluginLogger,
JsPluginLoader jsPluginLoader,
Expand All @@ -30,6 +31,9 @@ public sealed class PluginManager(
PermissionManager permissionManager
)
{
[GeneratedRegex(@"^[a-zA-Z][a-zA-Z0-9\-]{2,24}$")]
private static partial Regex GetIdRegex();
private static readonly Regex IdRegex = GetIdRegex();
private static readonly JsonSerializerOptions Options =
new(JsonSerializerOptionsFactory.Common)
{
Expand All @@ -50,35 +54,41 @@ PermissionManager permissionManager
public event EventHandler? PluginsReloading;
public event EventHandler? PluginsLoaded;

public bool Loading { get; private set; }
public bool Reloading { get; private set; }
public bool IsLoading { get; private set; }
public bool IsReloading { get; private set; }

public void ExportVariables(string key, object? value)
{
ExportedVariables.AddOrUpdate(key, value, (_, _) => value);
}

public void SetCommandVariable(string key, object? value)
public void SetCommandVariable(string key, string? value)
{
var str = value?.ToString() ?? string.Empty;
CommandVariables.AddOrUpdate(key, str, (_, _) => str);
if (value == null)
{
CommandVariables.TryRemove(key, out _);
}
else
{
CommandVariables.AddOrUpdate(key, value, (_, _) => value);
}
}

public void Load()
{
try
{
if (Loading)
if (IsLoading)
{
throw new InvalidOperationException("正在加载插件");
}

Loading = true;
IsLoading = true;

if (!Directory.Exists(PathConstants.PluginsDirectory))
{
Directory.CreateDirectory(PathConstants.PluginsDirectory);
Loading = false;
IsLoading = false;
return;
}

Expand All @@ -101,10 +111,15 @@ public void Load()
Options
) ?? throw new InvalidDataException("插件信息为空");

if (string.IsNullOrWhiteSpace(pluginInfo.Id))
if (string.IsNullOrEmpty(pluginInfo.Id))
{
throw new InvalidOperationException("Id不可为空");
}

if(!IdRegex.IsMatch(pluginInfo.Id))
{
throw new InvalidOperationException("Id不符合规范");
}
}
catch (Exception e)
{
Expand Down Expand Up @@ -166,12 +181,12 @@ public void Load()
}
catch (Exception e)
{
_logger.LogDebug(e, "[{}] 插件加载时出现异常", nameof(PluginManager));
_logger.LogDebug(e, "插件加载时出现异常");
throw;
}
finally
{
Loading = false;
IsLoading = false;
_logger.LogDebug("插件加载结束");
}
}
Expand All @@ -190,12 +205,12 @@ public void Unload()

public void Reload()
{
if (Reloading || Loading)
if (IsReloading || IsLoading)
{
throw new InvalidOperationException("正在加载插件");
}

Reloading = true;
IsReloading = true;

try
{
Expand All @@ -206,7 +221,7 @@ public void Reload()
}
finally
{
Reloading = false;
IsReloading = false;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Serein.Core/Services/SentryReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public void Initialize()
options.AutoSessionTracking = true;
options.TracesSampleRate = 1;
options.ProfilesSampleRate = 0.5;
options.AddIntegration(new ProfilingIntegration(TimeSpan.FromMilliseconds(1000)));
options.AddIntegration(new ProfilingIntegration(TimeSpan.FromMilliseconds(500)));

#if DEBUG
// options.Debug = true;
Expand Down
2 changes: 1 addition & 1 deletion src/Serein.Core/Services/Servers/ServerPluginManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public sealed class ServerPluginManager
/// <summary>
/// 禁用插件的扩展名
/// </summary>
public const string DisabledPluginExtension = ".disabled";
public static readonly string DisabledPluginExtension = ".disabled";

public event EventHandler? Updated;
public IReadOnlyList<ServerPlugin> Plugins => _plugins;
Expand Down
6 changes: 5 additions & 1 deletion src/Serein.Core/Utils/CrashHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ internal static class CrashHelper
{
public static string CreateLog(Exception e)
{
SentrySdk.CaptureException(e);
if (SentrySdk.IsEnabled)
{
SentrySdk.CaptureException(e);
}

try
{
Directory.CreateDirectory(PathConstants.LogDirectory + "/crash");
Expand Down
8 changes: 4 additions & 4 deletions src/Serein.Core/Utils/UrlConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ public static class UrlConstants

public static readonly string Docs = "https://sereindev.github.io/";

public static readonly string DocsPlugins = "https://sereindev.github.io/docs/guidance/plugins";
public static readonly string DocsArgument = "https://sereindev.github.io/docs/more/agreement";

public static readonly string DocsVariables =
"https://sereindev.github.io/docs/guidance/variables";
public static readonly string DocsPlugins = "https://sereindev.github.io/docs/guidance/plugins";

public static readonly string DocsMatch = "https://sereindev.github.io/docs/guidance/match";

public static readonly string DocsSchedule =
"https://sereindev.github.io/docs/guidance/schedule";

public static readonly string DocsArgument = "https://sereindev.github.io/docs/more/agreement";
public static readonly string DocsVariables =
"https://sereindev.github.io/docs/guidance/variables";
}
4 changes: 2 additions & 2 deletions src/Serein.Lite/Ui/Function/PluginPage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ private void DisableToolStripMenuItem_Click(object sender, EventArgs e)

private void ReloadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!_pluginManager.Loading && !_pluginManager.Reloading)
if (!_pluginManager.IsLoading && !_pluginManager.IsReloading)
{
Task.Run(_pluginManager.Reload);
}
Expand All @@ -125,7 +125,7 @@ private void LookUpDocsToolStripMenuItem_Click(object sender, EventArgs e)

private void ReloadButton_Click(object sender, EventArgs e)
{
if (!_pluginManager.Loading && !_pluginManager.Reloading)
if (!_pluginManager.IsLoading && !_pluginManager.IsReloading)
{
Task.Run(_pluginManager.Reload);
}
Expand Down
3 changes: 0 additions & 3 deletions src/Serein.Plugins.Demo/Demo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

using Newtonsoft.Json;

using Serein.Core.Models.Plugins.Net;

namespace Serein.Plugins.Demo;
Expand All @@ -13,7 +11,6 @@ public class Demo : PluginBase
public Demo(IServiceProvider serviceProvider)
{
Call();
Console.WriteLine(JsonConvert.DeserializeObject("{}"));
}

public override void Dispose()
Expand Down
1 change: 0 additions & 1 deletion src/Serein.Plugins.Demo/Serein.Plugins.Demo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<ProjectReference Include="..\Serein.Core\Serein.Core.csproj">
<Private>false</Private>
<ExcludeAssets>all</ExcludeAssets>
Expand Down
1 change: 1 addition & 0 deletions src/Serein.Tests/Serein.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
Expand Down
Loading

0 comments on commit 0d4d4a0

Please sign in to comment.