From 1eade9ce316ec5637a0d28ef328b43d0d133c485 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=88=E7=BA=BE?= Date: Thu, 26 Nov 2026 17:04:19 +0800 Subject: [PATCH] =?UTF-8?q?style:=20=E6=8C=89=20FormatterConfig=20?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E6=A0=BC=E5=BC=8F=E5=B9=B6=E5=8A=A0=20CI=20?= =?UTF-8?q?=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit .clang-format 与 .editorconfig 取自 FormatterConfig,逐字节相同。 dotnet format whitespace 收敛了 PluginManager.cs 的既有空白漂移。 CI 的 format job:clang-format(钉 23.1.4)查那一个 probe.c, .editorconfig 的空白规则由空白步骤查,C# 的 csharp_* 规则交给 dotnet format whitespace —— 只有它会执行这些规则。 --- .clang-format | 131 ++ .editorconfig | 211 +++ .github/workflows/verify.yml | 51 +- host/DiagnosticsPluginLoader.cs | 13 +- host/GuardedPluginLoader.cs | 28 +- host/HookPluginLoader.cs | 6 +- host/Hosihikari.PluginManager.Host.csproj | 12 +- host/PinnedPluginLoader.cs | 11 +- host/Program.cs | 1554 +++++++++++------ host/RegressionChecks.cs | 916 +++++++--- host/ScriptPluginLoader.cs | 10 +- host/ThrowingPluginLoader.cs | 7 +- src/AssemblyPluginHandle.cs | 7 +- src/AssemblyPluginLoader.cs | 23 +- src/CarrierComponentContext.cs | 3 +- src/CarrierStartup.cs | 142 +- src/CoreText.cs | 14 +- src/DependencyGraph.cs | 8 +- src/DependencyVersion.cs | 51 +- src/EventBus.cs | 45 +- src/Hosihikari.PluginManager.csproj | 20 +- src/ManifestReader.cs | 117 +- src/NativeForwardingLoggerProvider.cs | 33 +- src/NativeHostingEntry.cs | 83 +- src/PluginContext.cs | 4 +- src/PluginInfo.cs | 3 +- src/PluginManager.cs | 472 +++-- src/PluginScope.cs | 95 +- src/PluginServiceRegistry.cs | 6 +- test/Bar/Bar.csproj | 30 +- test/Bar/BarPlugin.cs | 6 +- test/Bindings.Stub/Bindings.Stub.csproj | 21 +- test/Foo/Foo.csproj | 36 +- test/Foo/FooPlugin.cs | 15 +- test/Lib/Lib.csproj | 2 - test/NativeProbe/NativeProbe.csproj | 30 +- test/NativeProbe/NativeProbePlugin.cs | 1 - test/Reloadable/Reloadable.csproj | 36 +- test/Reloadable/ReloadablePlugin.cs | 5 +- test/Retained/Retained.csproj | 36 +- .../Hosihikari.Testing.Smoke.csproj | 2 - testing/Hosihikari.Testing.Smoke/Program.cs | 187 +- .../Hosihikari.Testing.csproj | 2 - .../PluginManagerHarness.cs | 49 +- testing/Hosihikari.Testing/PluginTestHost.cs | 30 +- testing/Hosihikari.Testing/TestEventBus.cs | 23 +- .../Hosihikari.Testing/TestPluginContext.cs | 11 +- testing/Hosihikari.Testing/TestPluginScope.cs | 91 +- .../Hosihikari.Testing/TestServiceRegistry.cs | 7 +- tools/Build/Hosihikari.Plugin.Build.csproj | 32 +- .../build/Hosihikari.Plugin.Build.targets | 59 +- .../Hosihikari.Plugin.Build.targets | 8 +- tools/Pack/Hosihikari.Plugin.Pack.csproj | 2 - tools/Pack/PackText.cs | 14 +- tools/Pack/Packager.cs | 395 +++-- tools/Pack/Program.cs | 20 +- 56 files changed, 3645 insertions(+), 1581 deletions(-) create mode 100644 .clang-format create mode 100644 .editorconfig diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..c2e8798 --- /dev/null +++ b/.clang-format @@ -0,0 +1,131 @@ +--- +Language: Cpp +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align + +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true + +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + +AlignEscapedNewlines: Right +AlignOperands: true + +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 + +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: false + +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: Always + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true + +BreakBeforeBinaryOperators: None +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeComma +BreakInheritanceList: BeforeComma +BreakStringLiterals: false + +ColumnLimit: 120 +CommentPragmas: "^ IWYU pragma:" +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false + +EmptyLineAfterAccessModifier: Leave +EmptyLineBeforeAccessModifier: Leave +ExperimentalAutoDetectBinPacking: false +ForEachMacros: [] +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentWidth: 4 +IndentWrappedFunctionNames: false + +InsertNewlineAtEOF: true +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: OuterScope +MacroBlockBegin: "" +MacroBlockEnd: "" +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None + +PenaltyBreakBeforeFirstCallParameter: 400 +PenaltyBreakComment: 50 +PenaltyBreakFirstLessLess: 500 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 100000 + +PointerAlignment: Left +ReflowComments: true +SortIncludes: Never + +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false + +Standard: Latest +TabWidth: 4 +UseTab: Never +... diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..8eb3430 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,211 @@ +# editorconfig.org + +# top-most EditorConfig file +root = true + +# Default settings: +# A newline ending every file +# Use 4 spaces as indentation +[*] +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +# Specify UTF-8 without byte-order mark +[*.{csproj,locproj,nativeproj,proj,resx,slnx,vbproj}] +charset = utf-8 + +# Generated code +[*{_AssemblyInfo.cs,.notsupported.cs,AsmOffsets.cs}] +generated_code = true + +# C# files +[*.cs] +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = false +csharp_indent_switch_labels = true +csharp_indent_labels = one_less_than_current + +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:suggestion + +# avoid this. unless absolutely necessary +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion + +# Types: use keywords instead of BCL types, and permit var only when the type is clear +csharp_style_var_for_built_in_types = false:suggestion +csharp_style_var_when_type_is_apparent = false:none +csharp_style_var_elsewhere = false:suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# name all constant fields using PascalCase +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.required_modifiers = const +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +# static fields should have s_ prefix +dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion +dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields +dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static +dotnet_naming_symbols.static_fields.applicable_accessibilities = private, internal, private_protected +dotnet_naming_style.static_prefix_style.required_prefix = s_ +dotnet_naming_style.static_prefix_style.capitalization = camel_case + +# internal and private fields should be _camelCase +dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion +dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields +dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style +dotnet_naming_symbols.private_internal_fields.applicable_kinds = field +dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal +dotnet_naming_style.camel_case_underscore_style.required_prefix = _ +dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case + +# Code style defaults +csharp_using_directive_placement = outside_namespace:suggestion +dotnet_sort_system_directives_first = true +csharp_prefer_braces = true:silent +csharp_preserve_single_line_blocks = true:none +csharp_preserve_single_line_statements = false:none +csharp_prefer_static_local_function = true:suggestion +csharp_prefer_simple_using_statement = false:none +csharp_style_prefer_switch_expression = true:suggestion +dotnet_style_readonly_field = true:suggestion + +# Expression-level preferences +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_collection_expression = when_types_exactly_match +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +csharp_prefer_simple_default_expression = true:suggestion + +# Expression-bodied members +csharp_style_expression_bodied_methods = true:silent +csharp_style_expression_bodied_constructors = true:silent +csharp_style_expression_bodied_operators = true:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = true:silent + +# Pattern matching +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion + +# Null checking preferences +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion + +# Other features +csharp_style_prefer_index_operator = false:none +csharp_style_prefer_range_operator = false:none +csharp_style_pattern_local_over_anonymous_function = false:none + +# IDE0071: Simplify interpolation - keep as silent hint since ReadOnlySpan.ToString() is required for netstandard targets +dotnet_diagnostic.IDE0071.severity = silent + +# IDE0031: Use null propagation - keep as silent hint to avoid build errors with TreatWarningsAsErrors +dotnet_diagnostic.IDE0031.severity = silent + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# License header +file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe .NET Foundation licenses this file to you under the MIT license. + +# xUnit1051: recommends TestContext.Current.CancellationToken (v3 pattern) which +# is not yet adopted; suppress until a full v3 migration is performed. +dotnet_diagnostic.xUnit1051.severity = none + +[src/libraries/System.Net.Http/src/System/Net/Http/{SocketsHttpHandler/Http3RequestStream.cs,BrowserHttpHandler/BrowserHttpHandler.cs}] +# disable CA2025, the analyzer throws a NullReferenceException when processing this file: https://github.com/dotnet/roslyn-analyzers/issues/7652 +dotnet_diagnostic.CA2025.severity = none + +# C++ Files +[*.{cpp,h,in}] +curly_bracket_next_line = true +indent_brace_style = Allman + +# Xml project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}] +indent_size = 2 + +# Xml build files +[*.builds] +indent_size = 2 + +# Xml files +[*.{resx,ruleset,slnx,stylecop,xml}] +indent_size = 2 + +# Xml resource files +[*.resx] +# match Visual Studio behavior +insert_final_newline = false +trim_trailing_whitespace = false + +# Xml config files +[*.{props,targets,config,nuspec}] +indent_size = 2 + +# Data serialization +[*.{json,yaml,yml}] +indent_size = 2 + +# Shell scripts +[*.sh] +end_of_line = lf +[*.{cmd,bat}] +end_of_line = crlf diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index a671bef..b85732f 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -6,6 +6,55 @@ on: pull_request: jobs: + format: + name: 格式 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + # 仓里的配置文件与 FormatterConfig 逐字节相同,是标准;漂了就停下并打印 diff。 + # clang-format 版本钉死:新版本认不全新选项,--Werror 会把未知项也算失败。 + - name: C/C++ + run: | + set -euo pipefail + mapfile -d '' -t files < <( + git ls-files -z -- '*.c' '*.cpp' '*.h' '*.hpp' | grep -zvE '/(build|bin|obj)/' + ) + if [ ${#files[@]} -eq 0 ]; then echo "没有 C/C++ 文件"; exit 0; fi + python3 -m venv "$RUNNER_TEMP/cf" + "$RUNNER_TEMP/cf/bin/pip" install --quiet 'clang-format==23.1.4' + "$RUNNER_TEMP/cf/bin/clang-format" --dry-run --Werror "${files[@]}" + + # .clang-format 管不到的规则由 .editorconfig 规定,这里查它 —— clang-format 不看 + # .editorconfig。行尾不查:检出是 CRLF、索引里是 LF,先把 CR 去掉再判行尾空白。 + - name: 空白 + run: | + set -euo pipefail + mapfile -t files < <(git ls-files) + fail=0 + for f in "${files[@]}"; do + [ -s "$f" ] || continue + if [ -n "$(tail -c 1 "$f")" ]; then + echo "$f: 文件末尾缺换行"; fail=1 + fi + if sed 's/\r$//' "$f" | grep -qE '[[:space:]]+$'; then + echo "$f: 有行尾空白"; fail=1 + fi + done + exit "$fail" + + - uses: actions/setup-dotnet@v6 + with: + dotnet-version: "10.0.x" + + # .editorconfig 里的 csharp_* 规则只有 dotnet format 会执行。只放 whitespace: + # style 那套会连 file_header_template 一起要求。 + - name: C# 空白 + run: | + set -euo pipefail + sln=$(git ls-files -- '*.slnx' '*.sln' | head -n 1) + if [ -z "$sln" ]; then echo "没有解决方案文件"; exit 0; fi + dotnet format whitespace "$sln" --verify-no-changes assertions: runs-on: ubuntu-latest steps: @@ -50,7 +99,7 @@ jobs: - uses: actions/setup-dotnet@v6 with: - dotnet-version: '10.0.x' + dotnet-version: "10.0.x" # 宿主把整份断言清单跑一遍,任一条不过就以非零退出 —— 门槛就在这里(FX-0015)。 # 这里不写条数:它会变,而写死的数字只会变成下一处过时的注释。 diff --git a/host/DiagnosticsPluginLoader.cs b/host/DiagnosticsPluginLoader.cs index 4ff702e..08cef4d 100644 --- a/host/DiagnosticsPluginLoader.cs +++ b/host/DiagnosticsPluginLoader.cs @@ -9,9 +9,14 @@ public sealed class DiagnosticsPluginLoader : IPluginLoader, IPluginLoaderDiagno public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) => - throw new InvalidOperationException("诊断没有拦下"); + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) => throw new InvalidOperationException("诊断没有拦下"); - public IReadOnlyList Validate(PluginManifest manifest, string packageDirectory) => - [PluginDiagnostic.Error("entry-missing", "缺少入口文件 Diagnostic.dll")]; + public IReadOnlyList Validate( + PluginManifest manifest, + string packageDirectory + ) => [PluginDiagnostic.Error("entry-missing", "缺少入口文件 Diagnostic.dll")]; } diff --git a/host/GuardedPluginLoader.cs b/host/GuardedPluginLoader.cs index 8cbb988..68a608b 100644 --- a/host/GuardedPluginLoader.cs +++ b/host/GuardedPluginLoader.cs @@ -21,10 +21,17 @@ public sealed class GuardedPluginLoader : IPluginLoader public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) => - new TestPluginHandle(new GuardedPlugin(manifest.Name, this, context)); + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) => new TestPluginHandle(new GuardedPlugin(manifest.Name, this, context)); - private sealed class GuardedPlugin(string name, GuardedPluginLoader loader, IPluginContext context) : IPlugin + private sealed class GuardedPlugin( + string name, + GuardedPluginLoader loader, + IPluginContext context + ) : IPlugin { public ValueTask OnLoad(IPluginContext loadedContext, CancellationToken cancellationToken) { @@ -33,7 +40,8 @@ public ValueTask OnLoad(IPluginContext loadedContext, CancellationToken cancella // 模拟 Loader 在钩子之外发现的死亡:钩子返回后,从后台报告故障。 context.Scheduler.ScheduleOnce( TimeSpan.FromMilliseconds(50), - () => context.ReportFault(PluginDiagnostic.Error("async-death", "模拟异步死亡"))); + () => context.ReportFault(PluginDiagnostic.Error("async-death", "模拟异步死亡")) + ); } return ValueTask.CompletedTask; @@ -46,13 +54,17 @@ public ValueTask OnEnable(CancellationToken cancellationToken) throw new InvalidOperationException("故意在启用时抛出"); } - return ValueTask.FromResult(loader.RefuseEnable - ? PluginHookResult.Refuse("现在不行") - : PluginHookResult.Allow()); + return ValueTask.FromResult( + loader.RefuseEnable ? PluginHookResult.Refuse("现在不行") : PluginHookResult.Allow() + ); } public ValueTask OnDisable(CancellationToken cancellationToken) => - ValueTask.FromResult(loader.RefuseDisable ? PluginHookResult.Refuse("还不想停") : PluginHookResult.Allow()); + ValueTask.FromResult( + loader.RefuseDisable + ? PluginHookResult.Refuse("还不想停") + : PluginHookResult.Allow() + ); public ValueTask OnUnload(CancellationToken cancellationToken) => ValueTask.CompletedTask; } diff --git a/host/HookPluginLoader.cs b/host/HookPluginLoader.cs index 9f870d0..e0127ce 100644 --- a/host/HookPluginLoader.cs +++ b/host/HookPluginLoader.cs @@ -25,7 +25,11 @@ public sealed class HookPluginLoader : IPluginLoader public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) { SawLoaderContext[manifest.Name] = context is ILoaderContext; return new TestPluginHandle(new HookPlugin(manifest.Name, this)); diff --git a/host/Hosihikari.PluginManager.Host.csproj b/host/Hosihikari.PluginManager.Host.csproj index 4c183f0..80e8b0c 100644 --- a/host/Hosihikari.PluginManager.Host.csproj +++ b/host/Hosihikari.PluginManager.Host.csproj @@ -1,5 +1,4 @@ - Exe net10.0 @@ -19,9 +18,14 @@ - + - + - diff --git a/host/PinnedPluginLoader.cs b/host/PinnedPluginLoader.cs index 28db931..eef8d66 100644 --- a/host/PinnedPluginLoader.cs +++ b/host/PinnedPluginLoader.cs @@ -24,8 +24,11 @@ public sealed class PinnedPluginLoader : IPluginLoader public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) => - new PinnedPluginHandle(new PinnedPlugin(), this); + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) => new PinnedPluginHandle(new PinnedPlugin(), this); } internal sealed class PinnedPluginHandle(PinnedPlugin plugin, PinnedPluginLoader loader) @@ -42,7 +45,9 @@ public override void Unload() Plugin = null; } - public override async Task WaitForUnloadAsync(CancellationToken cancellationToken = default) + public override async Task WaitForUnloadAsync( + CancellationToken cancellationToken = default + ) { if (!_unloadStarted) { diff --git a/host/Program.cs b/host/Program.cs index 3dbf5fd..d0c403d 100644 --- a/host/Program.cs +++ b/host/Program.cs @@ -10,8 +10,11 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -if (args.Length > 0 && args[0] == "publish" - && Environment.GetEnvironmentVariable("HOSHI_PACK_OUTPUT_FIXTURE") == "1") +if ( + args.Length > 0 + && args[0] == "publish" + && Environment.GetEnvironmentVariable("HOSHI_PACK_OUTPUT_FIXTURE") == "1" +) { Console.Out.Write(new string('o', 2 * 1024 * 1024)); Console.Error.Write(new string('e', 2 * 1024 * 1024)); @@ -72,10 +75,12 @@ // Loader 的可读失败原因走插件日志,所以测试同时收一份。 var providerLogs = new System.Collections.Concurrent.ConcurrentQueue(); var collection = new ServiceCollection(); -collection.AddLogging(builder => builder - .AddSimpleConsole(options => options.SingleLine = true) - .AddProvider(new CapturingLoggerProvider(providerLogs)) - .SetMinimumLevel(LogLevel.Information)); +collection.AddLogging(builder => + builder + .AddSimpleConsole(options => options.SingleLine = true) + .AddProvider(new CapturingLoggerProvider(providerLogs)) + .SetMinimumLevel(LogLevel.Information) +); collection.AddSingleton(typeof(ICarrierInfo), new StubCarrier("stub")); var services = collection.BuildServiceProvider(); @@ -101,7 +106,8 @@ Console.WriteLine($"[框架] 已移除 {name}"); }, // 验证宿主模拟自持态:管理器拥有插件集,Reload 可用(FX-0062)。 - new PluginManagerOptions { OwnsPluginSet = true }); + new PluginManagerOptions { OwnsPluginSet = true } +); var pinnedLoader = new PinnedPluginLoader(); var guardedLoader = new GuardedPluginLoader(); host.RegisterLoader(new AssemblyPluginLoader(typeof(StubCarrier).Assembly)); @@ -123,42 +129,46 @@ // A25:同名 Loader 再登记会被拒并报出来,先来的那个不变(FX-0009) var duplicateRefused = !host.RegisterLoader(new ScriptPluginLoader()); -checks.Add(( - "A25 同名 Loader 被拒并报错", - duplicateRefused && reported.Any(entry => entry.Contains("插件种类名必须唯一")), - reported.LastOrDefault(entry => entry.Contains("插件种类名必须唯一")) ?? "(没有报告)" -)); +checks.Add( + ( + "A25 同名 Loader 被拒并报错", + duplicateRefused && reported.Any(entry => entry.Contains("插件种类名必须唯一")), + reported.LastOrDefault(entry => entry.Contains("插件种类名必须唯一")) ?? "(没有报告)" + ) +); // A48:加载器诊断在 Load 之前把问题并入报告(FX-0041) -var diagnosticProblem = reported.FirstOrDefault( - entry => entry.Contains("Diagnostic") && entry.Contains("缺少入口文件")); -checks.Add(( - "A48 加载器诊断进入加载报告", - diagnosticProblem is not null && !host.LoadedNames.Contains("Diagnostic"), - diagnosticProblem ?? "(没有诊断报告)" -)); +var diagnosticProblem = reported.FirstOrDefault(entry => + entry.Contains("Diagnostic") && entry.Contains("缺少入口文件") +); +checks.Add( + ( + "A48 加载器诊断进入加载报告", + diagnosticProblem is not null && !host.LoadedNames.Contains("Diagnostic"), + diagnosticProblem ?? "(没有诊断报告)" + ) +); // A49:状态快照是只读视图,带版本、加载器、启用状态与依赖(FX-0041) var fooSnapshot = host.Plugins.FirstOrDefault(plugin => plugin.Name == "Foo"); -var snapshotFound = host.TryGetPlugin("Foo", out var fooInfo) +var snapshotFound = + host.TryGetPlugin("Foo", out var fooInfo) && fooInfo is { Name: "Foo", State: PluginState.Loaded, Enabled: true }; -var snapshotOk = fooSnapshot is -{ - Version: "1.0.0", - Loader: "assembly", - State: PluginState.Loaded, - Enabled: true, -} -&& fooSnapshot.Dependencies.Any(dependency => dependency.Name == PluginContractInfo.ParentName) -&& snapshotFound; -checks.Add(( - "A49 插件状态快照读出依赖与启用状态", - snapshotOk, - fooSnapshot is null - ? "(没有 Foo 快照)" - : $"{fooSnapshot.Name} {fooSnapshot.Version} {fooSnapshot.Loader} " - + $"{fooSnapshot.State} enabled={fooSnapshot.Enabled} deps={fooSnapshot.Dependencies.Count}" -)); +var snapshotOk = + fooSnapshot + is { Version: "1.0.0", Loader: "assembly", State: PluginState.Loaded, Enabled: true } + && fooSnapshot.Dependencies.Any(dependency => dependency.Name == PluginContractInfo.ParentName) + && snapshotFound; +checks.Add( + ( + "A49 插件状态快照读出依赖与启用状态", + snapshotOk, + fooSnapshot is null + ? "(没有 Foo 快照)" + : $"{fooSnapshot.Name} {fooSnapshot.Version} {fooSnapshot.Loader} " + + $"{fooSnapshot.State} enabled={fooSnapshot.Enabled} deps={fooSnapshot.Dependencies.Count}" + ) +); // A9:一个 handler 抛出,其余照常收到(FX-0014) var heardFile = Path.Combine(dataRoot, "Foo", "heard.txt"); @@ -174,7 +184,13 @@ fooSnapshot is null Thread.Sleep(50); } -checks.Add(("A10 调度器的一次性任务执行", File.Exists(scheduledFile), File.Exists(scheduledFile) ? "已执行" : "没跑")); +checks.Add( + ( + "A10 调度器的一次性任务执行", + File.Exists(scheduledFile), + File.Exists(scheduledFile) ? "已执行" : "没跑" + ) +); // A40:停用关闭作用域闸门,事件不再投递;启用后恢复(FX-0035) var fooDisabled = host.Disable("Foo"); @@ -185,35 +201,34 @@ fooSnapshot is null host.Events.Publish("after-enable"); Thread.Sleep(100); var heardAfterEnable = File.Exists(heardFile) ? File.ReadAllText(heardFile) : "(没收到)"; -checks.Add(( - "A40 停用后不再回调,启用后恢复", - fooDisabled && fooEnabled && heardWhileDisabled == "ping" && heardAfterEnable == "after-enable", - $"disabled={fooDisabled} while={heardWhileDisabled} enabled={fooEnabled} after={heardAfterEnable}" -)); +checks.Add( + ( + "A40 停用后不再回调,启用后恢复", + fooDisabled + && fooEnabled + && heardWhileDisabled == "ping" + && heardAfterEnable == "after-enable", + $"disabled={fooDisabled} while={heardWhileDisabled} enabled={fooEnabled} after={heardAfterEnable}" + ) +); // A16:普通依赖(非契约、不在共享层)按 ALC 各一份 —— 这正是可卸载性的代价, // 也是"插件之间不共享类型"的另一面(FX-0026)。 var fooLib = File.ReadAllText(Path.Combine(dataRoot, "Foo", "lib.txt")); var barLib = File.ReadAllText(Path.Combine(dataRoot, "Bar", "lib.txt")); -checks.Add(( - "A16 普通依赖按 ALC 各一份", - fooLib != barLib, - $"Foo: {fooLib} / Bar: {barLib}" -)); +checks.Add(("A16 普通依赖按 ALC 各一份", fooLib != barLib, $"Foo: {fooLib} / Bar: {barLib}")); // A21:插件之间只走通道 —— 用共享层里的类型登记与解析,两个 ALC 看到同一个类型对象; // 同类型再次登记被拒、先来的留着(FX-0009 / 0026 / 0027)。 // 收回这条不单独断言:登记没被摘掉的话,Foo 的 ALC 就被钉住,下面那条卸载断言会失败。 var peerFile = Path.Combine(dataRoot, "Bar", "peer.txt"); var peer = File.Exists(peerFile) ? File.ReadAllText(peerFile) : "(插件没写出东西)"; -checks.Add(( - "A21 跨插件服务登记与解析", - peer == "Foo.FooPlugin | 冲突登记=False", - peer -)); +checks.Add(("A21 跨插件服务登记与解析", peer == "Foo.FooPlugin | 冲突登记=False", peer)); // A11:两个测试插件都经打包工具装配成了包 -var packedOk = Directory.Exists(Path.Combine(pluginsRoot, "Foo")) && Directory.Exists(Path.Combine(pluginsRoot, "Bar")); +var packedOk = + Directory.Exists(Path.Combine(pluginsRoot, "Foo")) + && Directory.Exists(Path.Combine(pluginsRoot, "Bar")); checks.Add(("A11 打包工具产出包", packedOk, packedOk ? "Foo / Bar" : "缺包")); // A12:误把契约打进包里的构建输出,打包必须拦下(FX-0004 / 0019)—— 这条在运行期是静默的 @@ -222,32 +237,58 @@ fooSnapshot is null File.Copy( Path.Combine(AppContext.BaseDirectory, "Hosihikari.Plugin.Abstractions.dll"), Path.Combine(badSource, "Hosihikari.Plugin.Abstractions.dll"), - overwrite: true); -var bad = Packager.Pack(badSource, Path.Combine(repoRoot, "test", "Foo", "hosihikari.json"), Path.Combine(stage, "bad-out"), sharedLayer); + overwrite: true +); +var bad = Packager.Pack( + badSource, + Path.Combine(repoRoot, "test", "Foo", "hosihikari.json"), + Path.Combine(stage, "bad-out"), + sharedLayer +); var sharedProblem = bad.Problems.FirstOrDefault(problem => problem.Contains("共享层")); -checks.Add(("A12 打包拒绝共享层副本", !bad.Succeeded && sharedProblem is not null, sharedProblem ?? "(未拦下)")); +checks.Add( + ( + "A12 打包拒绝共享层副本", + !bad.Succeeded && sharedProblem is not null, + sharedProblem ?? "(未拦下)" + ) +); // A6:apiVersion 不匹配必须被拒载并留下可读报告(FX-0012) -var rejected = !host.LoadedNames.Contains("Broken") && reported.Any(entry => entry.Contains("apiVersion 不匹配")); -checks.Add(("A6 apiVersion 不匹配时拒载", rejected, reported.LastOrDefault(entry => entry.Contains("apiVersion 不匹配")) ?? "(无报告)")); +var rejected = + !host.LoadedNames.Contains("Broken") + && reported.Any(entry => entry.Contains("apiVersion 不匹配")); +checks.Add( + ( + "A6 apiVersion 不匹配时拒载", + rejected, + reported.LastOrDefault(entry => entry.Contains("apiVersion 不匹配")) ?? "(无报告)" + ) +); // A33:schemaVersion 不匹配必须被拒载(FX-0012) -var formatRefused = !host.LoadedNames.Contains("BadFormat") +var formatRefused = + !host.LoadedNames.Contains("BadFormat") && reported.Any(entry => entry.Contains("schemaVersion 不匹配")); -checks.Add(( - "A33 schemaVersion 不匹配时拒载", - formatRefused, - reported.LastOrDefault(entry => entry.Contains("schemaVersion")) ?? "(无报告)" -)); +checks.Add( + ( + "A33 schemaVersion 不匹配时拒载", + formatRefused, + reported.LastOrDefault(entry => entry.Contains("schemaVersion")) ?? "(无报告)" + ) +); // A34:entry 必须留在包内 —— 绝对路径与 .. 都不能把包外的东西装进插件的 ALC(FX-0006) -var escapingRefused = !host.LoadedNames.Contains("Escaping") +var escapingRefused = + !host.LoadedNames.Contains("Escaping") && reported.Any(entry => entry.Contains("entry 必须是包内相对路径")); -checks.Add(( - "A34 entry 出界时拒载", - escapingRefused, - reported.LastOrDefault(entry => entry.Contains("entry 必须是包内相对路径")) ?? "(无报告)" -)); +checks.Add( + ( + "A34 entry 出界时拒载", + escapingRefused, + reported.LastOrDefault(entry => entry.Contains("entry 必须是包内相对路径")) ?? "(无报告)" + ) +); // A5:载体绑定程序集也走共享层 —— 转型成功才拿得到,副本会拿到另一种身份(FX-0019) var carrierFile = Path.Combine(dataRoot, "Foo", "carrier.txt"); @@ -257,31 +298,53 @@ fooSnapshot is null // A8:包内默认被包外覆盖,且没写配置的插件照样加载(FX-0018) var greetingFile = Path.Combine(dataRoot, "Foo", "greeting.txt"); var greeting = File.Exists(greetingFile) ? File.ReadAllText(greetingFile) : "(插件没写出东西)"; -checks.Add(("A8 配置分层:包外覆盖包内", greeting == "overridden" && host.LoadedNames.Contains("Bar"), greeting)); +checks.Add( + ( + "A8 配置分层:包外覆盖包内", + greeting == "overridden" && host.LoadedNames.Contains("Bar"), + greeting + ) +); // A7:另一种插件类型(不碰 ALC)走的是同一套契约与同一套生命周期(FX-0002 / FX-0010) var ranFile = Path.Combine(dataRoot, "Lua", "ran.txt"); -checks.Add(("A7 非 ALC 的插件类型走同一契约", File.Exists(ranFile), File.Exists(ranFile) ? "脚本已执行" : "脚本没跑")); +checks.Add( + ( + "A7 非 ALC 的插件类型走同一契约", + File.Exists(ranFile), + File.Exists(ranFile) ? "脚本已执行" : "脚本没跑" + ) +); // A4:Bar 依赖 Foo,此时卸 Foo 必须被拒,且如实返回(FX-0004) var refused = host.Unload("Foo"); -checks.Add(("A4 有依赖者时拒绝卸载", !refused.Released && !string.IsNullOrEmpty(refused.Error), refused.Error ?? "(未拒绝)")); +checks.Add( + ( + "A4 有依赖者时拒绝卸载", + !refused.Released && !string.IsNullOrEmpty(refused.Error), + refused.Error ?? "(未拒绝)" + ) +); // A24:传递依赖的第二段 —— Bar 现在依赖者是 Lua,卸它同样要被拒(FX-0004) var barRefused = host.Unload("Bar"); -checks.Add(( - "A24 传递依赖上仍然拒绝卸载", - !barRefused.Released && barRefused.Error?.Contains("Lua") == true, - barRefused.Error ?? "(未拒绝)" -)); +checks.Add( + ( + "A24 传递依赖上仍然拒绝卸载", + !barRefused.Released && barRefused.Error?.Contains("Lua") == true, + barRefused.Error ?? "(未拒绝)" + ) +); // A13:父级态下父级把包逐个交过来(FX-0003)—— 这个包不在 plugins/ 下,只有交付能让它进来 var delivered = host.Load(Path.Combine(stage, "parented", "Pinned")); -checks.Add(( - "A13 父级交付的包装上了", - delivered && host.LoadedNames.Contains("Pinned"), - delivered ? string.Join(", ", host.LoadedNames) : "交付被拒" -)); +checks.Add( + ( + "A13 父级交付的包装上了", + delivered && host.LoadedNames.Contains("Pinned"), + delivered ? string.Join(", ", host.LoadedNames) : "交付被拒" + ) +); // A20:父级态下启停由父级驱动(FX-0003)—— 交付时不自动启用,父级一发话钩子就该到 var hookFile = Path.Combine(dataRoot, "Pinned", "hook.txt"); @@ -290,28 +353,38 @@ fooSnapshot is null var afterDisable = File.ReadAllText(hookFile); var enabled = host.Enable("Pinned"); var afterEnable = File.ReadAllText(hookFile); -checks.Add(( - "A20 父级驱动启停,交付时不自动启用", - afterDelivery == "loaded" && disabled && afterDisable == "disabled" && enabled && afterEnable == "enabled", - $"交付后 {afterDelivery} → 停用 {afterDisable} → 启用 {afterEnable}" -)); +checks.Add( + ( + "A20 父级驱动启停,交付时不自动启用", + afterDelivery == "loaded" + && disabled + && afterDisable == "disabled" + && enabled + && afterEnable == "enabled", + $"交付后 {afterDelivery} → 停用 {afterDisable} → 启用 {afterEnable}" + ) +); // A14:放下之后回收验证没过,就是没卸掉 —— 照实报失败(FX-0004) var pinnedFirst = host.Unload("Pinned"); -checks.Add(( - "A14 回收没过时如实报失败", - !pinnedFirst.Released && pinnedFirst.Error?.Contains("回收") == true, - pinnedFirst.Error ?? "(居然说卸掉了)" -)); +checks.Add( + ( + "A14 回收没过时如实报失败", + !pinnedFirst.Released && pinnedFirst.Error?.Contains("回收") == true, + pinnedFirst.Error ?? "(居然说卸掉了)" + ) +); // A15:再问一次是重新验证,不是"未加载";外面那根没了就真卸掉 pinnedLoader.Pinned = false; var pinnedSecond = host.Unload("Pinned"); -checks.Add(( - "A15 待回收的插件可以再卸一次", - pinnedSecond.Released && !host.LoadedNames.Contains("Pinned"), - pinnedSecond.Error ?? "已回收" -)); +checks.Add( + ( + "A15 待回收的插件可以再卸一次", + pinnedSecond.Released && !host.LoadedNames.Contains("Pinned"), + pinnedSecond.Error ?? "已回收" + ) +); // A47:并发卸载共享同一个进行中的回收验证,验证等待不占 _gate。 pinnedLoader.Pinned = true; @@ -325,18 +398,22 @@ fooSnapshot is null pinnedLoader.Pinned = false; var concurrentFinished = Task.WaitAll( new[] { concurrentFirst, concurrentSecond }, - TimeSpan.FromSeconds(5)); -var concurrentReleased = concurrentFinished - && concurrentFirst.Result.Released - && concurrentSecond.Result.Released; -checks.Add(( - "A47 并发卸载共享同一个回收验证", - concurrentLoaded && firstWaiting && concurrentReleased - && pinnedLoader.WaitCalls - waitsBefore == 1 - && !host.LoadedNames.Contains("Pinned"), - $"loaded={concurrentLoaded} waiting={firstWaiting} released={concurrentReleased} " - + $"waits={pinnedLoader.WaitCalls - waitsBefore}" -)); + TimeSpan.FromSeconds(5) +); +var concurrentReleased = + concurrentFinished && concurrentFirst.Result.Released && concurrentSecond.Result.Released; +checks.Add( + ( + "A47 并发卸载共享同一个回收验证", + concurrentLoaded + && firstWaiting + && concurrentReleased + && pinnedLoader.WaitCalls - waitsBefore == 1 + && !host.LoadedNames.Contains("Pinned"), + $"loaded={concurrentLoaded} waiting={firstWaiting} released={concurrentReleased} " + + $"waits={pinnedLoader.WaitCalls - waitsBefore}" + ) +); // A50:回收验证超时按失败记,槽位留在待回收;下一次卸载复用同一个验证任务(FX-0042)。 var timeoutLoader = new PinnedPluginLoader { Pinned = true }; @@ -347,24 +424,31 @@ fooSnapshot is null _ => { }, null, null, - new PluginManagerOptions { UnloadVerificationTimeout = TimeSpan.FromMilliseconds(150) }); + new PluginManagerOptions { UnloadVerificationTimeout = TimeSpan.FromMilliseconds(150) } +); timeoutHost.RegisterLoader(timeoutLoader); var timeoutLoaded = timeoutHost.Load(Path.Combine(stage, "parented", "Pinned")); var timeoutFirst = timeoutHost.Unload("Pinned"); -var timeoutDetached = timeoutHost.TryGetPlugin("Pinned", out var timeoutInfo) +var timeoutDetached = + timeoutHost.TryGetPlugin("Pinned", out var timeoutInfo) && timeoutInfo is { State: PluginState.Detached, Enabled: false }; timeoutLoader.Pinned = false; var timeoutSecond = timeoutHost.Unload("Pinned"); var timeoutGone = !timeoutHost.TryGetPlugin("Pinned", out _); -checks.Add(( - "A50 回收验证超时按失败记并保留待回收", - timeoutLoaded && !timeoutFirst.Released - && timeoutFirst.Error?.Contains("回收验证超时") == true - && timeoutDetached && timeoutSecond.Released && timeoutGone - && timeoutLoader.WaitCalls == 1, - $"loaded={timeoutLoaded} first={timeoutFirst.Error ?? "成功"} detached={timeoutDetached} " - + $"second={timeoutSecond.Released} waits={timeoutLoader.WaitCalls}" -)); +checks.Add( + ( + "A50 回收验证超时按失败记并保留待回收", + timeoutLoaded + && !timeoutFirst.Released + && timeoutFirst.Error?.Contains("回收验证超时") == true + && timeoutDetached + && timeoutSecond.Released + && timeoutGone + && timeoutLoader.WaitCalls == 1, + $"loaded={timeoutLoaded} first={timeoutFirst.Error ?? "成功"} detached={timeoutDetached} " + + $"second={timeoutSecond.Released} waits={timeoutLoader.WaitCalls}" + ) +); // A51:WaitAsync 计时器不支持的超时在构造期拒绝,避免每次卸载都失败且不验证。 var invalidTimeoutRefused = false; @@ -377,18 +461,21 @@ fooSnapshot is null _ => { }, null, null, - new PluginManagerOptions { UnloadVerificationTimeout = TimeSpan.FromDays(60) }); + new PluginManagerOptions { UnloadVerificationTimeout = TimeSpan.FromDays(60) } + ); } catch (ArgumentOutOfRangeException) { invalidTimeoutRefused = true; } -checks.Add(( - "A51 拒绝超出计时器范围的卸载超时", - invalidTimeoutRefused, - invalidTimeoutRefused ? "构造期已拒绝" : "(没有拒绝)" -)); +checks.Add( + ( + "A51 拒绝超出计时器范围的卸载超时", + invalidTimeoutRefused, + invalidTimeoutRefused ? "构造期已拒绝" : "(没有拒绝)" + ) +); // A51b:InfiniteTimeSpan 关闭计时器,一直等到加载器的验证通过(FX-0042)。 var infiniteLoader = new PinnedPluginLoader { Pinned = true }; @@ -399,20 +486,26 @@ fooSnapshot is null _ => { }, null, null, - new PluginManagerOptions { UnloadVerificationTimeout = Timeout.InfiniteTimeSpan }); + new PluginManagerOptions { UnloadVerificationTimeout = Timeout.InfiniteTimeSpan } +); infiniteHost.RegisterLoader(infiniteLoader); var infiniteLoaded = infiniteHost.Load(Path.Combine(stage, "parented", "Pinned")); var infinitePending = Task.Run(() => infiniteHost.Unload("Pinned")); Thread.Sleep(300); var infiniteStillWaiting = !infinitePending.IsCompleted; infiniteLoader.Pinned = false; -var infiniteReleased = infinitePending.Wait(TimeSpan.FromSeconds(5)) && infinitePending.Result.Released; -checks.Add(( - "A51b InfiniteTimeSpan 不设计时器,等验证通过才返回", - infiniteLoaded && infiniteStillWaiting && infiniteReleased - && !infiniteHost.LoadedNames.Contains("Pinned"), - $"loaded={infiniteLoaded} waiting={infiniteStillWaiting} released={infiniteReleased}" -)); +var infiniteReleased = + infinitePending.Wait(TimeSpan.FromSeconds(5)) && infinitePending.Result.Released; +checks.Add( + ( + "A51b InfiniteTimeSpan 不设计时器,等验证通过才返回", + infiniteLoaded + && infiniteStillWaiting + && infiniteReleased + && !infiniteHost.LoadedNames.Contains("Pinned"), + $"loaded={infiniteLoaded} waiting={infiniteStillWaiting} released={infiniteReleased}" + ) +); // A53:服务端线程上装着 SynchronizationContext 时,钩子里的 await 不能把同步等待挂死(FX-0059)。 // 复现的就是这个:装上下文后直接 GetAwaiter().GetResult() 等 Task.Delay / Task.Yield / Task.Run 会永久阻塞。 @@ -422,7 +515,8 @@ fooSnapshot is null pluginsRoot, Path.Combine(stage, "hooks", "data"), Path.Combine(stage, "hooks", "config"), - _ => { }); + _ => { } +); hookedHost.RegisterLoader(hookLoader); var hookedPackage = Path.Combine(stage, "parented", "Awaiting"); var awaited = false; @@ -433,15 +527,21 @@ fooSnapshot is null var loaded = hookedHost.Load(hookedPackage); var enabled = loaded && hookedHost.Enable("Awaiting"); var unloaded = enabled && hookedHost.Unload("Awaiting").Released; - awaited = loaded && enabled && unloaded && hookLoader.DelaysCompleted.GetValueOrDefault("Awaiting"); -}) { IsBackground = true }; + awaited = + loaded && enabled && unloaded && hookLoader.DelaysCompleted.GetValueOrDefault("Awaiting"); +}) +{ + IsBackground = true, +}; awaitingThread.Start(); deadlocked = !awaitingThread.Join(TimeSpan.FromSeconds(5)); -checks.Add(( - "A53 装着服务端上下文时钩子不挂死", - awaited && !deadlocked, - $"completed={awaited} deadlocked={deadlocked}" -)); +checks.Add( + ( + "A53 装着服务端上下文时钩子不挂死", + awaited && !deadlocked, + $"completed={awaited} deadlocked={deadlocked}" + ) +); // A54:钩子超时是独立一段,回收验证照走;结果如实标注是钩子超的(FX-0063)。 // Hanging 的 OnDisable / OnUnload 等到令牌取消才返回,回收验证本身是快的。 @@ -453,21 +553,26 @@ fooSnapshot is null _ => { }, null, null, - new PluginManagerOptions { HookTimeout = TimeSpan.FromMilliseconds(150) }); + new PluginManagerOptions { HookTimeout = TimeSpan.FromMilliseconds(150) } +); hangHost.RegisterLoader(hangLoader); var hangLoaded = hangHost.Load(Path.Combine(stage, "parented", "Hanging")); var hangStarted = System.Diagnostics.Stopwatch.StartNew(); var hangUnload = hangHost.Unload("Hanging"); hangStarted.Stop(); -checks.Add(( - "A54 钩子超时不再等待并继续回收验证", - hangLoaded && hangUnload.Released && hangUnload.HookTimedOut - && hangUnload.Failure == UnloadFailure.None - && hangStarted.Elapsed < TimeSpan.FromSeconds(5) - && !hangHost.TryGetPlugin("Hanging", out _), - $"released={hangUnload.Released} hookTimedOut={hangUnload.HookTimedOut} " - + $"failure={hangUnload.Failure} elapsed={hangStarted.ElapsedMilliseconds}ms" -)); +checks.Add( + ( + "A54 钩子超时不再等待并继续回收验证", + hangLoaded + && hangUnload.Released + && hangUnload.HookTimedOut + && hangUnload.Failure == UnloadFailure.None + && hangStarted.Elapsed < TimeSpan.FromSeconds(5) + && !hangHost.TryGetPlugin("Hanging", out _), + $"released={hangUnload.Released} hookTimedOut={hangUnload.HookTimedOut} " + + $"failure={hangUnload.Failure} elapsed={hangStarted.ElapsedMilliseconds}ms" + ) +); // A55:钩子超时在自持态的装载/E启用里也成立:OnLoad 取消按回滚处理,OnEnable 取消保持停用(FX-0059)。 var enableHangLoader = new HookPluginLoader(); @@ -478,7 +583,8 @@ fooSnapshot is null _ => { }, null, null, - new PluginManagerOptions { HookTimeout = TimeSpan.FromMilliseconds(150) }); + new PluginManagerOptions { HookTimeout = TimeSpan.FromMilliseconds(150) } +); enableHangHost.RegisterLoader(enableHangLoader); var loadTimedOut = true; var hangingLoaded = false; @@ -493,13 +599,19 @@ fooSnapshot is null } var enableTimedOut = !enableHangHost.Enable("Hanging"); -checks.Add(( - "A55 OnEnable 超时保持停用且不挂死", - loadTimedOut && hangingLoaded && enableTimedOut && enableHangHost.LoadedNames.Contains("Hanging") - && enableHangHost.TryGetPlugin("Hanging", out var hangInfo) && hangInfo.Enabled == false, - $"load={loadTimedOut} loaded={hangingLoaded} refusedEnable={enableTimedOut} " - + $"names=[{string.Join(", ", enableHangHost.LoadedNames)}]" -)); +checks.Add( + ( + "A55 OnEnable 超时保持停用且不挂死", + loadTimedOut + && hangingLoaded + && enableTimedOut + && enableHangHost.LoadedNames.Contains("Hanging") + && enableHangHost.TryGetPlugin("Hanging", out var hangInfo) + && hangInfo.Enabled == false, + $"load={loadTimedOut} loaded={hangingLoaded} refusedEnable={enableTimedOut} " + + $"names=[{string.Join(", ", enableHangHost.LoadedNames)}]" + ) +); // A56:普通包与加载器包拿到的上下文不同(FX-0059);判别认清单的 packageKind。 var contextKindLoader = new HookPluginLoader(); @@ -507,24 +619,28 @@ fooSnapshot is null pluginsRoot, Path.Combine(stage, "contexts", "data"), Path.Combine(stage, "contexts", "config"), - _ => { }); + _ => { } +); kindHost.RegisterLoader(contextKindLoader); var plainPackage = Path.Combine(stage, "parented", "Awaiting"); var loaderPackage = Path.Combine(stage, "parented", "LoaderKind"); var plainLoaded = kindHost.Load(plainPackage); var loaderLoaded = kindHost.Load(loaderPackage); -checks.Add(( - "A56 普通包拿不到 ILoaderContext,加载器包拿得到(装载与 OnLoad 都算)", - plainLoaded && loaderLoaded - && contextKindLoader.SawLoaderContext.GetValueOrDefault("Awaiting") == false - && contextKindLoader.SawLoaderContext.GetValueOrDefault("LoaderKind") == true - && contextKindLoader.SawLoaderContextInHook.GetValueOrDefault("Awaiting") == false - && contextKindLoader.SawLoaderContextInHook.GetValueOrDefault("LoaderKind") == true, - $"plain={contextKindLoader.SawLoaderContext.GetValueOrDefault("Awaiting")}/" - + $"{contextKindLoader.SawLoaderContextInHook.GetValueOrDefault("Awaiting")} " - + $"loader={contextKindLoader.SawLoaderContext.GetValueOrDefault("LoaderKind")}/" - + $"{contextKindLoader.SawLoaderContextInHook.GetValueOrDefault("LoaderKind")}" -)); +checks.Add( + ( + "A56 普通包拿不到 ILoaderContext,加载器包拿得到(装载与 OnLoad 都算)", + plainLoaded + && loaderLoaded + && contextKindLoader.SawLoaderContext.GetValueOrDefault("Awaiting") == false + && contextKindLoader.SawLoaderContext.GetValueOrDefault("LoaderKind") == true + && contextKindLoader.SawLoaderContextInHook.GetValueOrDefault("Awaiting") == false + && contextKindLoader.SawLoaderContextInHook.GetValueOrDefault("LoaderKind") == true, + $"plain={contextKindLoader.SawLoaderContext.GetValueOrDefault("Awaiting")}/" + + $"{contextKindLoader.SawLoaderContextInHook.GetValueOrDefault("Awaiting")} " + + $"loader={contextKindLoader.SawLoaderContext.GetValueOrDefault("LoaderKind")}/" + + $"{contextKindLoader.SawLoaderContextInHook.GetValueOrDefault("LoaderKind")}" + ) +); // A66:钩子里报的故障不能在 _gate 上等死(Codex 指出的死锁形状)—— // Enable 期间 _gate 被握着,插件线程 ReportFault 必须先进待报账,钩子返回后立刻卸掉。 @@ -538,21 +654,26 @@ fooSnapshot is null faultReports.Add, services, null, - new PluginManagerOptions { HookTimeout = TimeSpan.FromSeconds(5) }); + new PluginManagerOptions { HookTimeout = TimeSpan.FromSeconds(5) } +); faultHost.RegisterLoader(faultLoader); var faultLoaded = faultHost.Load(Path.Combine(stage, "parented", "Awaiting")); var faultWatch = System.Diagnostics.Stopwatch.StartNew(); var faultEnable = faultHost.Enable("Awaiting"); var faultElapsed = faultWatch.Elapsed; Thread.Sleep(100); -checks.Add(( - "A66 钩子里的故障先进待报账,不在 _gate 上等到超时", - faultLoaded && !faultEnable && !faultHost.LoadedNames.Contains("Awaiting") - && faultElapsed < TimeSpan.FromSeconds(2) - && faultReports.Any(report => report.Contains("故障", StringComparison.Ordinal)), - $"loaded={faultLoaded} enable={faultEnable} elapsed={faultElapsed.TotalMilliseconds:0}ms " - + $"names=[{string.Join(", ", faultHost.LoadedNames)}]" -)); +checks.Add( + ( + "A66 钩子里的故障先进待报账,不在 _gate 上等到超时", + faultLoaded + && !faultEnable + && !faultHost.LoadedNames.Contains("Awaiting") + && faultElapsed < TimeSpan.FromSeconds(2) + && faultReports.Any(report => report.Contains("故障", StringComparison.Ordinal)), + $"loaded={faultLoaded} enable={faultEnable} elapsed={faultElapsed.TotalMilliseconds:0}ms " + + $"names=[{string.Join(", ", faultHost.LoadedNames)}]" + ) +); // A59:状态迁移事件照实发出 —— 装载成功发 →Loaded,放下发 Loaded→Detached(FX-0062 / 0062 的接线)。 // 事件在线程池上发,所以等一小会儿再收。 @@ -561,7 +682,8 @@ fooSnapshot is null pluginsRoot, Path.Combine(stage, "states", "data"), Path.Combine(stage, "states", "config"), - _ => { }); + _ => { } +); stateHost.RegisterLoader(statePlugin); var stateTransitions = new System.Collections.Concurrent.ConcurrentQueue(); stateHost.Events.Subscribe(change => stateTransitions.Enqueue(change)); @@ -569,19 +691,31 @@ fooSnapshot is null var stateUnloaded = stateHost.Unload("Awaiting").Released; Thread.Sleep(300); var transitions = stateTransitions.ToArray(); -checks.Add(( - "A59 装载与放下各发一次状态事件", - stateLoaded && stateUnloaded - && transitions.Any(change => change is { Previous: PluginState.Detached, Current: PluginState.Loaded }) - && transitions.Any(change => change is { Previous: PluginState.Loaded, Current: PluginState.Detached }), - string.Join(", ", transitions.Select(change => $"{change.Previous}→{change.Current}")) - is { Length: > 0 } text ? text : "(没有事件)" -)); +checks.Add( + ( + "A59 装载与放下各发一次状态事件", + stateLoaded + && stateUnloaded + && transitions.Any(change => + change is { Previous: PluginState.Detached, Current: PluginState.Loaded } + ) + && transitions.Any(change => + change is { Previous: PluginState.Loaded, Current: PluginState.Detached } + ), + string.Join(", ", transitions.Select(change => $"{change.Previous}→{change.Current}")) + is { Length: > 0 } text + ? text + : "(没有事件)" + ) +); + // A57:只有旧 manifest.json 的包在载入前拒载,报错指向 migrate(FX-0058)。 // 父级自己的插件住在同一个 plugins/ 下,它们的信封 type 不是 hosihikari,不该被报出来。 var legacyPackage = Path.Combine(pluginsRoot, "LegacyOnly"); Directory.CreateDirectory(legacyPackage); -File.WriteAllText(Path.Combine(legacyPackage, "manifest.json"), """ +File.WriteAllText( + Path.Combine(legacyPackage, "manifest.json"), + """ { "name": "LegacyOnly", "entry": "LegacyOnly.dll", @@ -589,21 +723,27 @@ fooSnapshot is null "dependencies": [ { "name": "hosihikari" } ], "extraInfo": { "api_version": "2", "manifest_version": "1" } } - """); + """ +); var parentPackage = Path.Combine(pluginsRoot, "ParentMod"); Directory.CreateDirectory(parentPackage); -File.WriteAllText(Path.Combine(parentPackage, "manifest.json"), """ +File.WriteAllText( + Path.Combine(parentPackage, "manifest.json"), + """ { "name": "ParentMod", "entry": "ParentMod.dll", "type": "native" } - """); + """ +); var foreignReports = new List(); ManifestReader.Scan(pluginsRoot, foreignReports.Add); -checks.Add(( - "A57 旧包拒载并给出 migrate,父级 mod 不吭声", - foreignReports.Any(report => report.Contains("hosihikari-pack migrate LegacyOnly")) - && !foreignReports.Any(report => report.Contains("ParentMod")) - && !host.LoadedNames.Contains("LegacyOnly"), - foreignReports.FirstOrDefault() ?? "(无报告)" -)); +checks.Add( + ( + "A57 旧包拒载并给出 migrate,父级 mod 不吭声", + foreignReports.Any(report => report.Contains("hosihikari-pack migrate LegacyOnly")) + && !foreignReports.Any(report => report.Contains("ParentMod")) + && !host.LoadedNames.Contains("LegacyOnly"), + foreignReports.FirstOrDefault() ?? "(无报告)" + ) +); // A58:carrier 组声明的程序集与类型要真的存在且实现 ICarrierComponent(FX-0061)。 // 核心按名字装配组件,等到启动阶段才发现就太晚了。入口只是占位:载体包不由父级加载。 @@ -613,87 +753,120 @@ fooSnapshot is null File.Copy( Path.Combine(AppContext.BaseDirectory, "Hosihikari.Bindings.Stub.dll"), Path.Combine(carrierSource, "probe.dll"), - overwrite: true); -string CarrierManifest(string components) => WriteManifest("carrier-" + Guid.NewGuid().ToString("N"), $$""" - { - "schemaVersion": 1, - "name": "hosihikari", - "entry": "entry.dll", - "loader": "stub", - "kind": "carrier", - "apiVersion": 3, - "carrier": { "components": {{components}} } - } - """); + overwrite: true +); +string CarrierManifest(string components) => + WriteManifest( + "carrier-" + Guid.NewGuid().ToString("N"), + $$""" + { + "schemaVersion": 1, + "name": "hosihikari", + "entry": "entry.dll", + "loader": "stub", + "kind": "carrier", + "apiVersion": 3, + "carrier": { "components": {{components}} } + } + """ + ); + // 替身里有一个真实现与一个抽象实现:类型不存在、类型没实现、抽象类都必须拒。 var carrierMissingType = Packager.Pack( carrierSource, CarrierManifest("""[ { "assembly": "probe.dll", "type": "Hosihikari.NoSuchComponent" } ]"""), Path.Combine(stage, "carrier-missing-type"), - sharedLayer); + sharedLayer +); var carrierMissingAssembly = Packager.Pack( carrierSource, CarrierManifest("""[ { "assembly": "nope.dll", "type": "Some.Component" } ]"""), Path.Combine(stage, "carrier-missing-assembly"), - sharedLayer); + sharedLayer +); var carrierAbstract = Packager.Pack( carrierSource, - CarrierManifest("""[ { "assembly": "probe.dll", "type": "Hosihikari.Bindings.AbstractCarrierComponent" } ]"""), + CarrierManifest( + """[ { "assembly": "probe.dll", "type": "Hosihikari.Bindings.AbstractCarrierComponent" } ]""" + ), Path.Combine(stage, "carrier-abstract"), - sharedLayer); + sharedLayer +); var carrierRealType = Packager.Pack( carrierSource, - CarrierManifest("""[ { "assembly": "probe.dll", "type": "Hosihikari.Bindings.StubCarrierComponent" } ]"""), + CarrierManifest( + """[ { "assembly": "probe.dll", "type": "Hosihikari.Bindings.StubCarrierComponent" } ]""" + ), Path.Combine(stage, "carrier-real"), - sharedLayer); + sharedLayer +); + // 引导(FX-0064):同样要在打包期校验——不是配置器、类型不存在都要拒。 -string BootstrapManifest(string bootstrap) => WriteManifest("carrier-" + Guid.NewGuid().ToString("N"), $$""" - { - "schemaVersion": 1, - "name": "hosihikari", - "entry": "entry.dll", - "loader": "stub", - "kind": "carrier", - "apiVersion": 3, - "carrier": { "bootstrap": {{bootstrap}} } - } - """); +string BootstrapManifest(string bootstrap) => + WriteManifest( + "carrier-" + Guid.NewGuid().ToString("N"), + $$""" + { + "schemaVersion": 1, + "name": "hosihikari", + "entry": "entry.dll", + "loader": "stub", + "kind": "carrier", + "apiVersion": 3, + "carrier": { "bootstrap": {{bootstrap}} } + } + """ + ); var bootstrapNotConfigurator = Packager.Pack( carrierSource, - BootstrapManifest("""{ "assembly": "probe.dll", "type": "Hosihikari.Bindings.StubCarrierComponent" }"""), + BootstrapManifest( + """{ "assembly": "probe.dll", "type": "Hosihikari.Bindings.StubCarrierComponent" }""" + ), Path.Combine(stage, "carrier-bootstrap-wrong"), - sharedLayer); + sharedLayer +); var bootstrapMissingType = Packager.Pack( carrierSource, BootstrapManifest("""{ "assembly": "probe.dll", "type": "Hosihikari.NoSuchConfigurator" }"""), Path.Combine(stage, "carrier-bootstrap-missing"), - sharedLayer); + sharedLayer +); var bootstrapRealType = Packager.Pack( carrierSource, - BootstrapManifest("""{ "assembly": "probe.dll", "type": "Hosihikari.Bindings.ProbeConfigurator" }"""), + BootstrapManifest( + """{ "assembly": "probe.dll", "type": "Hosihikari.Bindings.ProbeConfigurator" }""" + ), Path.Combine(stage, "carrier-bootstrap-real"), - sharedLayer); -checks.Add(( - "A58 carrier 组校验程序集与类型", - !carrierMissingType.Succeeded - && carrierMissingType.Problems.Any(problem => problem.Contains("NoSuchComponent")) - && !carrierMissingAssembly.Succeeded - && carrierMissingAssembly.Problems.Any(problem => problem.Contains("nope.dll")) - && !carrierAbstract.Succeeded - && carrierRealType.Succeeded - && !bootstrapNotConfigurator.Succeeded - && bootstrapNotConfigurator.Problems.Any(problem => problem.Contains("ICarrierServicesConfigurator")) - && !bootstrapMissingType.Succeeded - && bootstrapMissingType.Problems.Any(problem => problem.Contains("NoSuchConfigurator")) - && bootstrapRealType.Succeeded, - string.Join(" | ", carrierMissingType.Problems - .Concat(carrierMissingAssembly.Problems) - .Concat(carrierAbstract.Problems) - .Concat(carrierRealType.Problems) - .Concat(bootstrapNotConfigurator.Problems) - .Concat(bootstrapMissingType.Problems) - .Concat(bootstrapRealType.Problems)) -)); + sharedLayer +); +checks.Add( + ( + "A58 carrier 组校验程序集与类型", + !carrierMissingType.Succeeded + && carrierMissingType.Problems.Any(problem => problem.Contains("NoSuchComponent")) + && !carrierMissingAssembly.Succeeded + && carrierMissingAssembly.Problems.Any(problem => problem.Contains("nope.dll")) + && !carrierAbstract.Succeeded + && carrierRealType.Succeeded + && !bootstrapNotConfigurator.Succeeded + && bootstrapNotConfigurator.Problems.Any(problem => + problem.Contains("ICarrierServicesConfigurator") + ) + && !bootstrapMissingType.Succeeded + && bootstrapMissingType.Problems.Any(problem => problem.Contains("NoSuchConfigurator")) + && bootstrapRealType.Succeeded, + string.Join( + " | ", + carrierMissingType + .Problems.Concat(carrierMissingAssembly.Problems) + .Concat(carrierAbstract.Problems) + .Concat(carrierRealType.Problems) + .Concat(bootstrapNotConfigurator.Problems) + .Concat(bootstrapMissingType.Problems) + .Concat(bootstrapRealType.Problems) + ) + ) +); // A61:组件阶段按清单装配、逆序停止,且拿到的是总线与日志(FX-0061)。 // A62:停止超时只记账、不再等待,退出不被挂住的组件拖住(FX-0063 的第三段)。 @@ -704,43 +877,58 @@ string BootstrapManifest(string bootstrap) => WriteManifest("carrier-" + Guid.Ne _ => { }, services, null, - new PluginManagerOptions { ComponentStopTimeout = TimeSpan.FromMilliseconds(200) }); + new PluginManagerOptions { ComponentStopTimeout = TimeSpan.FromMilliseconds(200) } +); var componentSource = Path.Combine(stage, "component-source"); Directory.CreateDirectory(componentSource); File.Copy( Path.Combine(AppContext.BaseDirectory, "Hosihikari.Bindings.Stub.dll"), Path.Combine(componentSource, "probe.dll"), - overwrite: true); + overwrite: true +); var componentStarted = componentHost.StartComponents( componentSource, - [new ManifestCarrierComponent - { - Assembly = "probe.dll", - Type = "Hosihikari.Bindings.ProbeCarrierComponent", - }]); + [ + new ManifestCarrierComponent + { + Assembly = "probe.dll", + Type = "Hosihikari.Bindings.ProbeCarrierComponent", + }, + ] +); var componentSawBus = ProbeCarrierComponent.SeenBus is not null; + // 载体服务出口与插件侧同一份:组件从它取宿主句柄(Endstone 的 Plugin/Server)。 -var componentSawCarrierServices = ReferenceEquals(ProbeCarrierComponent.SeenCarrierServices, services); +var componentSawCarrierServices = ReferenceEquals( + ProbeCarrierComponent.SeenCarrierServices, + services +); ProbeCarrierComponent.HangOnStop = true; var componentStopWatch = System.Diagnostics.Stopwatch.StartNew(); componentHost.StopComponents(); componentStopWatch.Stop(); -checks.Add(( - "A61 组件按清单启动并拿到总线与载体服务,停止超时不拖住退出", - componentStarted && componentSawBus && componentSawCarrierServices - && ProbeCarrierComponent.Started == 1 && ProbeCarrierComponent.Stopped >= 1 - && componentStopWatch.Elapsed < TimeSpan.FromSeconds(5), - $"started={componentStarted} sawBus={componentSawBus} sawCarrierServices={componentSawCarrierServices} " - + $"starts={ProbeCarrierComponent.Started} stops={ProbeCarrierComponent.Stopped} " - + $"elapsed={componentStopWatch.ElapsedMilliseconds}ms" -)); +checks.Add( + ( + "A61 组件按清单启动并拿到总线与载体服务,停止超时不拖住退出", + componentStarted + && componentSawBus + && componentSawCarrierServices + && ProbeCarrierComponent.Started == 1 + && ProbeCarrierComponent.Stopped >= 1 + && componentStopWatch.Elapsed < TimeSpan.FromSeconds(5), + $"started={componentStarted} sawBus={componentSawBus} sawCarrierServices={componentSawCarrierServices} " + + $"starts={ProbeCarrierComponent.Started} stops={ProbeCarrierComponent.Stopped} " + + $"elapsed={componentStopWatch.ElapsedMilliseconds}ms" + ) +); // A62:组件类型不存在、程序集不存在时启动失败并记账,不抛。 var badComponentHost = new PluginManager( pluginsRoot, Path.Combine(stage, "components-bad", "data"), Path.Combine(stage, "components-bad", "config"), - _ => { }); + _ => { } +); var badComponentStarted = badComponentHost.StartComponents( componentSource, [ @@ -750,64 +938,73 @@ [new ManifestCarrierComponent Assembly = "probe.dll", Type = "Hosihikari.Bindings.NoSuchComponent", }, - ]); -checks.Add(( - "A62 组件装配失败只记账", - !badComponentStarted, - $"started={badComponentStarted}" -)); + ] +); +checks.Add(("A62 组件装配失败只记账", !badComponentStarted, $"started={badComponentStarted}")); // A60:信封里的展示字段是单向派生副本:清单有就写,没有就不写(FX-0058)。 // 它是父级与面板读的那一份,作者不该为它再手写一遍。 -var envelope = BuildEnvelopeProbe(""" +var envelope = BuildEnvelopeProbe( + """ { "schemaVersion": 1, "name": "Shown", "entry": "Shown.dll", "version": "1.0.0", "loader": "stub", "kind": "plugin", "apiVersion": 3, "description": "一句话说明", "author": "某作者", "dependencies": [ { "name": "hosihikari" } ] } - """); -var envelopePlain = BuildEnvelopeProbe(""" + """ +); +var envelopePlain = BuildEnvelopeProbe( + """ { "schemaVersion": 1, "name": "Shown", "entry": "Shown.dll", "version": "1.0.0", "loader": "stub", "kind": "plugin", "apiVersion": 3, "dependencies": [ { "name": "hosihikari" } ] } - """); + """ +); using var envelopeDocument = envelope is null ? null : JsonDocument.Parse(envelope); var envelopeRoot = envelopeDocument?.RootElement; -checks.Add(( - "A60 信封按清单派生展示字段,缺了就省", - envelopeRoot is { } shown - && shown.GetProperty("description").GetString() == "一句话说明" - && shown.GetProperty("author").GetString() == "某作者" - && envelopePlain is not null - && !envelopePlain.Contains("\"description\"", StringComparison.Ordinal) - && !envelopePlain.Contains("\"author\"", StringComparison.Ordinal), - envelope ?? "(没打出包)" -)); +checks.Add( + ( + "A60 信封按清单派生展示字段,缺了就省", + envelopeRoot is { } shown + && shown.GetProperty("description").GetString() == "一句话说明" + && shown.GetProperty("author").GetString() == "某作者" + && envelopePlain is not null + && !envelopePlain.Contains("\"description\"", StringComparison.Ordinal) + && !envelopePlain.Contains("\"author\"", StringComparison.Ordinal), + envelope ?? "(没打出包)" + ) +); // A63:载体声明的共享层与基地清单并集;没有载体目录时只回基地清单(FX-0061)。 // 打包期靠它把绑定程序集从插件包里剔掉,运行期也靠它判身份。 var carrierHome = Path.Combine(stage, "carrier-with-bindings"); Directory.CreateDirectory(carrierHome); -File.WriteAllText(Path.Combine(carrierHome, "hosihikari.json"), """ +File.WriteAllText( + Path.Combine(carrierHome, "hosihikari.json"), + """ { "schemaVersion": 1, "name": "hosihikari", "entry": "hosihikari.dll", "version": "1.2.3", "loader": "assembly", "kind": "carrier", "apiVersion": 3, "dependencies": [ { "name": "hosihikari" } ], "carrier": { "sharedAssemblies": [ "Hosihikari.Bindings.Stub.dll" ], "components": [] } } - """); + """ +); var mergedLayer = AssemblyPluginLoader.SharedLayerFor(carrierHome); -checks.Add(( - "A63 载体共享层并入基地清单", - mergedLayer.Contains("Hosihikari.Bindings.Stub.dll") - && mergedLayer.Contains("Hosihikari.Plugin.Abstractions.dll") - && !AssemblyPluginLoader.SharedLayerFor(Path.Combine(stage, "no-such-carrier")) - .Contains("Hosihikari.Bindings.Stub.dll"), - string.Join(", ", mergedLayer) -)); +checks.Add( + ( + "A63 载体共享层并入基地清单", + mergedLayer.Contains("Hosihikari.Bindings.Stub.dll") + && mergedLayer.Contains("Hosihikari.Plugin.Abstractions.dll") + && !AssemblyPluginLoader + .SharedLayerFor(Path.Combine(stage, "no-such-carrier")) + .Contains("Hosihikari.Bindings.Stub.dll"), + string.Join(", ", mergedLayer) + ) +); // A67:载体启动装配(FX-0064)——读清单、并共享层、跑配置器,句柄原样交到服务里, // 组件再从载体服务里取到配置器注册的东西。A68:没有载体目录时照常启动。 @@ -816,8 +1013,11 @@ envelopeRoot is { } shown File.Copy( Path.Combine(AppContext.BaseDirectory, "Hosihikari.Bindings.Stub.dll"), Path.Combine(startupHome, "probe.dll"), - overwrite: true); -File.WriteAllText(Path.Combine(startupHome, "hosihikari.json"), """ + overwrite: true +); +File.WriteAllText( + Path.Combine(startupHome, "hosihikari.json"), + """ { "schemaVersion": 1, "name": "hosihikari", "entry": "hosihikari.dll", "version": "2.0.0", "loader": "assembly", "kind": "carrier", "apiVersion": 3, @@ -828,38 +1028,55 @@ envelopeRoot is { } shown "bootstrap": { "assembly": "probe.dll", "type": "Hosihikari.Bindings.ProbeConfigurator" } } } - """); -var startupLoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder => builder.AddSimpleConsole()); -var carrierStartup = CarrierStartup.Create(startupHome, 0x2A, startupLoggerFactory, out var startupError); -var startupService = carrierStartup.Services.GetService(typeof(ProbeCarrierService)) as ProbeCarrierService; + """ +); +var startupLoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + builder.AddSimpleConsole() +); +var carrierStartup = CarrierStartup.Create( + startupHome, + 0x2A, + startupLoggerFactory, + out var startupError +); +var startupService = + carrierStartup.Services.GetService(typeof(ProbeCarrierService)) as ProbeCarrierService; var startupHost = new PluginManager( pluginsRoot, Path.Combine(stage, "carrier-startup", "data"), Path.Combine(stage, "carrier-startup", "config"), _ => { }, - carrierStartup.Services); + carrierStartup.Services +); var startupComponents = startupHost.StartComponents(startupHome, carrierStartup.Components); -var componentService = ProbeCarrierComponent.SeenCarrierServices?.GetService(typeof(ProbeCarrierService)) +var componentService = + ProbeCarrierComponent.SeenCarrierServices?.GetService(typeof(ProbeCarrierService)) as ProbeCarrierService; startupHost.StopComponents(); ProbeCarrierComponent.HangOnStop = false; -checks.Add(( - "A67 载体启动装配:清单、共享层、配置器(目录+句柄,先于组件)", - startupError is null - && carrierStartup.Components.Count == 1 - && carrierStartup.SharedAssemblies.Count == 1 - && startupService?.HostHandle == 0x2A - && ProbeConfigurator.LastHost == 0x2A - && ProbeConfigurator.LastDirectory is { } seenDirectory - && string.Equals(Path.GetFullPath(seenDirectory), Path.GetFullPath(startupHome), StringComparison.OrdinalIgnoreCase) - && ProbeCarrierComponent.SawBootstrap - && startupComponents - && componentService?.HostHandle == 0x2A, - $"error={startupError ?? "无"} components={carrierStartup.Components.Count} " - + $"shared={carrierStartup.SharedAssemblies.Count} handle={startupService?.HostHandle} " - + $"hook={componentService?.HostHandle} dir={ProbeConfigurator.LastDirectory} " - + $"bootstrapFirst={ProbeCarrierComponent.SawBootstrap}" -)); +checks.Add( + ( + "A67 载体启动装配:清单、共享层、配置器(目录+句柄,先于组件)", + startupError is null + && carrierStartup.Components.Count == 1 + && carrierStartup.SharedAssemblies.Count == 1 + && startupService?.HostHandle == 0x2A + && ProbeConfigurator.LastHost == 0x2A + && ProbeConfigurator.LastDirectory is { } seenDirectory + && string.Equals( + Path.GetFullPath(seenDirectory), + Path.GetFullPath(startupHome), + StringComparison.OrdinalIgnoreCase + ) + && ProbeCarrierComponent.SawBootstrap + && startupComponents + && componentService?.HostHandle == 0x2A, + $"error={startupError ?? "无"} components={carrierStartup.Components.Count} " + + $"shared={carrierStartup.SharedAssemblies.Count} handle={startupService?.HostHandle} " + + $"hook={componentService?.HostHandle} dir={ProbeConfigurator.LastDirectory} " + + $"bootstrapFirst={ProbeCarrierComponent.SawBootstrap}" + ) +); // A69:父级重载后换代载体服务——组件重新启动时看到的必须是新的提供器(FX-0065)。 var republishOld = new Microsoft.Extensions.DependencyInjection.ServiceCollection() @@ -878,37 +1095,48 @@ startupError is null Path.Combine(stage, "carrier-republish", "data"), Path.Combine(stage, "carrier-republish", "config"), _ => { }, - republishOld); + republishOld +); republishHost.RepublishCarrierServices(republishNew); var republishStarted = republishHost.StartComponents( startupHome, - [new ManifestCarrierComponent - { - Assembly = "probe.dll", - Type = "Hosihikari.Bindings.ProbeCarrierComponent", - }]); -var republishedService = ProbeCarrierComponent.SeenCarrierServices?.GetService(typeof(ProbeCarrierService)) + [ + new ManifestCarrierComponent + { + Assembly = "probe.dll", + Type = "Hosihikari.Bindings.ProbeCarrierComponent", + }, + ] +); +var republishedService = + ProbeCarrierComponent.SeenCarrierServices?.GetService(typeof(ProbeCarrierService)) as ProbeCarrierService; republishHost.StopComponents(); -checks.Add(( - "A69 重载后换代的载体服务对组件可见,旧容器被收掉", - republishStarted && ReferenceEquals(ProbeCarrierComponent.SeenCarrierServices, republishNew) - && republishedService?.HostHandle == 7 - && oldProbe.Disposed - && oldAsyncProbe.Disposed, - $"started={republishStarted} handle={republishedService?.HostHandle} " - + $"oldDisposed={oldProbe.Disposed}/{oldAsyncProbe.Disposed}" -)); +checks.Add( + ( + "A69 重载后换代的载体服务对组件可见,旧容器被收掉", + republishStarted + && ReferenceEquals(ProbeCarrierComponent.SeenCarrierServices, republishNew) + && republishedService?.HostHandle == 7 + && oldProbe.Disposed + && oldAsyncProbe.Disposed, + $"started={republishStarted} handle={republishedService?.HostHandle} " + + $"oldDisposed={oldProbe.Disposed}/{oldAsyncProbe.Disposed}" + ) +); var emptyStartup = CarrierStartup.Create(null, 0, startupLoggerFactory, out var emptyError); -checks.Add(( - "A68 没有载体目录时照常启动", - emptyError is null - && emptyStartup.Components.Count == 0 - && emptyStartup.SharedAssemblies.Count == 0 - && emptyStartup.Services.GetService(typeof(Microsoft.Extensions.Logging.ILoggerFactory)) is not null, - $"error={emptyError ?? "无"} components={emptyStartup.Components.Count}" -)); +checks.Add( + ( + "A68 没有载体目录时照常启动", + emptyError is null + && emptyStartup.Components.Count == 0 + && emptyStartup.SharedAssemblies.Count == 0 + && emptyStartup.Services.GetService(typeof(Microsoft.Extensions.Logging.ILoggerFactory)) + is not null, + $"error={emptyError ?? "无"} components={emptyStartup.Components.Count}" + ) +); // A64:自持态能重载,父级态拒绝(FX-0062)。 // Reloadable 没有任何依赖者,卸载不会撞上依赖图;父级态用一个不拥有插件集的管理器验证。 @@ -918,11 +1146,13 @@ emptyError is null var disableCalls = File.Exists(disableLog) ? File.ReadAllLines(disableLog).Count(line => line.Length > 0) : 0; -checks.Add(( - "A64 自持态 Reload 走完 Disable→Unload→Load→Enable,停用只调一次", - reloadedSelf && disableCalls == 1, - $"{reloadOutcome.Error ?? "已重载"} disableCalls={disableCalls}" -)); +checks.Add( + ( + "A64 自持态 Reload 走完 Disable→Unload→Load→Enable,停用只调一次", + reloadedSelf && disableCalls == 1, + $"{reloadOutcome.Error ?? "已重载"} disableCalls={disableCalls}" + ) +); var parentedManager = new PluginManager( pluginsRoot, @@ -931,13 +1161,16 @@ emptyError is null _ => { }, services, null, - new PluginManagerOptions { OwnsPluginSet = false }); + new PluginManagerOptions { OwnsPluginSet = false } +); var parentedReload = parentedManager.Reload("Reloadable"); -checks.Add(( - "A65 父级态 Reload 返回 NotSupported", - parentedReload.NotSupported && !parentedReload.Reloaded && parentedReload.Error is not null, - parentedReload.Error ?? "(没给原因)" -)); +checks.Add( + ( + "A65 父级态 Reload 返回 NotSupported", + parentedReload.NotSupported && !parentedReload.Reloaded && parentedReload.Error is not null, + parentedReload.Error ?? "(没给原因)" + ) +); // A29:拒绝启用留在册、未启用(FX-0030) var guardedLoaded = host.Load(Path.Combine(stage, "parented", "Guarded")); @@ -948,11 +1181,13 @@ emptyError is null guardedLoader.RefuseEnable = true; var enableRepeated = host.Enable("Guarded"); guardedLoader.RefuseEnable = false; -checks.Add(( - "A29 拒绝启用留在册、未启用;已启用时重复启用不再调钩子", - guardedLoaded && enableRefused && enableAllowed && enableRepeated, - $"loaded={guardedLoaded} refused={enableRefused} later={enableAllowed} repeated={enableRepeated}" -)); +checks.Add( + ( + "A29 拒绝启用留在册、未启用;已启用时重复启用不再调钩子", + guardedLoaded && enableRefused && enableAllowed && enableRepeated, + $"loaded={guardedLoaded} refused={enableRefused} later={enableAllowed} repeated={enableRepeated}" + ) +); // A30:拒绝停用让卸载中止;允许后才真正卸掉(FX-0030) guardedLoader.RefuseDisable = true; @@ -961,41 +1196,56 @@ emptyError is null var stillLoaded = host.LoadedNames.Contains("Guarded"); guardedLoader.RefuseDisable = false; var unloadedAfter = host.Unload("Guarded"); -checks.Add(( - "A30 拒绝停用中止卸载", - disableRefused && !unloadRefused.Released - && unloadRefused.Error?.Contains("拒绝停用") == true && stillLoaded && unloadedAfter.Released, - unloadRefused.Error ?? "(居然卸掉了)" -)); +checks.Add( + ( + "A30 拒绝停用中止卸载", + disableRefused + && !unloadRefused.Released + && unloadRefused.Error?.Contains("拒绝停用") == true + && stillLoaded + && unloadedAfter.Released, + unloadRefused.Error ?? "(居然卸掉了)" + ) +); // A31:钩子抛异常触发故障卸载,并通知载体(FX-0030) var faultyLoaded = host.Load(Path.Combine(stage, "parented", "Faulty")); var faultyEnable = host.Enable("Faulty"); -checks.Add(( - "A31 钩子抛出触发故障卸载", - faultyLoaded && !faultyEnable && !host.LoadedNames.Contains("Faulty") - && removed.Any(name => name == "Faulty"), - $"removed=[{string.Join(", ", removed)}]" -)); +checks.Add( + ( + "A31 钩子抛出触发故障卸载", + faultyLoaded + && !faultyEnable + && !host.LoadedNames.Contains("Faulty") + && removed.Any(name => name == "Faulty"), + $"removed=[{string.Join(", ", removed)}]" + ) +); // A32:Loader 在钩子之外报告的故障走同一条路径(FX-0030) var vanishingLoaded = host.Load(Path.Combine(stage, "parented", "Vanishing")); + // 先启用:闸门关闭时定时器不会跑(FX-0035)。 host.Enable("Vanishing"); Thread.Sleep(150); -checks.Add(( - "A32 钩子之外的故障也卸载并通知", - vanishingLoaded && !host.LoadedNames.Contains("Vanishing") - && removed.Any(name => name == "Vanishing"), - $"removed=[{string.Join(", ", removed)}]" -)); +checks.Add( + ( + "A32 钩子之外的故障也卸载并通知", + vanishingLoaded + && !host.LoadedNames.Contains("Vanishing") + && removed.Any(name => name == "Vanishing"), + $"removed=[{string.Join(", ", removed)}]" + ) +); // A43:故障报告必须先把 _gate 让出来再回调。父级线程可能正握着日志锁等 _gate, // 报告在锁内回调就会互相等死。这里用第二个管理器复现锁序:回调里让另一个线程去 Load, // 若 _gate 还攥在报告线程手里,那个 Load 在超时内完不成。 var probePackage = Path.Combine(stage, "parented", "Probe"); Directory.CreateDirectory(probePackage); -File.WriteAllText(Path.Combine(probePackage, "hosihikari.json"), """ +File.WriteAllText( + Path.Combine(probePackage, "hosihikari.json"), + """ { "name": "Probe", "entry": "Probe.dll", @@ -1003,7 +1253,8 @@ emptyError is null "dependencies": [ { "name": "hosihikari" } ], "loader": "guarded" } - """); + """ +); PluginManager? probeHost = null; var probeTimedOut = false; probeHost = new PluginManager( @@ -1023,16 +1274,19 @@ emptyError is null { probeTimedOut = true; } - }); + } +); probeHost.RegisterLoader(new GuardedPluginLoader()); probeHost.Load(Path.Combine(stage, "parented", "Vanishing")); probeHost.Enable("Vanishing"); Thread.Sleep(200); -checks.Add(( - "A43 故障报告先放锁再回调", - !probeTimedOut && probeHost.LoadedNames.Contains("Probe"), - $"timedOut={probeTimedOut} loaded=[{string.Join(", ", probeHost.LoadedNames)}]" -)); +checks.Add( + ( + "A43 故障报告先放锁再回调", + !probeTimedOut && probeHost.LoadedNames.Contains("Probe"), + $"timedOut={probeTimedOut} loaded=[{string.Join(", ", probeHost.LoadedNames)}]" + ) +); // A44:Enable/Disable 的异常路径同样必须先把 _gate 让出来再回调。 // Faulty 的 OnEnable 抛异常;报告回调里让另一个线程去 Load,超时即说明外层锁没放。 @@ -1057,17 +1311,21 @@ emptyError is null { enableProbeTimedOut = true; } - }); + } +); enableHost.RegisterLoader(new GuardedPluginLoader()); enableHost.Load(Path.Combine(stage, "parented", "Faulty")); var faultyEnabled = enableHost.Enable("Faulty"); -checks.Add(( - "A44 启停异常先放锁再回调", - !faultyEnabled && !enableProbeTimedOut - && !enableHost.LoadedNames.Contains("Faulty") - && enableHost.LoadedNames.Contains("Probe"), - $"enabled={faultyEnabled} timedOut={enableProbeTimedOut} loaded=[{string.Join(", ", enableHost.LoadedNames)}]" -)); +checks.Add( + ( + "A44 启停异常先放锁再回调", + !faultyEnabled + && !enableProbeTimedOut + && !enableHost.LoadedNames.Contains("Faulty") + && enableHost.LoadedNames.Contains("Probe"), + $"enabled={faultyEnabled} timedOut={enableProbeTimedOut} loaded=[{string.Join(", ", enableHost.LoadedNames)}]" + ) +); // A45:故障属于抛出的那个实例。报告在锁外,期间同名插件可能已经重载 —— // 随后按名字报故障就会把健康的新实例卸掉。这里在报告回调里完成同名重载, @@ -1090,19 +1348,25 @@ emptyError is null raceHost!.Unload("Faulty"); raceLoader.ThrowOnEnable = false; raceHost.Load(Path.Combine(stage, "parented", "Faulty")); - }); + } +); raceHost.RegisterLoader(raceLoader); raceHost.Load(Path.Combine(stage, "parented", "Faulty")); var raceFaulted = raceHost.Enable("Faulty"); var raceSurvived = raceHost.LoadedNames.Contains("Faulty"); var raceReenabled = raceHost.Enable("Faulty"); -checks.Add(( - "A45 故障不卸载同名新实例", - !raceFaulted && raceReloaded && raceSurvived && raceReenabled - && raceHost.LoadedNames.Contains("Faulty"), - $"faulted={raceFaulted} reloaded={raceReloaded} survived={raceSurvived} " - + $"reenabled={raceReenabled} loaded=[{string.Join(", ", raceHost.LoadedNames)}]" -)); +checks.Add( + ( + "A45 故障不卸载同名新实例", + !raceFaulted + && raceReloaded + && raceSurvived + && raceReenabled + && raceHost.LoadedNames.Contains("Faulty"), + $"faulted={raceFaulted} reloaded={raceReloaded} survived={raceSurvived} " + + $"reenabled={raceReenabled} loaded=[{string.Join(", ", raceHost.LoadedNames)}]" + ) +); // A46:上下文被外部保留时,故障卸载仍要能回收 ALC。 // 上下文只带名字与装载编号;带上槽位、实例或委托,外部的这一份引用就会钉住整个 ALC。 @@ -1110,83 +1374,114 @@ emptyError is null OutputDirectory("Retained"), Path.Combine(repoRoot, "test", "Retained", "hosihikari.json"), Path.Combine(stage, "parented"), - sharedLayer); -var retainedLoaded = retainedPacked.PackageDirectory is { } retainedPackage && host.Load(retainedPackage); + sharedLayer +); +var retainedLoaded = + retainedPacked.PackageDirectory is { } retainedPackage && host.Load(retainedPackage); var retainedFaulted = !host.Enable("Retained"); var retainedRemoved = removed.Any(name => name == "Retained"); -var retainedFailure = reported.LastOrDefault(entry => entry.Contains("Retained") && entry.Contains("没完成")); +var retainedFailure = reported.LastOrDefault(entry => + entry.Contains("Retained") && entry.Contains("没完成") +); ContextSink.Held = null; -checks.Add(( - "A46 外部保留上下文仍能回收 ALC", - retainedLoaded && retainedFaulted && retainedRemoved && retainedFailure is null, - $"packed={retainedPacked.Succeeded} loaded={retainedLoaded} faulted={retainedFaulted} " - + $"removed={retainedRemoved} failure={retainedFailure ?? "无"}" -)); +checks.Add( + ( + "A46 外部保留上下文仍能回收 ALC", + retainedLoaded && retainedFaulted && retainedRemoved && retainedFailure is null, + $"packed={retainedPacked.Succeeded} loaded={retainedLoaded} faulted={retainedFaulted} " + + $"removed={retainedRemoved} failure={retainedFailure ?? "无"}" + ) +); // A17:Loader 在装载时抛出 —— 如实把**完整异常**报出来,且这一个插件没装上(FX-0009) var thrown = reported.FirstOrDefault(entry => entry.Contains(ThrowingPluginLoader.ThrowMessage)); var thrownFull = thrown is not null && thrown.Contains(nameof(InvalidOperationException)); -checks.Add(( - "A17 装载抛出时如实报告且隔离", - !host.LoadedNames.Contains("Throwing") && thrownFull, - thrown ?? "(没有报告)" -)); +checks.Add( + ( + "A17 装载抛出时如实报告且隔离", + !host.LoadedNames.Contains("Throwing") && thrownFull, + thrown ?? "(没有报告)" + ) +); // A18:清单 type 不是 hosihikari 的包必须被拒 —— 父级态下它根本到不了我们手里(FX-0006) -var typeRefused = !host.LoadedNames.Contains("WrongType") - && reported.Any(entry => entry.Contains("type 必须是")); -checks.Add(( - "A18 type 写错时拒载", - typeRefused, - reported.LastOrDefault(entry => entry.Contains("type 必须是")) ?? "(未拒载)" -)); +var typeRefused = + !host.LoadedNames.Contains("WrongType") && reported.Any(entry => entry.Contains("type 必须是")); +checks.Add( + ( + "A18 type 写错时拒载", + typeRefused, + reported.LastOrDefault(entry => entry.Contains("type 必须是")) ?? "(未拒载)" + ) +); // A19:打包期同样要拦 —— 写错的包在父级那边连路由都过不去,失败点离病因很远(FX-0006) var wrongTypeManifest = Path.Combine(stage, "wrong-type.json"); File.WriteAllText( wrongTypeManifest, File.ReadAllText(Path.Combine(repoRoot, "test", "Foo", "hosihikari.json")) - .Replace("\"loader\": \"assembly\",", "\"loader\": \"assembly\", \"type\": \"assembly\",")); + .Replace("\"loader\": \"assembly\",", "\"loader\": \"assembly\", \"type\": \"assembly\",") +); var wrongType = Packager.Pack( - OutputDirectory("Foo"), wrongTypeManifest, Path.Combine(stage, "wrong-type-out"), sharedLayer); + OutputDirectory("Foo"), + wrongTypeManifest, + Path.Combine(stage, "wrong-type-out"), + sharedLayer +); var typeProblem = wrongType.Problems.FirstOrDefault(problem => problem.Contains("type 必须是")); -checks.Add(( - "A19 打包拒绝 type 写错的清单", - !wrongType.Succeeded && typeProblem is not null, - typeProblem ?? "(未拦下)" -)); +checks.Add( + ( + "A19 打包拒绝 type 写错的清单", + !wrongType.Succeeded && typeProblem is not null, + typeProblem ?? "(未拦下)" + ) +); // A22:entry 指向的文件不在构建输出里 —— 报错点离病因很远,所以拦在打包期(FX-0008) var missingEntry = Packager.Pack( OutputDirectory("Lib"), WriteManifest("missing-entry", ManifestLike("Lib", "Nope.dll")), Path.Combine(stage, "missing-entry-out"), - sharedLayer); -var missingProblem = missingEntry.Problems.FirstOrDefault(problem => problem.Contains("不在构建输出里")); -checks.Add(( - "A22 打包拒绝不存在的入口", - !missingEntry.Succeeded && missingProblem is not null, - missingProblem ?? "(未拦下)" -)); + sharedLayer +); +var missingProblem = missingEntry.Problems.FirstOrDefault(problem => + problem.Contains("不在构建输出里") +); +checks.Add( + ( + "A22 打包拒绝不存在的入口", + !missingEntry.Succeeded && missingProblem is not null, + missingProblem ?? "(未拦下)" + ) +); // A23:入口特性不是恰好一个 —— Lib 一个都没声明 var noEntry = Packager.Pack( OutputDirectory("Lib"), WriteManifest("no-entry", ManifestLike("Lib", "Lib.dll")), Path.Combine(stage, "no-entry-out"), - sharedLayer); + sharedLayer +); var noEntryProblem = noEntry.Problems.FirstOrDefault(problem => problem.Contains("个入口")); -checks.Add(( - "A23 打包拒绝没有入口声明的程序集", - !noEntry.Succeeded && noEntryProblem is not null, - noEntryProblem ?? "(未拦下)" -)); +checks.Add( + ( + "A23 打包拒绝没有入口声明的程序集", + !noEntry.Succeeded && noEntryProblem is not null, + noEntryProblem ?? "(未拦下)" + ) +); // A35:入口程序集没有声明入口时,Loader 报出数量(FX-0008) var noEntryPackage = Path.Combine(stage, "parented", "NoEntry"); Directory.CreateDirectory(noEntryPackage); -File.Copy(Path.Combine(OutputDirectory("Lib"), "Lib.dll"), Path.Combine(noEntryPackage, "Lib.dll"), overwrite: true); -File.WriteAllText(Path.Combine(noEntryPackage, "hosihikari.json"), """ +File.Copy( + Path.Combine(OutputDirectory("Lib"), "Lib.dll"), + Path.Combine(noEntryPackage, "Lib.dll"), + overwrite: true +); +File.WriteAllText( + Path.Combine(noEntryPackage, "hosihikari.json"), + """ { "name": "NoEntry", "entry": "Lib.dll", @@ -1194,18 +1489,23 @@ emptyError is null "dependencies": [ { "name": "hosihikari" } ], "loader": "assembly" } - """); + """ +); var noEntryLoaded = host.Load(noEntryPackage); -checks.Add(( - "A35 入口程序集没有入口声明时报出数量", - !noEntryLoaded && providerLogs.Any(line => line.Contains("声明了 0 个入口")), - providerLogs.LastOrDefault(line => line.Contains("个入口")) ?? "(无报告)" -)); +checks.Add( + ( + "A35 入口程序集没有入口声明时报出数量", + !noEntryLoaded && providerLogs.Any(line => line.Contains("声明了 0 个入口")), + providerLogs.LastOrDefault(line => line.Contains("个入口")) ?? "(无报告)" + ) +); // A36:入口文件不在包里时,Loader 报出路径而不是文件异常(FX-0008) var missingEntryPackage = Path.Combine(stage, "parented", "NoEntryFile"); Directory.CreateDirectory(missingEntryPackage); -File.WriteAllText(Path.Combine(missingEntryPackage, "hosihikari.json"), """ +File.WriteAllText( + Path.Combine(missingEntryPackage, "hosihikari.json"), + """ { "name": "NoEntryFile", "entry": "Nope.dll", @@ -1213,16 +1513,21 @@ emptyError is null "dependencies": [ { "name": "hosihikari" } ], "loader": "assembly" } - """); + """ +); var missingEntryLoaded = host.Load(missingEntryPackage); -checks.Add(( - "A36 入口文件不在包里时报出路径", - !missingEntryLoaded && providerLogs.Any(line => line.Contains("不在包里")), - providerLogs.LastOrDefault(line => line.Contains("不在包里")) ?? "(无报告)" -)); +checks.Add( + ( + "A36 入口文件不在包里时报出路径", + !missingEntryLoaded && providerLogs.Any(line => line.Contains("不在包里")), + providerLogs.LastOrDefault(line => line.Contains("不在包里")) ?? "(无报告)" + ) +); // A37:打包期同样拦 schemaVersion(FX-0012) -var badFormatManifest = WriteManifest("bad-format", """ +var badFormatManifest = WriteManifest( + "bad-format", + """ { "name": "Foo", "entry": "Foo.dll", @@ -1230,64 +1535,95 @@ emptyError is null "dependencies": [ { "name": "hosihikari" } ], "schemaVersion": 9 } - """); + """ +); var badFormat = Packager.Pack( - OutputDirectory("Foo"), badFormatManifest, Path.Combine(stage, "bad-format-out"), sharedLayer); -var badFormatProblem = badFormat.Problems.FirstOrDefault(problem => problem.Contains("schemaVersion")); -checks.Add(( - "A37 打包拒绝 schemaVersion 不匹配", - !badFormat.Succeeded && badFormatProblem is not null, - badFormatProblem ?? "(未拦下)" -)); + OutputDirectory("Foo"), + badFormatManifest, + Path.Combine(stage, "bad-format-out"), + sharedLayer +); +var badFormatProblem = badFormat.Problems.FirstOrDefault(problem => + problem.Contains("schemaVersion") +); +checks.Add( + ( + "A37 打包拒绝 schemaVersion 不匹配", + !badFormat.Succeeded && badFormatProblem is not null, + badFormatProblem ?? "(未拦下)" + ) +); // A38:打包期 entry 不能出界(FX-0006) var escapingManifest = WriteManifest("escaping-entry", ManifestLike("Lib", "../Lib.dll")); var escaping = Packager.Pack( - OutputDirectory("Lib"), escapingManifest, Path.Combine(stage, "escaping-entry-out"), sharedLayer); + OutputDirectory("Lib"), + escapingManifest, + Path.Combine(stage, "escaping-entry-out"), + sharedLayer +); var escapingProblem = escaping.Problems.FirstOrDefault(problem => problem.Contains("包内相对路径")); -checks.Add(( - "A38 打包拒绝出界的入口", - !escaping.Succeeded && escapingProblem is not null, - escapingProblem ?? "(未拦下)" -)); +checks.Add( + ( + "A38 打包拒绝出界的入口", + !escaping.Succeeded && escapingProblem is not null, + escapingProblem ?? "(未拦下)" + ) +); // A41:输出目录落在构建输出里时拒绝,避免递归复制自我嵌套(FX-0034) var nested = Packager.Pack( OutputDirectory("Lib"), WriteManifest("nested-output", ManifestLike("Lib", "Lib.dll")), Path.Combine(OutputDirectory("Lib"), "pack-out"), - sharedLayer); + sharedLayer +); var nestedProblem = nested.Problems.FirstOrDefault(problem => problem.Contains("打包输出")); -checks.Add(( - "A41 拒绝嵌套的打包输出", - !nested.Succeeded && nestedProblem is not null, - nestedProblem ?? "(未拦下)" -)); +checks.Add( + ( + "A41 拒绝嵌套的打包输出", + !nested.Succeeded && nestedProblem is not null, + nestedProblem ?? "(未拦下)" + ) +); // A42:清单 name 必须是单个目录名(不能带路径分隔符) -var badNameManifest = WriteManifest("bad-name", """ +var badNameManifest = WriteManifest( + "bad-name", + """ { "name": "../Evil", "entry": "Lib.dll", "schemaVersion": 1, "kind": "plugin", "apiVersion": 3, "dependencies": [ { "name": "hosihikari" } ] } - """); + """ +); var badName = Packager.Pack( - OutputDirectory("Lib"), badNameManifest, Path.Combine(stage, "bad-name-out"), sharedLayer); -var badNameProblem = badName.Problems.FirstOrDefault(problem => problem.Contains("name 必须是单个目录名")); -checks.Add(( - "A42 打包拒绝带路径的 name", - !badName.Succeeded && badNameProblem is not null, - badNameProblem ?? "(未拦下)" -)); + OutputDirectory("Lib"), + badNameManifest, + Path.Combine(stage, "bad-name-out"), + sharedLayer +); +var badNameProblem = badName.Problems.FirstOrDefault(problem => + problem.Contains("name 必须是单个目录名") +); +checks.Add( + ( + "A42 打包拒绝带路径的 name", + !badName.Succeeded && badNameProblem is not null, + badNameProblem ?? "(未拦下)" + ) +); // A39:本机库按 RID 目录优先解析;卸载只回收托管 ALC(FX-0034) var nativeProbe = RunNativeProbe(); checks.Add(("A39 本机库 RID 优先且不阻碍回收", nativeProbe.Ok, nativeProbe.Detail)); // A26:清单里声明的第三方包在打包期还原并进包(供应链留在打包那一刻) -var withPackages = WriteManifest("with-packages", """ +var withPackages = WriteManifest( + "with-packages", + """ { "name": "Bar", "entry": "Bar.dll", @@ -1295,25 +1631,52 @@ emptyError is null "dependencies": [ { "name": "hosihikari" } ], "pack": { "packages": [ "System.IO.Hashing/10.0.0" ] } } - """); + """ +); var declared = Packager.Pack( - OutputDirectory("Bar"), withPackages, Path.Combine(stage, "with-packages-out"), sharedLayer); + OutputDirectory("Bar"), + withPackages, + Path.Combine(stage, "with-packages-out"), + sharedLayer +); var restored = declared.PackageDirectory is null ? "(没打出包)" - : (File.Exists(Path.Combine(declared.PackageDirectory, "System.IO.Hashing.dll")) ? "已还原" : "缺 dll"); -checks.Add(("A26 清单声明的第三方包在打包期还原", declared.Succeeded && restored == "已还原", - declared.Succeeded ? restored : string.Join(";", declared.Problems))); + : ( + File.Exists(Path.Combine(declared.PackageDirectory, "System.IO.Hashing.dll")) + ? "已还原" + : "缺 dll" + ); +checks.Add( + ( + "A26 清单声明的第三方包在打包期还原", + declared.Succeeded && restored == "已还原", + declared.Succeeded ? restored : string.Join(";", declared.Problems) + ) +); // A1:每个插件一个 collectible ALC(FX-0004) var collectible = CollectibleContextCount(); -checks.Add(("A1 每插件一个 collectible ALC", collectible >= 2, $"进程内 collectible ALC 数 = {collectible}")); +checks.Add( + ( + "A1 每插件一个 collectible ALC", + collectible >= 2, + $"进程内 collectible ALC 数 = {collectible}" + ) +); // A2:插件包内不得有共享层副本 —— 这是会静默失败的那条规则(FX-0004 / FX-0007 / FX-0019)。 // 清单用的是给打包工具的那一份,不再另写一份:同一份事实源(FX-0026)。 -var copies = Directory.EnumerateFiles(pluginsRoot, "*.dll", SearchOption.AllDirectories) +var copies = Directory + .EnumerateFiles(pluginsRoot, "*.dll", SearchOption.AllDirectories) .Where(file => sharedLayer.Contains(Path.GetFileName(file))) .ToArray(); -checks.Add(("A2 插件包内无共享层副本", copies.Length == 0, copies.Length == 0 ? "无副本" : string.Join(", ", copies))); +checks.Add( + ( + "A2 插件包内无共享层副本", + copies.Length == 0, + copies.Length == 0 ? "无副本" : string.Join(", ", copies) + ) +); // 从链条末端往回卸:Lua 在前、Foo 在后。反序是依赖图的另一半承诺(FX-0004)。 var lua = host.Unload("Lua"); @@ -1354,13 +1717,15 @@ emptyError is null .Select(language => language.Culture) .ToArray(); CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("zh-Hans"); -checks.Add(( - "A52 操作员文本跟随 UI 文化", - missingLanguages.Length == 0, - missingLanguages.Length == 0 - ? $"6 种语言(繁中回落简中)" - : $"缺少 {string.Join(", ", missingLanguages)}" -)); +checks.Add( + ( + "A52 操作员文本跟随 UI 文化", + missingLanguages.Length == 0, + missingLanguages.Length == 0 + ? $"6 种语言(繁中回落简中)" + : $"缺少 {string.Join(", ", missingLanguages)}" + ) +); checks.AddRange(RegressionChecks.Run(Path.Combine(stage, "regressions"))); Console.WriteLine("=== 断言 ==="); @@ -1385,7 +1750,10 @@ void Stage(string name, bool withConfig) if (withConfig) { // 作者给的默认值,随包更新(FX-0018)。 - File.WriteAllText(Path.Combine(packed.PackageDirectory!, $"{name}.conf"), "greeting = \"default\"\n"); + File.WriteAllText( + Path.Combine(packed.PackageDirectory!, $"{name}.conf"), + "greeting = \"default\"\n" + ); } } @@ -1394,14 +1762,17 @@ void StageBroken() { var package = Path.Combine(pluginsRoot, "Broken"); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), $$""" + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + $$""" { "name": "Broken", "entry": "Broken.dll", "dependencies": [ { "name": "hosihikari" } ], "apiVersion": 999 } - """); + """ + ); } // 另一种插件类型的包:入口是脚本文件,清单与程序集型同形 —— 入口怎么找是各自 Loader 的事。 @@ -1410,7 +1781,9 @@ void StageScript() var package = Path.Combine(pluginsRoot, "Lua"); Directory.CreateDirectory(package); File.WriteAllText(Path.Combine(package, "main.lua"), "print('hello from script')\n"); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), """ + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + """ { "name": "Lua", "entry": "main.lua", @@ -1418,7 +1791,8 @@ void StageScript() "dependencies": [ { "name": "Bar" }, { "name": "hosihikari" } ], "loader": "script" } - """); + """ + ); } // 诊断加载器会拒掉这个包;入口文件故意不存在,证明装载没有开始。 @@ -1426,7 +1800,9 @@ void StageDiagnostic() { var package = Path.Combine(pluginsRoot, "Diagnostic"); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), """ + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + """ { "name": "Diagnostic", "entry": "Diagnostic.dll", @@ -1434,7 +1810,8 @@ void StageDiagnostic() "dependencies": [ { "name": "hosihikari" } ], "loader": "diagnostic" } - """); + """ + ); } // 父级态的那个包:故意放在 plugins/ **外面** —— 只有父级交付能让它进来(FX-0003)。 @@ -1442,7 +1819,9 @@ void StagePinned() { var package = Path.Combine(stage, "parented", "Pinned"); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), """ + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + """ { "name": "Pinned", "entry": "Pinned.dll", @@ -1450,7 +1829,8 @@ void StagePinned() "dependencies": [ { "name": "hosihikari" } ], "loader": "pinned" } - """); + """ + ); } // 钩子语义的检验包(FX-0059 / 0063):Awaiting 的钩子真的 await,Hanging 的停用/卸载挂到取消为止。 @@ -1458,7 +1838,9 @@ void StageHooking(string name, string packageKind = "plugin") { var package = Path.Combine(stage, "parented", name); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), $$""" + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + $$""" { "schemaVersion": 1, "name": "{{name}}", @@ -1468,7 +1850,8 @@ void StageHooking(string name, string packageKind = "plugin") "kind": "{{packageKind}}", "dependencies": [ { "name": "hosihikari" } ] } - """); + """ + ); } // 拒绝与故障的检验包:同样放在 plugins/ 外面,由测试逐个交付(FX-0030)。 @@ -1476,7 +1859,9 @@ void StageGuarded(string name) { var package = Path.Combine(stage, "parented", name); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), $$""" + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + $$""" { "name": "{{name}}", "entry": "{{name}}.dll", @@ -1484,18 +1869,20 @@ void StageGuarded(string name) "dependencies": [ { "name": "hosihikari" } ], "loader": "guarded" } - """); + """ + ); } // 造一份只改一两处的清单,别把整份 JSON 复制到测试里。 -string ManifestLike(string name, string entry) => $$""" - { - "name": "{{name}}", - "entry": "{{entry}}", - "schemaVersion": 1, "kind": "plugin", "apiVersion": 3, - "dependencies": [ { "name": "hosihikari" } ] - } - """; +string ManifestLike(string name, string entry) => + $$""" + { + "name": "{{name}}", + "entry": "{{entry}}", + "schemaVersion": 1, "kind": "plugin", "apiVersion": 3, + "dependencies": [ { "name": "hosihikari" } ] + } + """; string WriteManifest(string name, string json) { @@ -1514,7 +1901,8 @@ string WriteManifest(string name, string json) source, WriteManifest("envelope-" + Guid.NewGuid().ToString("N"), manifestJson), Path.Combine(stage, "envelope-out-" + Guid.NewGuid().ToString("N")), - sharedLayer); + sharedLayer + ); var envelope = packed.PackageDirectory is null ? null : Path.Combine(packed.PackageDirectory, "manifest.json"); @@ -1526,7 +1914,9 @@ void StageThrowing() { var package = Path.Combine(pluginsRoot, "Throwing"); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), """ + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + """ { "name": "Throwing", "entry": "Throwing.dll", @@ -1534,7 +1924,8 @@ void StageThrowing() "dependencies": [ { "name": "hosihikari" } ], "loader": "throwing" } - """); + """ + ); } // 清单 type 写错的那个包:别的都对,只有 type 是父级那边的另一个值。 @@ -1542,14 +1933,17 @@ void StageWrongType() { var package = Path.Combine(pluginsRoot, "WrongType"); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), """ + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + """ { "name": "WrongType", "entry": "WrongType.dll", "loader": "assembly", "type": "assembly" } - """); + """ + ); } // schemaVersion 不匹配的包:与 api 一样,拒载发生在载入之前(FX-0012)。 @@ -1557,7 +1951,9 @@ void StageBadFormat() { var package = Path.Combine(pluginsRoot, "BadFormat"); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), """ + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + """ { "name": "BadFormat", "entry": "BadFormat.dll", @@ -1565,7 +1961,8 @@ void StageBadFormat() "schemaVersion": 9, "dependencies": [ { "name": "hosihikari" } ] } - """); + """ + ); } // entry 跑出包外的包:绝对路径与 .. 在清单读取时就被拒(FX-0006)。 @@ -1573,7 +1970,9 @@ void StageEscapingEntry() { var package = Path.Combine(pluginsRoot, "Escaping"); Directory.CreateDirectory(package); - File.WriteAllText(Path.Combine(package, "hosihikari.json"), """ + File.WriteAllText( + Path.Combine(package, "hosihikari.json"), + """ { "name": "Escaping", "entry": "../Outside.dll", @@ -1581,7 +1980,8 @@ void StageEscapingEntry() "dependencies": [ { "name": "hosihikari" } ], "loader": "assembly" } - """); + """ + ); } // 本机夹具:同一符号在包根与 RID 目录各放一份,只有 RID 那份是 42。RID 优先则插件读到 42。 @@ -1594,14 +1994,16 @@ void StageEscapingEntry() } var output = OutputDirectory("NativeProbe"); - var fileName = OperatingSystem.IsWindows() ? "hosihikari_probe.dll" + var fileName = + OperatingSystem.IsWindows() ? "hosihikari_probe.dll" : OperatingSystem.IsMacOS() ? "libhosihikari_probe.dylib" : "libhosihikari_probe.so"; var ridDirectory = Path.Combine( output, "runtimes", System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier, - "native"); + "native" + ); Directory.CreateDirectory(ridDirectory); var source = Path.Combine(repoRoot, "test", "NativeProbe", "native", "probe.c"); var ridCompile = CompileNative(compiler, source, Path.Combine(ridDirectory, fileName), "42"); @@ -1615,7 +2017,8 @@ void StageEscapingEntry() output, Path.Combine(repoRoot, "test", "NativeProbe", "hosihikari.json"), Path.Combine(stage, "parented"), - sharedLayer); + sharedLayer + ); if (!packed.Succeeded || packed.PackageDirectory is null) { return (false, "打包失败:" + string.Join(";", packed.Problems)); @@ -1630,7 +2033,10 @@ void StageEscapingEntry() var value = File.Exists(valueFile) ? File.ReadAllText(valueFile).Trim() : "(没写出来)"; // 卸 NativeProbe 自己:它没有依赖者,测的是「本机库钉死不影响托管侧回收」。 var unload = host.Unload("NativeProbe"); - return (value == "42" && unload.Released, $"value={value} released={unload.Released} {unload.Error}"); + return ( + value == "42" && unload.Released, + $"value={value} released={unload.Released} {unload.Error}" + ); } static string? FindCCompiler() @@ -1662,15 +2068,18 @@ void StageEscapingEntry() return candidate; } } - catch (System.ComponentModel.Win32Exception) - { - } + catch (System.ComponentModel.Win32Exception) { } } return null; } -static (bool Ok, string Error) CompileNative(string compiler, string source, string output, string value) +static (bool Ok, string Error) CompileNative( + string compiler, + string source, + string output, + string value +) { var start = new System.Diagnostics.ProcessStartInfo(compiler) { @@ -1721,8 +2130,13 @@ string OutputDirectory(string name) const string configuration = "Release"; #endif var bin = Path.Combine(repoRoot, "test", name, "bin"); - var assembly = Directory.EnumerateFiles(bin, $"{name}.dll", SearchOption.AllDirectories) - .Where(file => file.Contains($"{Path.DirectorySeparatorChar}{configuration}{Path.DirectorySeparatorChar}")) + var assembly = Directory + .EnumerateFiles(bin, $"{name}.dll", SearchOption.AllDirectories) + .Where(file => + file.Contains( + $"{Path.DirectorySeparatorChar}{configuration}{Path.DirectorySeparatorChar}" + ) + ) .OrderByDescending(File.GetLastWriteTimeUtc) .First(); return Path.GetDirectoryName(assembly)!; @@ -1731,8 +2145,10 @@ string OutputDirectory(string name) static string RepoRoot() { var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null && - !File.Exists(Path.Combine(directory.FullName, "src", "Hosihikari.PluginManager.csproj"))) + while ( + directory is not null + && !File.Exists(Path.Combine(directory.FullName, "src", "Hosihikari.PluginManager.csproj")) + ) { directory = directory.Parent; } @@ -1740,16 +2156,18 @@ static string RepoRoot() return directory?.FullName ?? throw new InvalidOperationException("找不到仓库根"); } -sealed class CapturingLoggerProvider(System.Collections.Concurrent.ConcurrentQueue lines) : ILoggerProvider{ +sealed class CapturingLoggerProvider(System.Collections.Concurrent.ConcurrentQueue lines) + : ILoggerProvider +{ public ILogger CreateLogger(string categoryName) => new Logger(lines); - public void Dispose() - { - } + public void Dispose() { } - private sealed class Logger(System.Collections.Concurrent.ConcurrentQueue lines) : ILogger + private sealed class Logger(System.Collections.Concurrent.ConcurrentQueue lines) + : ILogger { - public IDisposable? BeginScope(TState state) where TState : notnull => null; + public IDisposable? BeginScope(TState state) + where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; @@ -1758,7 +2176,8 @@ public void Log( EventId eventId, TState state, Exception? exception, - Func formatter) => lines.Enqueue(formatter(state, exception)); + Func formatter + ) => lines.Enqueue(formatter(state, exception)); } } @@ -1768,7 +2187,10 @@ public void Log( /// sealed class SingleThreadContext : SynchronizationContext { - private readonly System.Collections.Concurrent.BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = []; + private readonly System.Collections.Concurrent.BlockingCollection<( + SendOrPostCallback Callback, + object? State + )> _queue = []; public override void Post(SendOrPostCallback d, object? state) => _queue.Add((d, state)); diff --git a/host/RegressionChecks.cs b/host/RegressionChecks.cs index 270bf34..dd24f60 100644 --- a/host/RegressionChecks.cs +++ b/host/RegressionChecks.cs @@ -17,7 +17,17 @@ internal static class RegressionChecks { internal static IEnumerable<(string Name, bool Passed, string Detail)> Run(string root) { - foreach (var mode in new[] { "load", "enable", "null", "loader-throw", "cleanup-throw", "fault-on-load" }) + foreach ( + var mode in new[] + { + "load", + "enable", + "null", + "loader-throw", + "cleanup-throw", + "fault-on-load", + } + ) { var directory = Path.Combine(root, mode); var host = NewHost(directory); @@ -29,15 +39,23 @@ internal static class RegressionChecks var context = regressionLoader.Context!; var scope = (PluginScope)context.Events; var expectedHooks = mode is "load" or "enable" or "cleanup-throw" or "fault-on-load"; - var hooksCleaned = regressionLoader.Unloads == (expectedHooks ? 1 : 0) - && regressionLoader.Disables == (mode == "enable" ? 1 : 0); - var clean = !loaded && host.LoadedNames.Count == 0 && regressionLoader.Events == 0 - && context.PluginServices.Get() is null && hooksCleaned - && regressionLoader.Releases == (expectedHooks ? 1 : 0) - && RejectsReleasedScope(scope); - yield return ($"R1 加载回滚 ({mode})", clean, + var hooksCleaned = + regressionLoader.Unloads == (expectedHooks ? 1 : 0) + && regressionLoader.Disables == (mode == "enable" ? 1 : 0); + var clean = + !loaded + && host.LoadedNames.Count == 0 + && regressionLoader.Events == 0 + && context.PluginServices.Get() is null + && hooksCleaned + && regressionLoader.Releases == (expectedHooks ? 1 : 0) + && RejectsReleasedScope(scope); + yield return ( + $"R1 加载回滚 ({mode})", + clean, $"events={regressionLoader.Events} unload={regressionLoader.Unloads} " - + $"disable={regressionLoader.Disables} release={regressionLoader.Releases}"); + + $"disable={regressionLoader.Disables} release={regressionLoader.Releases}" + ); bool LoadAll() { @@ -54,8 +72,11 @@ bool LoadAll() Stage(dependencyRoot, "Transitive", "Dependent"); Stage(dependencyRoot, "Independent"); dependencyHost.LoadAll(); - yield return ("R2 失败依赖跳过下游,独立分支继续", dependencyHost.LoadedNames.SequenceEqual(["Independent"]), - string.Join(",", dependencyHost.LoadedNames)); + yield return ( + "R2 失败依赖跳过下游,独立分支继续", + dependencyHost.LoadedNames.SequenceEqual(["Independent"]), + string.Join(",", dependencyHost.LoadedNames) + ); var configRoot = Path.Combine(root, "configuration"); var configHost = NewHost(configRoot); @@ -64,49 +85,87 @@ bool LoadAll() File.WriteAllText(Path.Combine(badConfig, "BadConfig.conf"), "foo = {"); Stage(configRoot, "GoodConfig"); var isolated = true; - try { configHost.LoadAll(); } - catch { isolated = false; } - yield return ("R3 坏配置只拒绝一个包", isolated && configHost.LoadedNames.SequenceEqual(["GoodConfig"]), - string.Join(",", configHost.LoadedNames)); + try + { + configHost.LoadAll(); + } + catch + { + isolated = false; + } + yield return ( + "R3 坏配置只拒绝一个包", + isolated && configHost.LoadedNames.SequenceEqual(["GoodConfig"]), + string.Join(",", configHost.LoadedNames) + ); var bus = new EventBus(NullLogger.Instance); var weak = SubscribeCollectibleEvent(bus); Collect(); - yield return ("R4 最后一次退订释放事件类型", !weak.IsAlive, $"assembly alive={weak.IsAlive}"); + yield return ( + "R4 最后一次退订释放事件类型", + !weak.IsAlive, + $"assembly alive={weak.IsAlive}" + ); GC.KeepAlive(bus); var scheduler = new CountingScheduler(); - var scopeForGrowth = new PluginScope(new EventBus(NullLogger.Instance), scheduler, new PluginServiceRegistry()); + var scopeForGrowth = new PluginScope( + new EventBus(NullLogger.Instance), + scheduler, + new PluginServiceRegistry() + ); DisposeTasks(scopeForGrowth); Collect(); var retained = scheduler.References.Count(reference => reference.IsAlive); - yield return ("R5 已释放句柄不累积", retained == 0 && scheduler.Disposed == 1000, - $"retained={retained} disposed={scheduler.Disposed}"); + yield return ( + "R5 已释放句柄不累积", + retained == 0 && scheduler.Disposed == 1000, + $"retained={retained} disposed={scheduler.Disposed}" + ); GC.KeepAlive(scopeForGrowth); var concurrentScheduler = new CountingScheduler(); var registry = new PluginServiceRegistry(); - var concurrentScope = new PluginScope(new EventBus(NullLogger.Instance), concurrentScheduler, registry); - Parallel.For(0, 2000, i => - { - try + var concurrentScope = new PluginScope( + new EventBus(NullLogger.Instance), + concurrentScheduler, + registry + ); + Parallel.For( + 0, + 2000, + i => { - var handle = concurrentScope.ScheduleOnce(TimeSpan.FromHours(1), () => { }); - if (i % 2 == 0) handle.Dispose(); - if (i % 7 == 0) concurrentScope.Register(new Marker()); - if (i == 100) concurrentScope.ReleaseAll(); - handle.Dispose(); + try + { + var handle = concurrentScope.ScheduleOnce(TimeSpan.FromHours(1), () => { }); + if (i % 2 == 0) + handle.Dispose(); + if (i % 7 == 0) + concurrentScope.Register(new Marker()); + if (i == 100) + concurrentScope.ReleaseAll(); + handle.Dispose(); + } + catch (ObjectDisposedException) { } } - catch (ObjectDisposedException) { } - }); + ); concurrentScope.ReleaseAll(); - yield return ("R6 并发释放与登记不遗留资源", concurrentScheduler.Created == concurrentScheduler.Disposed - && concurrentScheduler.DuplicateDisposes == 0 && registry.Get() is null - && RejectsReleasedScope(concurrentScope), - $"created={concurrentScheduler.Created} disposed={concurrentScheduler.Disposed} duplicates={concurrentScheduler.DuplicateDisposes}"); + yield return ( + "R6 并发释放与登记不遗留资源", + concurrentScheduler.Created == concurrentScheduler.Disposed + && concurrentScheduler.DuplicateDisposes == 0 + && registry.Get() is null + && RejectsReleasedScope(concurrentScope), + $"created={concurrentScheduler.Created} disposed={concurrentScheduler.Disposed} duplicates={concurrentScheduler.DuplicateDisposes}" + ); - yield return ("R7 打包同时消费大量 stdout/stderr", PackOutput(Path.Combine(root, "pack")), - "受控 publish 进程各输出 2MiB,10 秒内应退出"); + yield return ( + "R7 打包同时消费大量 stdout/stderr", + PackOutput(Path.Combine(root, "pack")), + "受控 publish 进程各输出 2MiB,10 秒内应退出" + ); var manifestRoot = Path.Combine(root, "manifest"); var manifestHost = NewHost(manifestRoot); @@ -114,75 +173,116 @@ bool LoadAll() Stage(manifestRoot, "Good"); Stage(manifestRoot, "SelfDependency", "SelfDependency"); Stage(manifestRoot, "NullDependencies"); - StageManifest(manifestRoot, "NullDependencies", """ + StageManifest( + manifestRoot, + "NullDependencies", + """ { "name": "NullDependencies", "entry": "main", "schemaVersion": 1, "kind": "plugin", "apiVersion": 3, "dependencies": null, "loader": "regression" } - """); - StageManifest(manifestRoot, "NullExtra", """ + """ + ); + StageManifest( + manifestRoot, + "NullExtra", + """ { "name": "NullExtra", "entry": "main", "schemaVersion": 1, "kind": "plugin", "apiVersion": 3, "carrier": null, "loader": "regression" } - """); - StageManifest(manifestRoot, "NullDependencyEntry", """ + """ + ); + StageManifest( + manifestRoot, + "NullDependencyEntry", + """ { "name": "NullDependencyEntry", "entry": "main", "schemaVersion": 1, "kind": "plugin", "apiVersion": 3, "dependencies": [null], "loader": "regression" } - """); + """ + ); var manifestThrew = false; - try { manifestHost.LoadAll(); } - catch { manifestThrew = true; } + try + { + manifestHost.LoadAll(); + } + catch + { + manifestThrew = true; + } var manifestLoaded = manifestHost.LoadedNames; - yield return ("R8 清单 null 字段不中断整轮", + yield return ( + "R8 清单 null 字段不中断整轮", !manifestThrew - && manifestLoaded.Contains("Good") - && !manifestLoaded.Contains("SelfDependency") - && !manifestLoaded.Contains("NullExtra") - && !manifestLoaded.Contains("NullDependencyEntry"), - string.Join(",", manifestLoaded)); + && manifestLoaded.Contains("Good") + && !manifestLoaded.Contains("SelfDependency") + && !manifestLoaded.Contains("NullExtra") + && !manifestLoaded.Contains("NullDependencyEntry"), + string.Join(",", manifestLoaded) + ); var legacyRoot = Path.Combine(root, "legacy-keys"); - var legacyPackage = StageManifest(legacyRoot, "Legacy", """ + var legacyPackage = StageManifest( + legacyRoot, + "Legacy", + """ { "name": "Legacy", "entry": "main", "type": "hosihikari", "dependencies": [ { "name": "hosihikari" } ], "extraInfo": { "api": "2", "manifest_version": "1" } } - """); + """ + ); var legacyReports = new List(); var legacyRead = ManifestReader.Read(legacyPackage, legacyReports.Add); var legacySource = Path.Combine(legacyRoot, "source"); Directory.CreateDirectory(legacySource); var legacyManifestPath = Path.Combine(legacyRoot, "Legacy.json"); - File.WriteAllText(legacyManifestPath, File.ReadAllText(Path.Combine(legacyPackage, "hosihikari.json"))); - var legacyPack = Packager.Pack(legacySource, legacyManifestPath, Path.Combine(legacyRoot, "out"), []); - yield return ("R20 旧清单键给出迁移错误", + File.WriteAllText( + legacyManifestPath, + File.ReadAllText(Path.Combine(legacyPackage, "hosihikari.json")) + ); + var legacyPack = Packager.Pack( + legacySource, + legacyManifestPath, + Path.Combine(legacyRoot, "out"), + [] + ); + yield return ( + "R20 旧清单键给出迁移错误", legacyRead is null - && legacyReports.Any(message => message.Contains("已改名为 extraInfo.api_version", StringComparison.Ordinal)) - && !legacyPack.Succeeded - && legacyPack.Problems.Any(problem => problem.Contains("已改名为 extraInfo.api_version", StringComparison.Ordinal)), - legacyReports.FirstOrDefault() ?? string.Join(" | ", legacyPack.Problems)); + && legacyReports.Any(message => + message.Contains("已改名为 extraInfo.api_version", StringComparison.Ordinal) + ) + && !legacyPack.Succeeded + && legacyPack.Problems.Any(problem => + problem.Contains("已改名为 extraInfo.api_version", StringComparison.Ordinal) + ), + legacyReports.FirstOrDefault() ?? string.Join(" | ", legacyPack.Problems) + ); // R24:migrate 把旧包搬成新清单:字段改名、删旧文件、打包设置搬进 pack(FX-0058)。 var migrateRoot = Path.Combine(root, "migrate"); var migratePackage = Path.Combine(migrateRoot, "Old"); Directory.CreateDirectory(migratePackage); - File.WriteAllText(Path.Combine(migratePackage, "manifest.json"), """ + File.WriteAllText( + Path.Combine(migratePackage, "manifest.json"), + """ { "name": "Old", "entry": "Old.dll", "type": "hosihikari", "version": "1.2.3", "dependencies": [ { "name": "hosihikari" } ], "extraInfo": { "api_version": "2", "manifest_version": "1", "loader": "assembly", "packages": "A/1.0.0, B" } } - """); + """ + ); var migrated = Packager.Migrate(migratePackage); var migratedJson = Path.Combine(migratePackage, "hosihikari.json"); using var migratedDocument = migrated.Succeeded @@ -190,72 +290,112 @@ legacyRead is null : null; var migratedRoot = migratedDocument?.RootElement; var migratedAgain = Packager.Migrate(migratePackage); - yield return ("R24 migrate 生成新清单并删掉旧文件", + yield return ( + "R24 migrate 生成新清单并删掉旧文件", migrated.Succeeded - && !File.Exists(Path.Combine(migratePackage, "manifest.json")) - && migratedRoot is { } element - && element.GetProperty("kind").GetString() == "plugin" - && element.GetProperty("apiVersion").GetInt32() == 3 - && element.GetProperty("schemaVersion").GetInt32() == 1 - // 旧文件马上就删,打包设置必须已经搬进 pack;1.x 的逗号写法要拆成两项。 - && element.GetProperty("pack").GetProperty("packages")[0].GetString() == "A/1.0.0" - && element.GetProperty("pack").GetProperty("packages")[1].GetString() == "B" - && migrated.Notes.Count == 0 - && !migratedAgain.Succeeded, + && !File.Exists(Path.Combine(migratePackage, "manifest.json")) + && migratedRoot is { } element + && element.GetProperty("kind").GetString() == "plugin" + && element.GetProperty("apiVersion").GetInt32() == 3 + && element.GetProperty("schemaVersion").GetInt32() == 1 + // 旧文件马上就删,打包设置必须已经搬进 pack;1.x 的逗号写法要拆成两项。 + && element.GetProperty("pack").GetProperty("packages")[0].GetString() == "A/1.0.0" + && element.GetProperty("pack").GetProperty("packages")[1].GetString() == "B" + && migrated.Notes.Count == 0 + && !migratedAgain.Succeeded, migrated.Succeeded ? string.Join(" | ", migrated.Notes) - : string.Join(" | ", migrated.Problems)); + : string.Join(" | ", migrated.Problems) + ); // R21 起是 FX-0006 / 0013 / 0042 的规则:每条都同时看读取期与打包期。 var ruleRoot = Path.Combine(root, "manifest-rules"); var ruleSource = Path.Combine(ruleRoot, "source"); Directory.CreateDirectory(ruleSource); File.WriteAllText(Path.Combine(ruleSource, "main"), "entry placeholder"); - string RuleManifest(string name, string extra, string dependencies = """[ { "name": "hosihikari" } ]""") + string RuleManifest( + string name, + string extra, + string dependencies = """[ { "name": "hosihikari" } ]""" + ) { var path = Path.Combine(ruleRoot, name + ".json"); - File.WriteAllText(path, $$""" + File.WriteAllText( + path, + $$""" { "schemaVersion": 1, "name": "{{name}}", "entry": "main", "kind": "plugin", "apiVersion": 3, "version": "1.0.0", "dependencies": {{dependencies}}, {{extra}} } - """); + """ + ); return path; } var missingDependency = RuleManifest("NoFramework", """ "loader": "regression" """, "[]"); var missingDependencyReports = new List(); var missingDependencyRead = ManifestReader.Read( - StageManifest(ruleRoot, "NoFramework", File.ReadAllText(missingDependency)), missingDependencyReports.Add); - var missingDependencyPack = Packager.Pack(ruleSource, missingDependency, Path.Combine(ruleRoot, "out-no-framework"), []); - yield return ("R21 缺少 hosihikari 依赖时读取期与打包期都拒绝", + StageManifest(ruleRoot, "NoFramework", File.ReadAllText(missingDependency)), + missingDependencyReports.Add + ); + var missingDependencyPack = Packager.Pack( + ruleSource, + missingDependency, + Path.Combine(ruleRoot, "out-no-framework"), + [] + ); + yield return ( + "R21 缺少 hosihikari 依赖时读取期与打包期都拒绝", missingDependencyRead is null - && missingDependencyReports.Any(message => message.Contains("hosihikari", StringComparison.Ordinal)) - && !missingDependencyPack.Succeeded - && missingDependencyPack.Problems.Any(problem => problem.Contains("hosihikari", StringComparison.Ordinal)), - string.Join(" | ", missingDependencyReports.Concat(missingDependencyPack.Problems))); + && missingDependencyReports.Any(message => + message.Contains("hosihikari", StringComparison.Ordinal) + ) + && !missingDependencyPack.Succeeded + && missingDependencyPack.Problems.Any(problem => + problem.Contains("hosihikari", StringComparison.Ordinal) + ), + string.Join(" | ", missingDependencyReports.Concat(missingDependencyPack.Problems)) + ); var carrierKind = RuleManifest( PluginContractInfo.ParentName, """ "loader": "regression", "kind": "carrier" """, - "[]"); + "[]" + ); var unknownKind = RuleManifest( "UnknownKind", - """ "loader": "regression", "kind": "pluginish" """); - var carrierPack = Packager.Pack(ruleSource, carrierKind, Path.Combine(ruleRoot, "out-carrier"), []); - var unknownPack = Packager.Pack(ruleSource, unknownKind, Path.Combine(ruleRoot, "out-unknown"), []); - yield return ("R22 kind 只认三个值,carrier 只给 hosihikari", + """ "loader": "regression", "kind": "pluginish" """ + ); + var carrierPack = Packager.Pack( + ruleSource, + carrierKind, + Path.Combine(ruleRoot, "out-carrier"), + [] + ); + var unknownPack = Packager.Pack( + ruleSource, + unknownKind, + Path.Combine(ruleRoot, "out-unknown"), + [] + ); + yield return ( + "R22 kind 只认三个值,carrier 只给 hosihikari", carrierPack.Succeeded - && !unknownPack.Succeeded - && unknownPack.Problems.Any(problem => problem.Contains("packageKind", StringComparison.Ordinal)), - string.Join(" | ", carrierPack.Problems.Concat(unknownPack.Problems))); + && !unknownPack.Succeeded + && unknownPack.Problems.Any(problem => + problem.Contains("packageKind", StringComparison.Ordinal) + ), + string.Join(" | ", carrierPack.Problems.Concat(unknownPack.Problems)) + ); var prepackSource = Path.Combine(ruleRoot, "prepack-source"); Directory.CreateDirectory(prepackSource); var prepackGood = Path.Combine(ruleRoot, "prepack-good.json"); - File.WriteAllText(prepackGood, $$""" + File.WriteAllText( + prepackGood, + $$""" { "schemaVersion": 1, "name": "Prepack", "entry": "main", "kind": "plugin", "apiVersion": 3, "version": "1.0.0", @@ -263,9 +403,12 @@ missingDependencyRead is null "loader": "regression", "pack": { "prepack": "{{(OperatingSystem.IsWindows() ? "cmd" : "sh")}}" } } - """); + """ + ); var prepackBad = Path.Combine(ruleRoot, "prepack-bad.json"); - File.WriteAllText(prepackBad, $$""" + File.WriteAllText( + prepackBad, + $$""" { "schemaVersion": 1, "name": "PrepackBad", "entry": "main", "kind": "plugin", "apiVersion": 3, "version": "1.0.0", @@ -273,14 +416,29 @@ missingDependencyRead is null "loader": "regression", "pack": { "prepack": "hosihikari-no-such-program" } } - """); - var prepackGoodPack = Packager.Pack(prepackSource, prepackGood, Path.Combine(ruleRoot, "out-prepack"), []); - var prepackBadPack = Packager.Pack(prepackSource, prepackBad, Path.Combine(ruleRoot, "out-prepack-bad"), []); - yield return ("R23 prepack 在打包期执行,失败拒包", + """ + ); + var prepackGoodPack = Packager.Pack( + prepackSource, + prepackGood, + Path.Combine(ruleRoot, "out-prepack"), + [] + ); + var prepackBadPack = Packager.Pack( + prepackSource, + prepackBad, + Path.Combine(ruleRoot, "out-prepack-bad"), + [] + ); + yield return ( + "R23 prepack 在打包期执行,失败拒包", prepackGoodPack.Succeeded - && !prepackBadPack.Succeeded - && prepackBadPack.Problems.Any(problem => problem.Contains("prepack", StringComparison.Ordinal)), - string.Join(" | ", prepackGoodPack.Problems.Concat(prepackBadPack.Problems))); + && !prepackBadPack.Succeeded + && prepackBadPack.Problems.Any(problem => + problem.Contains("prepack", StringComparison.Ordinal) + ), + string.Join(" | ", prepackGoodPack.Problems.Concat(prepackBadPack.Problems)) + ); var lockRoot = Path.Combine(root, "load-lock"); var parentLock = new object(); @@ -292,8 +450,14 @@ missingDependencyRead is null SecondRelease = secondRelease, }; var lockHost = new PluginManager( - Path.Combine(lockRoot, "plugins"), Path.Combine(lockRoot, "data"), Path.Combine(lockRoot, "config"), - _ => { lock (parentLock) { } }); + Path.Combine(lockRoot, "plugins"), + Path.Combine(lockRoot, "data"), + Path.Combine(lockRoot, "config"), + _ => + { + lock (parentLock) { } + } + ); lockHost.RegisterLoader(lockLoader); Stage(lockRoot, "Probe"); Stage(lockRoot, "Second", "Probe"); @@ -302,9 +466,18 @@ missingDependencyRead is null Exception? loadError = null; var loader = new Thread(() => { - try { lockHost.LoadAll(); } - catch (Exception ex) { loadError = ex; } - finally { loadDone.Set(); } + try + { + lockHost.LoadAll(); + } + catch (Exception ex) + { + loadError = ex; + } + finally + { + loadDone.Set(); + } }); var unloader = new Thread(() => { @@ -318,26 +491,36 @@ missingDependencyRead is null }); loader.Start(); unloader.Start(); - var bothDone = loadDone.Wait(TimeSpan.FromSeconds(5)) && unloadDone.Wait(TimeSpan.FromSeconds(5)); - yield return ("R9 加载路径不在锁内回调父级", bothDone && secondStarted.IsSet && loadError is null, - $"loaded={string.Join(",", lockHost.LoadedNames)} error={loadError?.Message}"); + var bothDone = + loadDone.Wait(TimeSpan.FromSeconds(5)) && unloadDone.Wait(TimeSpan.FromSeconds(5)); + yield return ( + "R9 加载路径不在锁内回调父级", + bothDone && secondStarted.IsSet && loadError is null, + $"loaded={string.Join(",", lockHost.LoadedNames)} error={loadError?.Message}" + ); var rollbackRoot = Path.Combine(root, "loader-rollback"); var rollbackHost = NewHost(rollbackRoot); rollbackHost.RegisterLoader(new FailingLoader("loader-register-throw")); var brokenPackage = Stage(rollbackRoot, "Broken"); - var ghostPackage = StageManifest(rollbackRoot, "GhostUser", """ + var ghostPackage = StageManifest( + rollbackRoot, + "GhostUser", + """ { "schemaVersion": 1, "name": "GhostUser", "entry": "main", "apiVersion": 3, "loader": "ghost", "kind": "plugin", "dependencies": [ { "name": "hosihikari" } ] } - """); + """ + ); var brokenLoaded = rollbackHost.Load(brokenPackage); var ghostLoaded = rollbackHost.Load(ghostPackage); - yield return ("R10 失败装载撤销 Loader 登记", + yield return ( + "R10 失败装载撤销 Loader 登记", !brokenLoaded && !ghostLoaded && rollbackHost.LoadedNames.Count == 0, - $"broken={brokenLoaded} ghost={ghostLoaded} loaded={string.Join(",", rollbackHost.LoadedNames)}"); + $"broken={brokenLoaded} ghost={ghostLoaded} loaded={string.Join(",", rollbackHost.LoadedNames)}" + ); var loaderRoot = Path.Combine(root, "loader-unload"); var loaderHost = NewHost(loaderRoot); @@ -345,9 +528,13 @@ missingDependencyRead is null var loaderPackage = Stage(loaderRoot, "LoaderPackage", kind: "loader"); var loaderLoaded = loaderHost.Load(loaderPackage); var loaderUnload = loaderHost.Unload("LoaderPackage"); - yield return ("R11 显式卸载 Loader 包被拒绝", - loaderLoaded && !loaderUnload.Released && loaderHost.LoadedNames.Contains("LoaderPackage"), - loaderUnload.Error ?? "卸载竟然成功"); + yield return ( + "R11 显式卸载 Loader 包被拒绝", + loaderLoaded + && !loaderUnload.Released + && loaderHost.LoadedNames.Contains("LoaderPackage"), + loaderUnload.Error ?? "卸载竟然成功" + ); if (!OperatingSystem.IsWindows()) { @@ -358,11 +545,19 @@ missingDependencyRead is null var lockedPackage = Stage(aclRoot, "Locked"); File.SetUnixFileMode(Path.Combine(lockedPackage, "hosihikari.json"), UnixFileMode.None); var aclIsolated = true; - try { aclHost.LoadAll(); } - catch { aclIsolated = false; } - yield return ("R12 读不了的清单只跳过该包", + try + { + aclHost.LoadAll(); + } + catch + { + aclIsolated = false; + } + yield return ( + "R12 读不了的清单只跳过该包", aclIsolated && aclHost.LoadedNames.SequenceEqual(["Good"]), - string.Join(",", aclHost.LoadedNames)); + string.Join(",", aclHost.LoadedNames) + ); } var reuseRoot = Path.Combine(root, "loader-reuse-log"); @@ -375,9 +570,12 @@ missingDependencyRead is null lock (reuseLock) { } }); var reuseHost = new PluginManager( - Path.Combine(reuseRoot, "plugins"), Path.Combine(reuseRoot, "data"), Path.Combine(reuseRoot, "config"), + Path.Combine(reuseRoot, "plugins"), + Path.Combine(reuseRoot, "data"), + Path.Combine(reuseRoot, "config"), message => Console.WriteLine($"[回归] {message}"), - new SingleService(reuseLogger)); + new SingleService(reuseLogger) + ); reuseHost.RegisterLoader(new FailingLoader("none") { RegisterLoader = true }); var reusePackage = Stage(reuseRoot, "LoaderPackage", kind: "loader"); var firstLoad = reuseHost.Load(reusePackage); @@ -393,10 +591,15 @@ missingDependencyRead is null }); reuseParentHeld.Wait(TimeSpan.FromSeconds(2)); var reuseLoad = Task.Run(() => reuseHost.Load(reusePackage)); - var completed = reuseLoad.Wait(TimeSpan.FromSeconds(5)) && unloadThread.Wait(TimeSpan.FromSeconds(5)); - yield return ("R13 Loader 复用日志不在核心锁内", + var completed = + reuseLoad.Wait(TimeSpan.FromSeconds(5)) && unloadThread.Wait(TimeSpan.FromSeconds(5)); + yield return ( + "R13 Loader 复用日志不在核心锁内", firstLoad && completed && reuseLoad.Result && reuseUnload is { Released: false }, - completed ? $"reload={reuseLoad.Result} unload={reuseUnload?.Error}" : "超时:日志回调与卸载互相等"); + completed + ? $"reload={reuseLoad.Result} unload={reuseUnload?.Error}" + : "超时:日志回调与卸载互相等" + ); var versionRoot = Path.Combine(root, "dependency-versions"); var versionHost = NewHost(versionRoot); @@ -416,11 +619,24 @@ missingDependencyRead is null StageVersioned(versionRoot, "NeedsUntyped", "1.0.0", ("UntypedLib", "[1.0.0,3.0.0)")); StageVersioned(versionRoot, "BadVersion", "not-semver"); versionHost.LoadAll(); - var versionLoaded = versionHost.LoadedNames.OrderBy(name => name, StringComparer.Ordinal).ToArray(); - yield return ("R14 依赖版本约束过滤", - versionLoaded.SequenceEqual( - ["Any", "Exact", "Lib", "Lib1", "Lib12", "MajorWildcard", "MinorWildcard", "Range", "UntypedLib"]), - string.Join(",", versionLoaded)); + var versionLoaded = versionHost + .LoadedNames.OrderBy(name => name, StringComparer.Ordinal) + .ToArray(); + yield return ( + "R14 依赖版本约束过滤", + versionLoaded.SequenceEqual([ + "Any", + "Exact", + "Lib", + "Lib1", + "Lib12", + "MajorWildcard", + "MinorWildcard", + "Range", + "UntypedLib", + ]), + string.Join(",", versionLoaded) + ); var parentVersionRoot = Path.Combine(root, "dependency-versions-parent"); var parentVersionHost = NewHost(parentVersionRoot); @@ -431,48 +647,92 @@ missingDependencyRead is null var needs2Star = StageVersioned(parentVersionRoot, "Needs2Star", "1.0.0", ("Lib", "2.*")); var needs1Star = StageVersioned(parentVersionRoot, "Needs1Star", "1.0.0", ("Lib", "1.*")); var bare = StageVersioned(parentVersionRoot, "Bare", "1.0.0", ("Lib", null)); - var parentLoaded = parentVersionHost.Load(versionLib) - && parentVersionHost.Load(needs2) - && !parentVersionHost.Load(needs3) - && parentVersionHost.Load(needs2Star) - && !parentVersionHost.Load(needs1Star) - && parentVersionHost.Load(bare); - yield return ("R15 父级交付也检查依赖版本", - parentLoaded && parentVersionHost.LoadedNames.OrderBy(name => name, StringComparer.Ordinal) - .SequenceEqual(["Bare", "Lib", "Needs2", "Needs2Star"]), - string.Join(",", parentVersionHost.LoadedNames)); + var parentLoaded = + parentVersionHost.Load(versionLib) + && parentVersionHost.Load(needs2) + && !parentVersionHost.Load(needs3) + && parentVersionHost.Load(needs2Star) + && !parentVersionHost.Load(needs1Star) + && parentVersionHost.Load(bare); + yield return ( + "R15 父级交付也检查依赖版本", + parentLoaded + && parentVersionHost + .LoadedNames.OrderBy(name => name, StringComparer.Ordinal) + .SequenceEqual(["Bare", "Lib", "Needs2", "Needs2Star"]), + string.Join(",", parentVersionHost.LoadedNames) + ); var packVersionRoot = Path.Combine(root, "pack-version"); var packVersionSource = Path.Combine(packVersionRoot, "source"); Directory.CreateDirectory(packVersionSource); var badVersionManifest = Path.Combine(packVersionRoot, "bad-version.json"); - File.WriteAllText(badVersionManifest, JsonSerializer.Serialize(new - { - schemaVersion = 1, name = "BadVersion", entry = "main.dll", kind = "plugin", - apiVersion = int.Parse(PluginContractInfo.CurrentApiVersion), version = "not-semver", - dependencies = new object[] { new { name = "hosihikari" } }, - loader = "assembly", - })); + File.WriteAllText( + badVersionManifest, + JsonSerializer.Serialize( + new + { + schemaVersion = 1, + name = "BadVersion", + entry = "main.dll", + kind = "plugin", + apiVersion = int.Parse(PluginContractInfo.CurrentApiVersion), + version = "not-semver", + dependencies = new object[] { new { name = "hosihikari" } }, + loader = "assembly", + } + ) + ); var badConstraintManifest = Path.Combine(packVersionRoot, "bad-constraint.json"); - File.WriteAllText(badConstraintManifest, JsonSerializer.Serialize(new - { - schemaVersion = 1, name = "BadConstraint", entry = "main.dll", kind = "plugin", - apiVersion = int.Parse(PluginContractInfo.CurrentApiVersion), version = "1.0.0", - dependencies = new object[] { new { name = "Lib", version = ">>1" }, new { name = "hosihikari" } }, - loader = "assembly", - })); + File.WriteAllText( + badConstraintManifest, + JsonSerializer.Serialize( + new + { + schemaVersion = 1, + name = "BadConstraint", + entry = "main.dll", + kind = "plugin", + apiVersion = int.Parse(PluginContractInfo.CurrentApiVersion), + version = "1.0.0", + dependencies = new object[] + { + new { name = "Lib", version = ">>1" }, + new { name = "hosihikari" }, + }, + loader = "assembly", + } + ) + ); var badVersionPack = Packager.Pack( - packVersionSource, badVersionManifest, Path.Combine(packVersionRoot, "out-version"), []); + packVersionSource, + badVersionManifest, + Path.Combine(packVersionRoot, "out-version"), + [] + ); var badConstraintPack = Packager.Pack( - packVersionSource, badConstraintManifest, Path.Combine(packVersionRoot, "out-constraint"), []); - yield return ("R16 打包拒绝非法版本与约束", - !badVersionPack.Succeeded && !badConstraintPack.Succeeded - && badVersionPack.Problems.Any(problem => problem.Contains("SemVer", StringComparison.Ordinal)) - && badConstraintPack.Problems.Any(problem => problem.Contains("SemVer", StringComparison.Ordinal)), - string.Join(" | ", badVersionPack.Problems.Concat(badConstraintPack.Problems))); + packVersionSource, + badConstraintManifest, + Path.Combine(packVersionRoot, "out-constraint"), + [] + ); + yield return ( + "R16 打包拒绝非法版本与约束", + !badVersionPack.Succeeded + && !badConstraintPack.Succeeded + && badVersionPack.Problems.Any(problem => + problem.Contains("SemVer", StringComparison.Ordinal) + ) + && badConstraintPack.Problems.Any(problem => + problem.Contains("SemVer", StringComparison.Ordinal) + ), + string.Join(" | ", badVersionPack.Problems.Concat(badConstraintPack.Problems)) + ); var nullDependencyManifest = Path.Combine(packVersionRoot, "null-dependency.json"); - File.WriteAllText(nullDependencyManifest, """ + File.WriteAllText( + nullDependencyManifest, + """ { "name": "NullDependency", "entry": "main.dll", @@ -483,24 +743,33 @@ missingDependencyRead is null "dependencies": [ null ], "loader": "assembly" } - """); + """ + ); PackResult? nullDependencyPack = null; string? nullDependencyError = null; try { nullDependencyPack = Packager.Pack( - packVersionSource, nullDependencyManifest, Path.Combine(packVersionRoot, "out-null-dep"), []); + packVersionSource, + nullDependencyManifest, + Path.Combine(packVersionRoot, "out-null-dep"), + [] + ); } catch (Exception ex) { nullDependencyError = $"{ex.GetType().Name}: {ex.Message}"; } - yield return ("R18 打包拒绝 null 依赖而不是抛出", + yield return ( + "R18 打包拒绝 null 依赖而不是抛出", nullDependencyError is null - && nullDependencyPack is { Succeeded: false, Problems: { } nullProblems } - && nullProblems.Any(problem => problem.Contains("dependencies", StringComparison.Ordinal)), - nullDependencyError ?? string.Join(" | ", nullDependencyPack?.Problems ?? [])); + && nullDependencyPack is { Succeeded: false, Problems: { } nullProblems } + && nullProblems.Any(problem => + problem.Contains("dependencies", StringComparison.Ordinal) + ), + nullDependencyError ?? string.Join(" | ", nullDependencyPack?.Problems ?? []) + ); var timerProbe = ScheduleOnceRetentionProbe(); yield return ("R19 单次定时任务完成后释放捕获对象", timerProbe.Passed, timerProbe.Detail); @@ -514,7 +783,10 @@ nullDependencyError is null { var directory = Path.Combine(fuzzRoot, "p" + i); Directory.CreateDirectory(directory); - File.WriteAllText(Path.Combine(directory, "hosihikari.json"), RandomManifest(fuzzRandom)); + File.WriteAllText( + Path.Combine(directory, "hosihikari.json"), + RandomManifest(fuzzRandom) + ); try { ManifestReader.Read(directory, _ => { }); @@ -532,7 +804,11 @@ nullDependencyError is null private static (bool Passed, string Detail) ScheduleOnceRetentionProbe() { var logger = NullLogger.Instance; - var scope = new PluginScope(new EventBus(logger), new Scheduler(logger), new PluginServiceRegistry()); + var scope = new PluginScope( + new EventBus(logger), + new Scheduler(logger), + new PluginServiceRegistry() + ); scope.Open(); using var done = new ManualResetEventSlim(); @@ -544,7 +820,9 @@ private static (bool Passed, string Detail) ScheduleOnceRetentionProbe() } var ownedField = typeof(PluginScope).GetField( - "_owned", BindingFlags.NonPublic | BindingFlags.Instance); + "_owned", + BindingFlags.NonPublic | BindingFlags.Instance + ); var deadline = Stopwatch.StartNew(); var ownedCount = -1; while (deadline.Elapsed < TimeSpan.FromSeconds(2)) @@ -565,24 +843,40 @@ private static (bool Passed, string Detail) ScheduleOnceRetentionProbe() return (ownedCount == 0, $"owned={ownedCount}"); } - private static PluginManager NewHost(string root) => new( - Path.Combine(root, "plugins"), Path.Combine(root, "data"), Path.Combine(root, "config"), - message => Console.WriteLine($"[回归] {message}")); + private static PluginManager NewHost(string root) => + new( + Path.Combine(root, "plugins"), + Path.Combine(root, "data"), + Path.Combine(root, "config"), + message => Console.WriteLine($"[回归] {message}") + ); - private static string Stage(string root, string name, string? dependency = null, string kind = "plugin") + private static string Stage( + string root, + string name, + string? dependency = null, + string kind = "plugin" + ) { var directory = Path.Combine(root, "plugins", name); Directory.CreateDirectory(directory); - File.WriteAllText(Path.Combine(directory, "hosihikari.json"), JsonSerializer.Serialize(new - { - schemaVersion = 1, - name, - entry = "main", - apiVersion = 3, - loader = "regression", - kind, - dependencies = dependency is null ? new object[] { new { name = "hosihikari" } } : new object[] { new { name = dependency }, new { name = "hosihikari" } }, - })); + File.WriteAllText( + Path.Combine(directory, "hosihikari.json"), + JsonSerializer.Serialize( + new + { + schemaVersion = 1, + name, + entry = "main", + apiVersion = 3, + loader = "regression", + kind, + dependencies = dependency is null + ? new object[] { new { name = "hosihikari" } } + : new object[] { new { name = dependency }, new { name = "hosihikari" } }, + } + ) + ); return directory; } @@ -598,9 +892,30 @@ private static string RandomManifest(Random random) { string[] fragments = [ - "{", "}", "[", "]", "\"name\"", ":", "\"p\"", "\"entry\"", "\"..\"", "\"main.dll\"", - "\"type\"", "\"hosihikari\"", "\"version\"", "\"1.0.0\"", "\"dependencies\"", - "null", "0", ",", "\\", "\n", "\"kind\"", "\"apiVersion\"", "3", "\"carrier\"", + "{", + "}", + "[", + "]", + "\"name\"", + ":", + "\"p\"", + "\"entry\"", + "\"..\"", + "\"main.dll\"", + "\"type\"", + "\"hosihikari\"", + "\"version\"", + "\"1.0.0\"", + "\"dependencies\"", + "null", + "0", + ",", + "\\", + "\n", + "\"kind\"", + "\"apiVersion\"", + "3", + "\"carrier\"", ]; var builder = new StringBuilder(); for (var i = 0; i < random.Next(1, 50); i++) @@ -615,45 +930,74 @@ private static string StageVersioned( string root, string name, string? version, - params (string Name, string? Version)[] dependencies) => - StageManifest(root, name, JsonSerializer.Serialize(new - { + params (string Name, string? Version)[] dependencies + ) => + StageManifest( + root, name, - entry = "main", - type = "hosihikari", - version, - schemaVersion = 1, kind = "plugin", - apiVersion = int.Parse(PluginContractInfo.CurrentApiVersion), - dependencies = dependencies.Select(dependency => new { dependency.Name, dependency.Version }) - .Cast() - .Append(new { Name = "hosihikari", Version = (string?)null }) - .ToArray(), - loader = "regression", - })); + JsonSerializer.Serialize( + new + { + name, + entry = "main", + type = "hosihikari", + version, + schemaVersion = 1, + kind = "plugin", + apiVersion = int.Parse(PluginContractInfo.CurrentApiVersion), + dependencies = dependencies + .Select(dependency => new { dependency.Name, dependency.Version }) + .Cast() + .Append(new { Name = "hosihikari", Version = (string?)null }) + .ToArray(), + loader = "regression", + } + ) + ); private static bool RejectsReleasedScope(PluginScope scope) { - Action[] actions = [() => scope.Subscribe(_ => { }), + Action[] actions = + [ + () => scope.Subscribe(_ => { }), () => scope.ScheduleOnce(TimeSpan.FromHours(1), () => { }), - () => scope.Register(new Marker())]; + () => scope.Register(new Marker()), + ]; return actions.All(action => { - try { action(); return false; } - catch (ObjectDisposedException) { return true; } + try + { + action(); + return false; + } + catch (ObjectDisposedException) + { + return true; + } }); } [MethodImpl(MethodImplOptions.NoInlining)] private static WeakReference SubscribeCollectibleEvent(EventBus bus) { - var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("CollectibleRegression"), - AssemblyBuilderAccess.RunAndCollect); - var type = assembly.DefineDynamicModule("Events").DefineType("PluginEvent", TypeAttributes.Public).CreateType()!; + var assembly = AssemblyBuilder.DefineDynamicAssembly( + new AssemblyName("CollectibleRegression"), + AssemblyBuilderAccess.RunAndCollect + ); + var type = assembly + .DefineDynamicModule("Events") + .DefineType("PluginEvent", TypeAttributes.Public) + .CreateType()!; var method = new DynamicMethod("Handle", typeof(void), [type]); method.GetILGenerator().Emit(OpCodes.Ret); var handler = method.CreateDelegate(typeof(Action<>).MakeGenericType(type)); - ((IDisposable)typeof(EventBus).GetMethod(nameof(EventBus.Subscribe))! - .MakeGenericMethod(type).Invoke(bus, [handler, EventPriority.Normal])!).Dispose(); + ( + (IDisposable) + typeof(EventBus) + .GetMethod(nameof(EventBus.Subscribe))! + .MakeGenericMethod(type) + .Invoke(bus, [handler, EventPriority.Normal])! + ).Dispose(); return new WeakReference(type.Assembly); } @@ -670,7 +1014,11 @@ private static void DisposeTasks(PluginScope scope) private static void Collect() { - for (var i = 0; i < 10; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } + for (var i = 0; i < 10; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } } private static bool PackOutput(string root) @@ -679,15 +1027,26 @@ private static bool PackOutput(string root) Directory.CreateDirectory(fixtureBin); foreach (var file in Directory.EnumerateFiles(AppContext.BaseDirectory)) File.Copy(file, Path.Combine(fixtureBin, Path.GetFileName(file)), true); - var apphost = Path.Combine(AppContext.BaseDirectory, - "Hosihikari.PluginManager.Host" + (OperatingSystem.IsWindows() ? ".exe" : "")); - var fakeDotnet = Path.Combine(fixtureBin, "dotnet" + (OperatingSystem.IsWindows() ? ".exe" : "")); + var apphost = Path.Combine( + AppContext.BaseDirectory, + "Hosihikari.PluginManager.Host" + (OperatingSystem.IsWindows() ? ".exe" : "") + ); + var fakeDotnet = Path.Combine( + fixtureBin, + "dotnet" + (OperatingSystem.IsWindows() ? ".exe" : "") + ); File.Copy(apphost, fakeDotnet, true); - if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(fakeDotnet, File.GetUnixFileMode(apphost)); - var start = new ProcessStartInfo(apphost) { RedirectStandardOutput = true, RedirectStandardError = true }; + if (!OperatingSystem.IsWindows()) + File.SetUnixFileMode(fakeDotnet, File.GetUnixFileMode(apphost)); + var start = new ProcessStartInfo(apphost) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + }; start.ArgumentList.Add("--pack-output-regression"); start.ArgumentList.Add(root); - start.Environment["PATH"] = fixtureBin + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH"); + start.Environment["PATH"] = + fixtureBin + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH"); start.Environment["HOSHI_PACK_OUTPUT_FIXTURE"] = "1"; using var process = Process.Start(start)!; var stdout = process.StandardOutput.ReadToEndAsync(); @@ -708,24 +1067,39 @@ internal static int PackOutputChild(string root) var source = Path.Combine(root, "source"); Directory.CreateDirectory(Path.Combine(source, "src")); Directory.CreateDirectory(Path.Combine(source, "shared")); - File.WriteAllText(Path.Combine(source, "src", "main.cs"), """ + File.WriteAllText( + Path.Combine(source, "src", "main.cs"), + """ #:include "../shared/*.cs" #:package fixture@1.0.0 public static class Entry { } - """); - File.WriteAllText(Path.Combine(source, "shared", "helper.cs"), "public static class Helper { }"); + """ + ); + File.WriteAllText( + Path.Combine(source, "shared", "helper.cs"), + "public static class Helper { }" + ); var manifest = Path.Combine(root, "hosihikari.json"); - File.WriteAllText(manifest, JsonSerializer.Serialize(new - { - schemaVersion = 1, name = "OutputFixture", entry = "src/main.cs", kind = "plugin", - apiVersion = int.Parse(PluginContractInfo.CurrentApiVersion), - dependencies = new object[] { new { name = "hosihikari" } }, - loader = "csharp", - })); + File.WriteAllText( + manifest, + JsonSerializer.Serialize( + new + { + schemaVersion = 1, + name = "OutputFixture", + entry = "src/main.cs", + kind = "plugin", + apiVersion = int.Parse(PluginContractInfo.CurrentApiVersion), + dependencies = new object[] { new { name = "hosihikari" } }, + loader = "csharp", + } + ) + ); var result = Packager.Pack(source, manifest, Path.Combine(root, "packages"), []); - return result.Succeeded - && result.PackageDirectory is { } package - && File.Exists(Path.Combine(package, "shared", "helper.cs")) + return + result.Succeeded + && result.PackageDirectory is { } package + && File.Exists(Path.Combine(package, "shared", "helper.cs")) ? 0 : 1; } @@ -748,7 +1122,8 @@ public void Dispose() { } private sealed class BlockingLogger(Action onLog) : ILogger { - public IDisposable? BeginScope(TState state) where TState : notnull => null; + public IDisposable? BeginScope(TState state) + where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; @@ -757,25 +1132,36 @@ public void Log( EventId eventId, TState state, Exception? exception, - Func formatter) => onLog(); + Func formatter + ) => onLog(); } } private sealed class GhostLoader : IPluginLoader { public string Id => "ghost"; + public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) => - new TestPluginHandle(new GhostPlugin()); + + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) => new TestPluginHandle(new GhostPlugin()); private sealed class GhostPlugin : IPlugin { - public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationToken) => ValueTask.CompletedTask; + public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationToken) => + ValueTask.CompletedTask; + public ValueTask OnEnable(CancellationToken cancellationToken) => ValueTask.FromResult(PluginHookResult.Allow()); + public ValueTask OnDisable(CancellationToken cancellationToken) => ValueTask.FromResult(PluginHookResult.Allow()); - public ValueTask OnUnload(CancellationToken cancellationToken) => ValueTask.CompletedTask; + + public ValueTask OnUnload(CancellationToken cancellationToken) => + ValueTask.CompletedTask; } } @@ -787,9 +1173,18 @@ private sealed class FailingLoader(string mode) : IPluginLoader public ManualResetEventSlim? SecondLoadStarted; public ManualResetEventSlim? SecondRelease; public bool RegisterLoader { get; set; } - public int Events, Unloads, Disables, Releases; + public int Events, + Unloads, + Disables, + Releases; + public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) + + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) { Context = context; if (manifest.Name == "Second") @@ -801,17 +1196,23 @@ private sealed class FailingLoader(string mode) : IPluginLoader if (manifest.Name == "Broken" && _mode is "null" or "loader-throw") { UseContext(context); - if (_mode == "loader-throw") throw new InvalidOperationException("loader failure"); + if (_mode == "loader-throw") + throw new InvalidOperationException("loader failure"); return null; } return new Instance(new Plugin(this, manifest.Name), this); } + private void UseContext(IPluginContext context) { context.Events.Subscribe(_ => Interlocked.Increment(ref Events)); context.PluginServices.Register(new Marker()); - context.Scheduler.ScheduleOnce(TimeSpan.FromHours(1), () => Interlocked.Increment(ref Events)); + context.Scheduler.ScheduleOnce( + TimeSpan.FromHours(1), + () => Interlocked.Increment(ref Events) + ); } + private sealed class Instance(IPlugin plugin, FailingLoader owner) : PluginHandle(plugin) { public override bool IsUnloaded => Plugin is null; @@ -827,9 +1228,11 @@ public override void Unload() Plugin = null; } - public override Task WaitForUnloadAsync(CancellationToken cancellationToken = default) => - Task.FromResult(IsUnloaded); + public override Task WaitForUnloadAsync( + CancellationToken cancellationToken = default + ) => Task.FromResult(IsUnloaded); } + private sealed class Plugin(FailingLoader owner, string name) : IPlugin { public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationToken) @@ -844,7 +1247,9 @@ public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationTo if (name == "Broken" && owner._mode is "load" or "cleanup-throw") throw new InvalidOperationException("load failure"); if (name == "Broken" && owner._mode == "fault-on-load") - context.ReportFault(PluginDiagnostic.Error("immediate-death", "immediate death")); + context.ReportFault( + PluginDiagnostic.Error("immediate-death", "immediate death") + ); if (name == "Broken" && owner._mode == "loader-register-throw") { loaderContext?.RegisterLoader(new GhostLoader()); @@ -853,19 +1258,23 @@ public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationTo return ValueTask.CompletedTask; } + public ValueTask OnEnable(CancellationToken cancellationToken) => name == "Broken" && owner._mode == "enable" ? throw new InvalidOperationException("enable failure") : ValueTask.FromResult(PluginHookResult.Allow()); + public ValueTask OnDisable(CancellationToken cancellationToken) { owner.Disables++; return ValueTask.FromResult(PluginHookResult.Allow()); } + public ValueTask OnUnload(CancellationToken cancellationToken) { owner.Unloads++; - if (owner._mode == "cleanup-throw") throw new InvalidOperationException("unload failure"); + if (owner._mode == "cleanup-throw") + throw new InvalidOperationException("unload failure"); return ValueTask.CompletedTask; } } @@ -874,7 +1283,10 @@ public ValueTask OnUnload(CancellationToken cancellationToken) private sealed class CountingScheduler : IScheduler { internal readonly ConcurrentBag References = []; - internal int Created, Disposed, DuplicateDisposes; + internal int Created, + Disposed, + DuplicateDisposes; + public IDisposable ScheduleOnce(TimeSpan delay, Action work) { Interlocked.Increment(ref Created); @@ -882,14 +1294,20 @@ public IDisposable ScheduleOnce(TimeSpan delay, Action work) References.Add(new WeakReference(disposable)); return disposable; } - public IDisposable SchedulePeriodic(TimeSpan interval, Action work) => ScheduleOnce(interval, work); + + public IDisposable SchedulePeriodic(TimeSpan interval, Action work) => + ScheduleOnce(interval, work); + private sealed class Counted(CountingScheduler owner) : IDisposable { private int _disposed; + public void Dispose() { - if (Interlocked.Exchange(ref _disposed, 1) == 0) Interlocked.Increment(ref owner.Disposed); - else Interlocked.Increment(ref owner.DuplicateDisposes); + if (Interlocked.Exchange(ref _disposed, 1) == 0) + Interlocked.Increment(ref owner.Disposed); + else + Interlocked.Increment(ref owner.DuplicateDisposes); } } } diff --git a/host/ScriptPluginLoader.cs b/host/ScriptPluginLoader.cs index 7eb7e0a..f0a4d8d 100644 --- a/host/ScriptPluginLoader.cs +++ b/host/ScriptPluginLoader.cs @@ -12,7 +12,11 @@ public sealed class ScriptPluginLoader : IPluginLoader public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) { var scriptPath = Path.Combine(packageDirectory, manifest.EntryPath); if (!File.Exists(scriptPath)) @@ -20,7 +24,9 @@ public sealed class ScriptPluginLoader : IPluginLoader return null; } - return new TestPluginHandle(new ScriptPlugin(File.ReadAllText(scriptPath), context.DataDirectory)); + return new TestPluginHandle( + new ScriptPlugin(File.ReadAllText(scriptPath), context.DataDirectory) + ); } } diff --git a/host/ThrowingPluginLoader.cs b/host/ThrowingPluginLoader.cs index b20b133..6fb202a 100644 --- a/host/ThrowingPluginLoader.cs +++ b/host/ThrowingPluginLoader.cs @@ -18,6 +18,9 @@ public sealed class ThrowingPluginLoader : IPluginLoader public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) => - throw new InvalidOperationException(ThrowMessage); + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) => throw new InvalidOperationException(ThrowMessage); } diff --git a/src/AssemblyPluginHandle.cs b/src/AssemblyPluginHandle.cs index 419ba6d..04ba4bf 100644 --- a/src/AssemblyPluginHandle.cs +++ b/src/AssemblyPluginHandle.cs @@ -3,7 +3,8 @@ namespace Hosihikari.Internal; /// 内置加载器交出的句柄:放下插件并观察 collectible ALC 的回收(FX-0010 / 0023)。 -internal sealed class AssemblyPluginHandle(IPlugin plugin, PluginLoader loader) : PluginHandle(plugin) +internal sealed class AssemblyPluginHandle(IPlugin plugin, PluginLoader loader) + : PluginHandle(plugin) { private WeakReference? _weakContext; private PluginLoader? _loader = loader; @@ -23,7 +24,9 @@ public override void Unload() Plugin = null; } - public override async Task WaitForUnloadAsync(CancellationToken cancellationToken = default) + public override async Task WaitForUnloadAsync( + CancellationToken cancellationToken = default + ) { if (_weakContext is null) { diff --git a/src/AssemblyPluginLoader.cs b/src/AssemblyPluginLoader.cs index aedaefd..7c6835f 100644 --- a/src/AssemblyPluginLoader.cs +++ b/src/AssemblyPluginLoader.cs @@ -26,7 +26,8 @@ public sealed class AssemblyPluginLoader(params Assembly[] sharedSources) : IPlu /// 基地清单:契约与它引用的抽象包(FX-0019)。载体自己的绑定程序集在它的包清单里, /// 由 并进来。 /// - public static IReadOnlyList SharedAssemblyFileNames => PluginContractInfo.BaseSharedAssemblyFileNames; + public static IReadOnlyList SharedAssemblyFileNames => + PluginContractInfo.BaseSharedAssemblyFileNames; /// /// 目标载体的完整共享层:基地清单 + 该载体包 carrier.sharedAssemblies 声明的程序集 @@ -42,7 +43,10 @@ public static IReadOnlyList SharedLayerFor(string carrierPackageDirector } var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; - var manifest = JsonSerializer.Deserialize(File.ReadAllText(manifestPath), options); + var manifest = JsonSerializer.Deserialize( + File.ReadAllText(manifestPath), + options + ); var declared = manifest?.Carrier?.SharedAssemblies ?? []; return [.. PluginContractInfo.BaseSharedAssemblyFileNames, .. declared]; } @@ -57,14 +61,19 @@ private static Type[] DeclareShared(Assembly[] sources) => public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) { var entryPath = Path.Combine(packageDirectory, manifest.EntryPath); if (!File.Exists(entryPath)) { context.Logger.LogError( "{Message}", - CoreText.Get("Assembly_EntryMissing", manifest.Name, manifest.EntryPath)); + CoreText.Get("Assembly_EntryMissing", manifest.Name, manifest.EntryPath) + ); return null; } @@ -73,7 +82,8 @@ private static Type[] DeclareShared(Assembly[] sources) => entryPath, isUnloadable: true, sharedTypes: _sharedTypes, - configure: config => config.PreferSharedTypes = true); + configure: config => config.PreferSharedTypes = true + ); // 入口由程序集上的特性声明 —— 怎么找到入口是本加载器的事(FX-0008 / FX-0010)。 var assembly = loader.LoadDefaultAssembly(); @@ -82,7 +92,8 @@ private static Type[] DeclareShared(Assembly[] sources) => { context.Logger.LogError( "{Message}", - CoreText.Get("Assembly_EntryCount", manifest.Name, declared)); + CoreText.Get("Assembly_EntryCount", manifest.Name, declared) + ); loader.Dispose(); return null; } diff --git a/src/CarrierComponentContext.cs b/src/CarrierComponentContext.cs index 99dc187..98c8d5e 100644 --- a/src/CarrierComponentContext.cs +++ b/src/CarrierComponentContext.cs @@ -6,7 +6,8 @@ namespace Hosihikari.Internal; internal sealed class CarrierComponentContext( IEventBus events, ILogger logger, - IServiceProvider carrierServices) : ICarrierComponentContext + IServiceProvider carrierServices +) : ICarrierComponentContext { public IEventBus Events => events; diff --git a/src/CarrierStartup.cs b/src/CarrierStartup.cs index 384e70e..606d515 100644 --- a/src/CarrierStartup.cs +++ b/src/CarrierStartup.cs @@ -22,7 +22,8 @@ private CarrierStartup( IServiceProvider services, IReadOnlyList sharedAssemblies, IReadOnlyList components, - string? directory) + string? directory + ) { Services = services; SharedAssemblies = sharedAssemblies; @@ -53,7 +54,8 @@ public static CarrierStartup Create( string? carrierDirectory, nint hostHandle, ILoggerFactory loggerFactory, - out string? error) + out string? error + ) { error = null; var logger = loggerFactory.CreateLogger("Hosihikari"); @@ -76,12 +78,19 @@ public static CarrierStartup Create( { manifest = JsonSerializer.Deserialize( File.ReadAllText(manifestPath), - new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + new JsonSerializerOptions { PropertyNameCaseInsensitive = true } + ); } - catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + catch (Exception ex) + when (ex is JsonException or IOException or UnauthorizedAccessException) { error = CoreText.Get("Native_CarrierManifestInvalid", manifestPath, ex.Message); - return new CarrierStartup(services.BuildServiceProvider(), shared, [], carrierDirectory); + return new CarrierStartup( + services.BuildServiceProvider(), + shared, + [], + carrierDirectory + ); } if (manifest is null || manifest.PackageKind != "carrier") @@ -89,8 +98,14 @@ public static CarrierStartup Create( error = CoreText.Get( "Native_CarrierManifestInvalid", manifestPath, - CoreText.Get("Native_CarrierManifestKind", manifest?.PackageKind ?? "none")); - return new CarrierStartup(services.BuildServiceProvider(), shared, [], carrierDirectory); + CoreText.Get("Native_CarrierManifestKind", manifest?.PackageKind ?? "none") + ); + return new CarrierStartup( + services.BuildServiceProvider(), + shared, + [], + carrierDirectory + ); } var carrier = manifest.Carrier; @@ -105,17 +120,38 @@ public static CarrierStartup Create( else { error = CoreText.Get("Native_CarrierSharedMissing", name); - return new CarrierStartup(services.BuildServiceProvider(), shared, [], carrierDirectory); + return new CarrierStartup( + services.BuildServiceProvider(), + shared, + [], + carrierDirectory + ); } } - if (carrier.Bootstrap is { } bootstrap - && (bootstrap.Assembly.Length > 0 || bootstrap.Type.Length > 0)) + if ( + carrier.Bootstrap is { } bootstrap + && (bootstrap.Assembly.Length > 0 || bootstrap.Type.Length > 0) + ) { - if (!TryConfigure(carrierDirectory, bootstrap, services, hostHandle, logger, out var problem)) + if ( + !TryConfigure( + carrierDirectory, + bootstrap, + services, + hostHandle, + logger, + out var problem + ) + ) { error = problem; - return new CarrierStartup(services.BuildServiceProvider(), shared, [], carrierDirectory); + return new CarrierStartup( + services.BuildServiceProvider(), + shared, + [], + carrierDirectory + ); } } @@ -125,14 +161,21 @@ public static CarrierStartup Create( "Native_CarrierStage", carrierDirectory, carrier.Components.Count, - carrier.Bootstrap?.Type is { Length: > 0 } type ? type : CoreText.Get("Common_None"), - hostHandle == 0 ? CoreText.Get("Common_No") : hostHandle.ToString("X", CultureInfo.InvariantCulture))); + carrier.Bootstrap?.Type is { Length: > 0 } type + ? type + : CoreText.Get("Common_None"), + hostHandle == 0 + ? CoreText.Get("Common_No") + : hostHandle.ToString("X", CultureInfo.InvariantCulture) + ) + ); return new CarrierStartup( services.BuildServiceProvider(), shared, carrier.Components, - carrierDirectory); + carrierDirectory + ); } } } @@ -146,20 +189,30 @@ private static bool TryConfigure( IServiceCollection services, nint hostHandle, ILogger logger, - out string? problem) + out string? problem + ) { problem = null; try { var assembly = ResolveAssembly(carrierDirectory, bootstrap.Assembly, logger); var type = assembly?.GetType(bootstrap.Type, throwOnError: false); - if (type is null || Activator.CreateInstance(type) is not ICarrierServicesConfigurator configurator) + if ( + type is null + || Activator.CreateInstance(type) is not ICarrierServicesConfigurator configurator + ) { - problem = CoreText.Get("Native_CarrierBootstrapMissing", bootstrap.Assembly, bootstrap.Type); + problem = CoreText.Get( + "Native_CarrierBootstrapMissing", + bootstrap.Assembly, + bootstrap.Type + ); return false; } - configurator.Configure(new CarrierServiceContext(services, carrierDirectory, hostHandle)); + configurator.Configure( + new CarrierServiceContext(services, carrierDirectory, hostHandle) + ); return true; } catch (Exception ex) @@ -172,7 +225,8 @@ private static bool TryConfigure( private sealed class CarrierServiceContext( IServiceCollection services, string carrierDirectory, - nint hostHandle) : ICarrierServiceContext + nint hostHandle + ) : ICarrierServiceContext { public IServiceCollection Services => services; @@ -190,12 +244,19 @@ private sealed class CarrierServiceContext( /// private static void EnsurePackageResolver(string carrierDirectory, ILogger logger) { - var context = AssemblyLoadContext.GetLoadContext(typeof(CarrierStartup).Assembly) + var context = + AssemblyLoadContext.GetLoadContext(typeof(CarrierStartup).Assembly) ?? AssemblyLoadContext.Default; lock (ResolverGate) { - if (string.Equals(s_resolvedDirectory, carrierDirectory, StringComparison.OrdinalIgnoreCase)) + if ( + string.Equals( + s_resolvedDirectory, + carrierDirectory, + StringComparison.OrdinalIgnoreCase + ) + ) { return; } @@ -219,7 +280,11 @@ private static void EnsurePackageResolver(string carrierDirectory, ILogger logge } catch (Exception ex) when (ex is FileLoadException or BadImageFormatException) { - logger.LogError(ex, "{Message}", CoreText.Get("Native_CarrierAssemblyFailed", name.Name + ".dll")); + logger.LogError( + ex, + "{Message}", + CoreText.Get("Native_CarrierAssemblyFailed", name.Name + ".dll") + ); return null; } }; @@ -236,7 +301,11 @@ private static void EnsurePackageResolver(string carrierDirectory, ILogger logge /// FileNotFoundException)。也不用 :它挂的是包目录 /// 探测,会把已在上下文里的契约**再装一份**,同名类型于是有两个类型对象,转型失败。 /// - internal static Assembly? ResolveAssembly(string carrierDirectory, string fileName, ILogger logger) + internal static Assembly? ResolveAssembly( + string carrierDirectory, + string fileName, + ILogger logger + ) { if (string.IsNullOrWhiteSpace(fileName)) { @@ -244,14 +313,22 @@ private static void EnsurePackageResolver(string carrierDirectory, ILogger logge } var simpleName = Path.GetFileNameWithoutExtension(fileName); - var context = AssemblyLoadContext.GetLoadContext(typeof(CarrierStartup).Assembly) + var context = + AssemblyLoadContext.GetLoadContext(typeof(CarrierStartup).Assembly) ?? AssemblyLoadContext.Default; try { // 同一份程序集只装一次:bootstrap 与组件都要先查共享层里已经装进来的那份。 - if (context.Assemblies.FirstOrDefault( - loaded => string.Equals(loaded.GetName().Name, simpleName, StringComparison.OrdinalIgnoreCase)) - is { } existing) + if ( + context.Assemblies.FirstOrDefault(loaded => + string.Equals( + loaded.GetName().Name, + simpleName, + StringComparison.OrdinalIgnoreCase + ) + ) is + { } existing + ) { return existing; } @@ -261,9 +338,14 @@ private static void EnsurePackageResolver(string carrierDirectory, ILogger logge ? context.LoadFromAssemblyPath(Path.GetFullPath(path)) : Assembly.Load(new AssemblyName(simpleName)); } - catch (Exception ex) when (ex is FileNotFoundException or FileLoadException or BadImageFormatException) + catch (Exception ex) + when (ex is FileNotFoundException or FileLoadException or BadImageFormatException) { - logger.LogError(ex, "{Message}", CoreText.Get("Native_CarrierAssemblyFailed", fileName)); + logger.LogError( + ex, + "{Message}", + CoreText.Get("Native_CarrierAssemblyFailed", fileName) + ); return null; } } diff --git a/src/CoreText.cs b/src/CoreText.cs index 4ad02f0..a40f278 100644 --- a/src/CoreText.cs +++ b/src/CoreText.cs @@ -15,13 +15,13 @@ internal static class CoreText { private const string ResourceBaseName = "Hosihikari.Resources.CoreStrings"; - private static readonly IStringLocalizer Localizer = - new ResourceManagerStringLocalizer( - new ResourceManager(ResourceBaseName, typeof(CoreStrings).Assembly), - typeof(CoreStrings).Assembly, - ResourceBaseName, - new ResourceNamesCache(), - NullLogger.Instance); + private static readonly IStringLocalizer Localizer = new ResourceManagerStringLocalizer( + new ResourceManager(ResourceBaseName, typeof(CoreStrings).Assembly), + typeof(CoreStrings).Assembly, + ResourceBaseName, + new ResourceNamesCache(), + NullLogger.Instance + ); internal static string Get(string key, params object[] arguments) => Localizer[key, arguments]; } diff --git a/src/DependencyGraph.cs b/src/DependencyGraph.cs index 21ecd74..027d477 100644 --- a/src/DependencyGraph.cs +++ b/src/DependencyGraph.cs @@ -4,7 +4,10 @@ namespace Hosihikari.Internal; internal static class DependencyGraph { /// 返回加载顺序;缺失依赖或成环的包被剔出来单独报告,不牵连其余包(FX-0009)。 - internal static List Resolve(IReadOnlyList packages, Action report) + internal static List Resolve( + IReadOnlyList packages, + Action report + ) { var byName = packages.ToDictionary(p => p.Manifest.Name, StringComparer.Ordinal); var order = new List(); @@ -26,7 +29,8 @@ private static bool Visit( Dictionary byName, Dictionary state, List order, - Action report) + Action report + ) { var name = package.Manifest.Name; if (state.TryGetValue(name, out var mark)) diff --git a/src/DependencyVersion.cs b/src/DependencyVersion.cs index 54b72ba..e727d60 100644 --- a/src/DependencyVersion.cs +++ b/src/DependencyVersion.cs @@ -11,8 +11,10 @@ internal static bool TryValidateManifest(PluginManifest manifest, out string? pr { problem = null; - if (!string.IsNullOrWhiteSpace(manifest.Version) - && !NuGetVersion.TryParse(manifest.Version, out _)) + if ( + !string.IsNullOrWhiteSpace(manifest.Version) + && !NuGetVersion.TryParse(manifest.Version, out _) + ) { problem = CoreText.Get("Version_Invalid", manifest.Name, manifest.Version); return false; @@ -26,14 +28,17 @@ internal static bool TryValidateManifest(PluginManifest manifest, out string? pr return false; } - if (!string.IsNullOrWhiteSpace(dependency.VersionRange) - && !VersionRange.TryParse(dependency.VersionRange, out _)) + if ( + !string.IsNullOrWhiteSpace(dependency.VersionRange) + && !VersionRange.TryParse(dependency.VersionRange, out _) + ) { problem = CoreText.Get( "Version_InvalidRange", manifest.Name, dependency.Name, - dependency.VersionRange); + dependency.VersionRange + ); return false; } } @@ -42,23 +47,36 @@ internal static bool TryValidateManifest(PluginManifest manifest, out string? pr } /// 目标插件的版本是否满足这条依赖约束;没有约束时接受任意版本。 - internal static bool Satisfies(PluginManifest target, ManifestDependency dependency, out string? problem) + internal static bool Satisfies( + PluginManifest target, + ManifestDependency dependency, + out string? problem + ) { problem = null; - if (string.IsNullOrWhiteSpace(dependency.VersionRange) || dependency.VersionRange.Trim() == "*") + if ( + string.IsNullOrWhiteSpace(dependency.VersionRange) + || dependency.VersionRange.Trim() == "*" + ) { return true; } if (!VersionRange.TryParse(dependency.VersionRange, out var range)) { - problem = CoreText.Get("Version_ConstraintInvalid", dependency.Name, dependency.VersionRange); + problem = CoreText.Get( + "Version_ConstraintInvalid", + dependency.Name, + dependency.VersionRange + ); return false; } - if (string.IsNullOrWhiteSpace(target.Version) - || !NuGetVersion.TryParse(target.Version, out var version)) + if ( + string.IsNullOrWhiteSpace(target.Version) + || !NuGetVersion.TryParse(target.Version, out var version) + ) { problem = CoreText.Get("Version_NoVersion", dependency.Name, dependency.VersionRange); return false; @@ -66,10 +84,17 @@ internal static bool Satisfies(PluginManifest target, ManifestDependency depende // 浮动版本(1.*、1.2.*)在 VersionRange 里没有上界,Satisfies 会放过 2.0.0; // 上界由 FloatRange 给出,两个都要满足。 - if (!range.Satisfies(version) - || (range.Float is { } floatRange && !floatRange.Satisfies(version))) + if ( + !range.Satisfies(version) + || (range.Float is { } floatRange && !floatRange.Satisfies(version)) + ) { - problem = CoreText.Get("Version_NotSatisfied", dependency.Name, version, dependency.VersionRange); + problem = CoreText.Get( + "Version_NotSatisfied", + dependency.Name, + version, + dependency.VersionRange + ); return false; } diff --git a/src/EventBus.cs b/src/EventBus.cs index d322c93..55ad86a 100644 --- a/src/EventBus.cs +++ b/src/EventBus.cs @@ -5,19 +5,34 @@ namespace Hosihikari.Internal; internal sealed class EventBus(ILogger logger) : IEventBus { private static readonly EventPriority[] Bands = - [EventPriority.Lowest, EventPriority.Low, EventPriority.Normal, EventPriority.High, EventPriority.Highest, EventPriority.Monitor]; + [ + EventPriority.Lowest, + EventPriority.Low, + EventPriority.Normal, + EventPriority.High, + EventPriority.Highest, + EventPriority.Monitor, + ]; private readonly Lock _gate = new(); + // 每个事件类型六个桶,按 Bands 的次序分发(FX-0060);桶内按订阅顺序。 private readonly Dictionary[]> _handlers = []; - public IDisposable Subscribe(Action handler, EventPriority priority = EventPriority.Normal) + public IDisposable Subscribe( + Action handler, + EventPriority priority = EventPriority.Normal + ) { ArgumentNullException.ThrowIfNull(handler); var bucket = Array.IndexOf(Bands, priority); if (bucket < 0) { - throw new ArgumentOutOfRangeException(nameof(priority), priority, "Unknown event priority"); + throw new ArgumentOutOfRangeException( + nameof(priority), + priority, + "Unknown event priority" + ); } lock (_gate) @@ -47,7 +62,8 @@ public IDisposable Subscribe(Action handler, EventPriority prior }); } - private static List[] CreateBuckets() => [.. Bands.Select(static _ => new List())]; + private static List[] CreateBuckets() => + [.. Bands.Select(static _ => new List())]; public void Publish(TEvent @event) { @@ -71,7 +87,11 @@ public void Publish(TEvent @event) catch (Exception ex) { // 隔离到这一个 handler,继续分发给其余 —— FX-0009 在事件总线上的落地(FX-0014)。 - logger.LogError(ex, "{Message}", CoreText.Get("Event_HandlerThrew", typeof(TEvent).Name)); + logger.LogError( + ex, + "{Message}", + CoreText.Get("Event_HandlerThrew", typeof(TEvent).Name) + ); } } } @@ -91,11 +111,16 @@ public IDisposable ScheduleOnce(TimeSpan delay, Action work) { // 先建成不引发的那种,赋值之后再 Change —— 否则回调可能早于赋值而拿不到自己。 Timer? timer = null; - timer = new Timer(_ => - { - timer!.Dispose(); - Raise(work); - }, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + timer = new Timer( + _ => + { + timer!.Dispose(); + Raise(work); + }, + null, + Timeout.InfiniteTimeSpan, + Timeout.InfiniteTimeSpan + ); timer.Change(delay, Timeout.InfiniteTimeSpan); return new Handle(timer); } diff --git a/src/Hosihikari.PluginManager.csproj b/src/Hosihikari.PluginManager.csproj index 04cb951..ae7394e 100644 --- a/src/Hosihikari.PluginManager.csproj +++ b/src/Hosihikari.PluginManager.csproj @@ -1,5 +1,4 @@ - net10.0 enable @@ -32,12 +31,20 @@ - - + + - + @@ -64,5 +71,4 @@ - diff --git a/src/ManifestReader.cs b/src/ManifestReader.cs index 93b157d..50fac36 100644 --- a/src/ManifestReader.cs +++ b/src/ManifestReader.cs @@ -33,9 +33,11 @@ internal static List Scan(string pluginsRoot, Action repo // 旧信封的 type 也不是 hosihikari 的目录,不吭声。 if (File.Exists(Path.Combine(directory, FileName))) { - if (Read(directory, report) is { } package + if ( + Read(directory, report) is { } package // 载体包就是垫片自己,不是插件(FX-0006)。 - && package.Manifest.PackageKind != "carrier") + && package.Manifest.PackageKind != "carrier" + ) { packages.Add(package); } @@ -57,15 +59,20 @@ internal static List Scan(string pluginsRoot, Action repo if (!File.Exists(manifestPath)) { // 父级只把路由给我们的包交过来,所以这里的旧信封一定是旧包(FX-0058)。 - report(File.Exists(Path.Combine(directory, LegacyFileName)) - ? CoreText.Get("Manifest_LegacyPackage", folderName) - : CoreText.Get("Manifest_MissingFile", folderName, FileName)); + report( + File.Exists(Path.Combine(directory, LegacyFileName)) + ? CoreText.Get("Manifest_LegacyPackage", folderName) + : CoreText.Get("Manifest_MissingFile", folderName, FileName) + ); return null; } try { - var manifest = JsonSerializer.Deserialize(File.ReadAllText(manifestPath), Options); + var manifest = JsonSerializer.Deserialize( + File.ReadAllText(manifestPath), + Options + ); if (manifest is null) { report(CoreText.Get("Manifest_Empty", folderName)); @@ -102,54 +109,77 @@ internal static List Scan(string pluginsRoot, Action repo // type 在 hosihikari.json 里可省;写了就必须对。它是父级的路由键,写错的包 // 不会被父级交过来,所以在自持态下也一并拦下(FX-0012)。 - if (!string.IsNullOrWhiteSpace(manifest.ParentName) - && manifest.ParentName != PluginContractInfo.ParentName) + if ( + !string.IsNullOrWhiteSpace(manifest.ParentName) + && manifest.ParentName != PluginContractInfo.ParentName + ) { - report(CoreText.Get( - "Manifest_ParentMismatch", - folderName, - PluginContractInfo.ParentName, - manifest.ParentName)); + report( + CoreText.Get( + "Manifest_ParentMismatch", + folderName, + PluginContractInfo.ParentName, + manifest.ParentName + ) + ); return null; } - if (manifest.EffectiveApiVersion is not { } apiVersion - || apiVersion.ToString(CultureInfo.InvariantCulture) != PluginContractInfo.CurrentApiVersion) + if ( + manifest.EffectiveApiVersion is not { } apiVersion + || apiVersion.ToString(CultureInfo.InvariantCulture) + != PluginContractInfo.CurrentApiVersion + ) { - report(CoreText.Get( - "Manifest_ApiMismatch", - folderName, - manifest.EffectiveApiVersion?.ToString(CultureInfo.InvariantCulture) - ?? CoreText.Get("Common_Undeclared"), - PluginContractInfo.CurrentApiVersion)); + report( + CoreText.Get( + "Manifest_ApiMismatch", + folderName, + manifest.EffectiveApiVersion?.ToString(CultureInfo.InvariantCulture) + ?? CoreText.Get("Common_Undeclared"), + PluginContractInfo.CurrentApiVersion + ) + ); return null; } // 清单 schema 版本(FX-0012):解析器只认这一个版本。 - if (manifest.EffectiveSchemaVersion is not { } schemaVersion - || schemaVersion.ToString(CultureInfo.InvariantCulture) != PluginContractInfo.CurrentManifestVersion) + if ( + manifest.EffectiveSchemaVersion is not { } schemaVersion + || schemaVersion.ToString(CultureInfo.InvariantCulture) + != PluginContractInfo.CurrentManifestVersion + ) { - report(CoreText.Get( - "Manifest_ManifestVersionMismatch", - folderName, - manifest.EffectiveSchemaVersion?.ToString(CultureInfo.InvariantCulture) - ?? CoreText.Get("Common_Undeclared"), - PluginContractInfo.CurrentManifestVersion)); + report( + CoreText.Get( + "Manifest_ManifestVersionMismatch", + folderName, + manifest.EffectiveSchemaVersion?.ToString(CultureInfo.InvariantCulture) + ?? CoreText.Get("Common_Undeclared"), + PluginContractInfo.CurrentManifestVersion + ) + ); return null; } // JSON null 会绕过集合初始化;ManifestDependency 也可能被写成 null。 // 这里统一拒绝,别让依赖图在后面抛 NRE。 - if (manifest.Dependencies.Any(dependency => - dependency is null || string.IsNullOrWhiteSpace(dependency.Name))) + if ( + manifest.Dependencies.Any(dependency => + dependency is null || string.IsNullOrWhiteSpace(dependency.Name) + ) + ) { report(CoreText.Get("Manifest_DependencyName", folderName)); return null; } // 父级态不跑依赖图;自依赖会让卸载永远看到“还有依赖者”。 - if (manifest.Dependencies.Any(dependency => - string.Equals(dependency.Name, manifest.Name, StringComparison.Ordinal))) + if ( + manifest.Dependencies.Any(dependency => + string.Equals(dependency.Name, manifest.Name, StringComparison.Ordinal) + ) + ) { report(CoreText.Get("Manifest_SelfDependency", folderName)); return null; @@ -171,9 +201,16 @@ internal static List Scan(string pluginsRoot, Action repo // 对框架的依赖(FX-0006):缺了父级会把它排到垫片前面,判成 Unknown mod type。 // 载体包就是垫片自己,不依赖自己。 - if (kind != "carrier" + if ( + kind != "carrier" && !manifest.Dependencies.Any(dependency => - string.Equals(dependency.Name, PluginContractInfo.ParentName, StringComparison.Ordinal))) + string.Equals( + dependency.Name, + PluginContractInfo.ParentName, + StringComparison.Ordinal + ) + ) + ) { report(CoreText.Get("Manifest_MissingFrameworkDependency", folderName)); return null; @@ -216,7 +253,8 @@ private static bool IsRoutedToUs(string directory) && type.ValueKind == JsonValueKind.String && type.GetString() == PluginContractInfo.ParentName; } - catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + catch (Exception ex) + when (ex is JsonException or IOException or UnauthorizedAccessException) { return false; } @@ -254,14 +292,17 @@ internal static bool IsEntryContained(string packageDirectory, string entry) } var root = Path.GetFullPath(packageDirectory); - var prefix = root.EndsWith(Path.DirectorySeparatorChar) ? root : root + Path.DirectorySeparatorChar; + var prefix = root.EndsWith(Path.DirectorySeparatorChar) + ? root + : root + Path.DirectorySeparatorChar; var full = Path.GetFullPath(Path.Combine(root, entry)); var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; return full.StartsWith(prefix, comparison); } - catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + catch (Exception ex) + when (ex is ArgumentException or NotSupportedException or PathTooLongException) { return false; } diff --git a/src/NativeForwardingLoggerProvider.cs b/src/NativeForwardingLoggerProvider.cs index 9b0af67..43cccf7 100644 --- a/src/NativeForwardingLoggerProvider.cs +++ b/src/NativeForwardingLoggerProvider.cs @@ -1,6 +1,5 @@ using System.Diagnostics; using System.Text; - using Microsoft.Extensions.Logging; namespace Hosihikari.Internal; @@ -28,13 +27,12 @@ internal static void SetSink(IntPtr callback, IntPtr user) public ILogger CreateLogger(string categoryName) => new Logger(categoryName); - public void Dispose() - { - } + public void Dispose() { } private sealed class Logger(string category) : ILogger { - public IDisposable? BeginScope(TState state) where TState : notnull => null; + public IDisposable? BeginScope(TState state) + where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information; @@ -43,7 +41,8 @@ public void Log( EventId eventId, TState state, Exception? error, - Func formatter) + Func formatter + ) { var callback = Volatile.Read(ref s_callback); if (!IsEnabled(logLevel) || callback == IntPtr.Zero) @@ -63,18 +62,22 @@ public void Log( fixed (byte* text = bytes) { ((delegate* unmanaged[Cdecl])callback)( - Volatile.Read(ref s_user), Level(logLevel), text); + Volatile.Read(ref s_user), + Level(logLevel), + text + ); } } /// 0 调试、1 信息、2 警告、3 错误、4 致命 —— 与两个载体的桥一致。 - private static int Level(LogLevel level) => level switch - { - LogLevel.Trace or LogLevel.Debug => 0, - LogLevel.Information => 1, - LogLevel.Warning => 2, - LogLevel.Error => 3, - _ => 4, - }; + private static int Level(LogLevel level) => + level switch + { + LogLevel.Trace or LogLevel.Debug => 0, + LogLevel.Information => 1, + LogLevel.Warning => 2, + LogLevel.Error => 3, + _ => 4, + }; } } diff --git a/src/NativeHostingEntry.cs b/src/NativeHostingEntry.cs index 01e6405..4721015 100644 --- a/src/NativeHostingEntry.cs +++ b/src/NativeHostingEntry.cs @@ -38,7 +38,8 @@ public static class NativeHostingEntry /// 给原生垫片读取的契约版本入口。 [UnmanagedCallersOnly] - public static int GetHostingContractVersion(IntPtr arg, int argSizeInBytes) => HostingContractVersion; + public static int GetHostingContractVersion(IntPtr arg, int argSizeInBytes) => + HostingContractVersion; /// /// 父级交来日志出口: 指向 { void* callback; void* user; }。 @@ -107,7 +108,10 @@ public static int StartUnderParent(IntPtr arg, int argSizeInBytes) => /// 读启动参数:载体包目录与不透明宿主句柄。字符串只在这次调用里有效,立刻复制; /// 没有参数(验证宿主、旧行为)时目录为空、句柄为零。 /// - private static (string? CarrierDirectory, nint Host) ReadStartArgs(IntPtr arg, int argSizeInBytes) + private static (string? CarrierDirectory, nint Host) ReadStartArgs( + IntPtr arg, + int argSizeInBytes + ) { if (arg == IntPtr.Zero || argSizeInBytes < IntPtr.Size * 2) { @@ -268,7 +272,9 @@ private static int Deliver(IntPtr arg, Verb verb) CoreText.Get( "Native_UnloadIncomplete", text, - result.Error ?? CoreText.Get("Common_Unknown"))); + result.Error ?? CoreText.Get("Common_Unknown") + ) + ); } return result.Released ? 0 : 1; @@ -281,13 +287,14 @@ private static int Deliver(IntPtr arg, Verb verb) } } - private static string ActionName(Verb verb) => verb switch - { - Verb.Load => CoreText.Get("Verb_Load"), - Verb.Unload => CoreText.Get("Verb_Unload"), - Verb.Enable => CoreText.Get("Verb_Enable"), - _ => CoreText.Get("Verb_Disable"), - }; + private static string ActionName(Verb verb) => + verb switch + { + Verb.Load => CoreText.Get("Verb_Load"), + Verb.Unload => CoreText.Get("Verb_Unload"), + Verb.Enable => CoreText.Get("Verb_Enable"), + _ => CoreText.Get("Verb_Disable"), + }; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void RemovalCallback(IntPtr user, IntPtr nameUtf8); @@ -319,7 +326,8 @@ private static void ForwardRemoval(string name) } catch (Exception ex) { - s_loggerFactory?.CreateLogger("Hosihikari") + s_loggerFactory + ?.CreateLogger("Hosihikari") .LogError(ex, "{Message}", CoreText.Get("Native_RemovalNotifyFailed", name)); } } @@ -337,7 +345,11 @@ private static int StartCore(bool scanPlugins, (string? CarrierDirectory, nint H try { var restarted = CarrierStartup.Create( - args.CarrierDirectory, args.Host, s_loggerFactory!, out var restartError); + args.CarrierDirectory, + args.Host, + s_loggerFactory!, + out var restartError + ); if (restartError is not null) { reuseLogger?.LogError("{Message}", restartError); @@ -345,12 +357,19 @@ private static int StartCore(bool scanPlugins, (string? CarrierDirectory, nint H } reused.RepublishCarrierServices(restarted.Services); - if (restarted.Directory is { Length: > 0 } reusedDirectory && restarted.Components.Count > 0 - && !reused.StartComponents(reusedDirectory, restarted.Components)) + if ( + restarted.Directory is { Length: > 0 } reusedDirectory + && restarted.Components.Count > 0 + && !reused.StartComponents(reusedDirectory, restarted.Components) + ) { reuseLogger?.LogError( "{Message}", - CoreText.Get("Native_ComponentsFailed", string.Join(" | ", restarted.Components))); + CoreText.Get( + "Native_ComponentsFailed", + string.Join(" | ", restarted.Components) + ) + ); return 1; } @@ -384,16 +403,24 @@ private static int StartCore(bool scanPlugins, (string? CarrierDirectory, nint H "{Message}", CoreText.Get( "Native_Versions", - typeof(PluginManager).Assembly.GetName().Version?.ToString(3) ?? CoreText.Get("Common_Unknown"), + typeof(PluginManager).Assembly.GetName().Version?.ToString(3) + ?? CoreText.Get("Common_Unknown"), HostingContractVersion, - PluginContractInfo.CurrentApiVersion)); + PluginContractInfo.CurrentApiVersion + ) + ); // 服务端根就是进程的工作目录;配置与数据都相对它找(FX-0018)。 var root = Directory.GetCurrentDirectory(); // 宿主从 services 里取 ILoggerFactory;不传的话插件拿到的是 NullLogger —— // 它们的每一行都会消失,而且不会有人报错。 // 载体包在容器建成之前配置它自己的服务(FX-0064)。 - var startup = CarrierStartup.Create(args.CarrierDirectory, args.Host, s_loggerFactory!, out var startupError); + var startup = CarrierStartup.Create( + args.CarrierDirectory, + args.Host, + s_loggerFactory!, + out var startupError + ); if (startupError is not null) { logger.LogError("{Message}", startupError); @@ -408,16 +435,26 @@ private static int StartCore(bool scanPlugins, (string? CarrierDirectory, nint H startup.Services, ForwardRemoval, // 自持态扫描并拥有插件集;父级态由父级驱动启停(FX-0003 / 0062)。 - new PluginManagerOptions { OwnsPluginSet = scanPlugins }); + new PluginManagerOptions { OwnsPluginSet = scanPlugins } + ); host.RegisterLoader(new AssemblyPluginLoader([.. startup.SharedAssemblies])); // 组件在事件分发对插件开启之前启动;任何一个失败都中止整次启动(FX-0061)。 // 宿主到这里才公布:失败的启动不能留一个“已就绪”的静态宿主给重试(Codex 指出)。 - if (startup.Directory is { Length: > 0 } carrierDirectory && startup.Components.Count > 0) + if ( + startup.Directory is { Length: > 0 } carrierDirectory + && startup.Components.Count > 0 + ) { if (!host.StartComponents(carrierDirectory, startup.Components)) { - logger.LogError("{Message}", CoreText.Get("Native_ComponentsFailed", string.Join(" | ", startup.Components))); + logger.LogError( + "{Message}", + CoreText.Get( + "Native_ComponentsFailed", + string.Join(" | ", startup.Components) + ) + ); (startup.Services as IDisposable)?.Dispose(); return 1; } @@ -433,7 +470,9 @@ private static int StartCore(bool scanPlugins, (string? CarrierDirectory, nint H CoreText.Get( "Native_Loaded", host.LoadedNames.Count, - string.Join(", ", host.LoadedNames))); + string.Join(", ", host.LoadedNames) + ) + ); } else { diff --git a/src/PluginContext.cs b/src/PluginContext.cs index da89b7e..3a53c88 100644 --- a/src/PluginContext.cs +++ b/src/PluginContext.cs @@ -14,7 +14,8 @@ internal sealed class PluginContext( PluginManager host, Guid instanceId, bool isLoader, - Action reportFault) : ILoaderContext + Action reportFault +) : ILoaderContext { internal static readonly IServiceProvider Empty = new EmptyServices(); @@ -60,6 +61,7 @@ private sealed class PlainContext(PluginContext inner) : IPluginContext public IScheduler Scheduler => inner.Scheduler; public IPluginServiceRegistry PluginServices => inner.PluginServices; public IServiceProvider CarrierServices => inner.CarrierServices; + public void ReportFault(PluginDiagnostic diagnostic) => inner.ReportFault(diagnostic); } diff --git a/src/PluginInfo.cs b/src/PluginInfo.cs index 037f97a..35cf907 100644 --- a/src/PluginInfo.cs +++ b/src/PluginInfo.cs @@ -17,7 +17,8 @@ public sealed record PluginInfo( PluginState State, bool Enabled, bool IsLoader, - IReadOnlyList Dependencies); + IReadOnlyList Dependencies +); /// 一条依赖的只读快照。 /// 被依赖的插件名。 diff --git a/src/PluginManager.cs b/src/PluginManager.cs index 3551c50..0ac7218 100644 --- a/src/PluginManager.cs +++ b/src/PluginManager.cs @@ -2,10 +2,10 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Hocon.Extensions.Configuration; +using Hosihikari.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Hosihikari.Internal; namespace Hosihikari; @@ -15,20 +15,22 @@ public sealed class PluginManager private readonly string _pluginsRoot; private readonly string _dataRoot; private readonly string _configRoot; + // Task.WaitAsync / Task.Delay 的计时器上限;超过它会抛 ArgumentOutOfRangeException。 - private static readonly TimeSpan MaxTimeout = - TimeSpan.FromMilliseconds(uint.MaxValue - 1); + private static readonly TimeSpan MaxTimeout = TimeSpan.FromMilliseconds(uint.MaxValue - 1); private readonly TimeSpan _hookTimeout; private readonly TimeSpan _unloadVerificationTimeout; private readonly TimeSpan _componentStopTimeout; private readonly bool _ownsPluginSet; private readonly Action _reportFault; + // 载体服务在父级重载后可以换代(Endstone 的 Plugin* 会变),所以不是 readonly; // 换代经 RepublishCarrierServices,由托管入口在重载路径上调用(FX-0065)。 private IServiceProvider? _carrierServices; private readonly Action? _onRemoved; private readonly object _gate = new(); + // 钩子跑在线程池上,钩子里回调管理器时拿不到 _gate(调用方正握着它等钩子)。 // 所以在装载钩子里会用到的那两本账各有自己的锁,不与 _gate 相交。 private readonly object _faultGate = new(); @@ -57,7 +59,8 @@ public PluginManager( string configRoot, Action reportFault, IServiceProvider? carrierServices = null, - Action? onRemoved = null) + Action? onRemoved = null + ) : this( pluginsRoot, dataRoot, @@ -65,9 +68,9 @@ public PluginManager( reportFault, carrierServices, onRemoved, - new PluginManagerOptions()) - { - } + new PluginManagerOptions() + ) + { } /// 带显式配置的构造函数;现有构造函数保持原签名。 public PluginManager( @@ -77,15 +80,22 @@ public PluginManager( Action reportFault, IServiceProvider? carrierServices, Action? onRemoved, - PluginManagerOptions options) + PluginManagerOptions options + ) { ArgumentNullException.ThrowIfNull(options); // InfiniteTimeSpan 是 1.x 已有的取值,继续收(加法承诺);有限值才走范围校验。 _hookTimeout = ValidateTimeout(options.HookTimeout, nameof(options), "HookTimeout"); _unloadVerificationTimeout = ValidateTimeout( - options.UnloadVerificationTimeout, nameof(options), "UnloadVerificationTimeout"); + options.UnloadVerificationTimeout, + nameof(options), + "UnloadVerificationTimeout" + ); _componentStopTimeout = ValidateTimeout( - options.ComponentStopTimeout, nameof(options), "ComponentStopTimeout"); + options.ComponentStopTimeout, + nameof(options), + "ComponentStopTimeout" + ); _ownsPluginSet = options.OwnsPluginSet; _pluginsRoot = pluginsRoot; @@ -94,8 +104,9 @@ public PluginManager( _reportFault = reportFault; _carrierServices = carrierServices; _onRemoved = onRemoved; - _loggerFactory = carrierServices?.GetService(typeof(ILoggerFactory)) as ILoggerFactory - ?? NullLoggerFactory.Instance; + _loggerFactory = + carrierServices?.GetService(typeof(ILoggerFactory)) as ILoggerFactory + ?? NullLoggerFactory.Instance; _events = new EventBus(_loggerFactory.CreateLogger("Hosihikari.Events")); _scheduler = new Scheduler(_loggerFactory.CreateLogger("Hosihikari.Scheduler")); @@ -110,7 +121,8 @@ private static TimeSpan ValidateTimeout(TimeSpan value, string parameter, string { throw new ArgumentOutOfRangeException( parameter, - $"{name} must be positive and no more than about 49.7 days, or Timeout.InfiniteTimeSpan."); + $"{name} must be positive and no more than about 49.7 days, or Timeout.InfiniteTimeSpan." + ); } return value; @@ -142,7 +154,8 @@ internal bool TryRegisterLoader( Guid instanceId, PluginContext context, IPluginLoader loader, - out string? problem) + out string? problem + ) { lock (_loaderGate) { @@ -159,7 +172,8 @@ internal bool TryRegisterLoader( "Manager_LoaderDuplicate", loader.Id, existing.GetType().Name, - loader.GetType().Name); + loader.GetType().Name + ); return false; } @@ -208,7 +222,8 @@ internal bool TryAddLoader(IPluginLoader loader, out string? problem) "Manager_LoaderDuplicate", loader.Id, existing.GetType().Name, - loader.GetType().Name); + loader.GetType().Name + ); return false; } @@ -258,7 +273,8 @@ public IReadOnlyCollection LoadedNames { lock (_gate) { - return _slots.Where(slot => slot.Value.State == PluginState.Loaded) + return _slots + .Where(slot => slot.Value.State == PluginState.Loaded) .Select(slot => slot.Key) .ToArray(); } @@ -272,8 +288,8 @@ public IReadOnlyList Plugins { lock (_gate) { - return _slots.Values - .OrderBy(slot => slot.Manifest.Name, StringComparer.Ordinal) + return _slots + .Values.OrderBy(slot => slot.Manifest.Name, StringComparer.Ordinal) .Select(ToInfo) .ToArray(); } @@ -296,16 +312,20 @@ public bool TryGetPlugin(string name, [NotNullWhen(true)] out PluginInfo? plugin } } - private static PluginInfo ToInfo(Slot slot) => new( - slot.Manifest.Name, - slot.Manifest.Version, - slot.Manifest.Loader, - slot.State, - slot.Enabled, - slot.IsLoader, - slot.Manifest.Dependencies - .Select(dependency => new PluginDependencyInfo(dependency.Name, dependency.VersionRange)) - .ToArray()); + private static PluginInfo ToInfo(Slot slot) => + new( + slot.Manifest.Name, + slot.Manifest.Version, + slot.Manifest.Loader, + slot.State, + slot.Enabled, + slot.IsLoader, + slot.Manifest.Dependencies.Select(dependency => new PluginDependencyInfo( + dependency.Name, + dependency.VersionRange + )) + .ToArray() + ); /// 载体适配器要把载体事件并进来,所以事件总线得对外可达(FX-0007)。 public IEventBus Events => _events; @@ -352,7 +372,8 @@ private static void DisposeCarrierServices(IServiceProvider services) /// 全部启动成功为 。 public bool StartComponents( string carrierPackageDirectory, - IReadOnlyList components) + IReadOnlyList components + ) { ArgumentNullException.ThrowIfNull(components); if (_componentsStarted) @@ -365,7 +386,9 @@ public bool StartComponents( var ok = true; // 组件类型住共享层(FX-0026 / 0061),按约定名从默认上下文解析;载体包里的私有程序集按路径装。 - var assemblies = new Dictionary(StringComparer.OrdinalIgnoreCase); + var assemblies = new Dictionary( + StringComparer.OrdinalIgnoreCase + ); foreach (var component in components) { if (!assemblies.TryGetValue(component.Assembly, out var assembly)) @@ -374,18 +397,22 @@ public bool StartComponents( { // 与载体装配同一条解析规则:共享层里装过一次的那份就复用, // 否则按包内路径装(LoadFrom 会为同一个类型再装一份,别用)。 - assemblies[component.Assembly] = assembly = CarrierStartup.ResolveAssembly( - carrierPackageDirectory, - component.Assembly, - _loggerFactory.CreateLogger("Hosihikari.Components")) - ?? throw new FileNotFoundException(component.Assembly); + assemblies[component.Assembly] = assembly = + CarrierStartup.ResolveAssembly( + carrierPackageDirectory, + component.Assembly, + _loggerFactory.CreateLogger("Hosihikari.Components") + ) ?? throw new FileNotFoundException(component.Assembly); } catch (Exception ex) { - reports.Add(CoreText.Get( - "Manager_ComponentAssemblyFailed", - component.Assembly, - ex.Demystify())); + reports.Add( + CoreText.Get( + "Manager_ComponentAssemblyFailed", + component.Assembly, + ex.Demystify() + ) + ); ok = false; break; } @@ -395,12 +422,15 @@ public bool StartComponents( try { var type = assembly.GetType(component.Type, throwOnError: false); - instance = type is null ? null : Activator.CreateInstance(type) as ICarrierComponent; + instance = type is null + ? null + : Activator.CreateInstance(type) as ICarrierComponent; } catch (Exception ex) { // 构造函数抛出与类型缺失同一种结局:记一笔、按启动失败处理(Codex 指出的漏网路径)。 - _loggerFactory.CreateLogger("Hosihikari.Components") + _loggerFactory + .CreateLogger("Hosihikari.Components") .LogDebug(ex, "{Message}", component.Type); instance = null; } @@ -415,11 +445,18 @@ public bool StartComponents( var context = new CarrierComponentContext( _events, _loggerFactory.CreateLogger(instance.GetType().FullName ?? instance.GetType().Name), - _carrierServices ?? PluginContext.Empty); + _carrierServices ?? PluginContext.Empty + ); // 先记账再启动:启动失败的那一个也可能已经订阅了事件或拿了原生资源, // 回滚同样要给它一次 StopAsync(Codex 指出)。 started.Add(instance); - if (!TryInvokeComponent(component.Type, token => instance.StartAsync(context, token), reports)) + if ( + !TryInvokeComponent( + component.Type, + token => instance.StartAsync(context, token), + reports + ) + ) { ok = false; break; @@ -434,7 +471,8 @@ public bool StartComponents( TryInvokeComponent( started[i].GetType().FullName ?? started[i].GetType().Name, started[i].StopAsync, - reports); + reports + ); } started.Clear(); @@ -491,7 +529,8 @@ public void StopComponents() private bool TryInvokeComponent( string name, Func call, - List reports) + List reports + ) { using var budget = new CancellationTokenSource(); if (_componentStopTimeout != Timeout.InfiniteTimeSpan) @@ -525,29 +564,44 @@ public void LoadAll() { lock (_gate) { - foreach (var package in DependencyGraph.Resolve(ManifestReader.Scan(_pluginsRoot, reports.Add), reports.Add)) + foreach ( + var package in DependencyGraph.Resolve( + ManifestReader.Scan(_pluginsRoot, reports.Add), + reports.Add + ) + ) { if (_slots.ContainsKey(package.Manifest.Name)) { continue; } - var missing = package.Manifest.Dependencies - .Where(dependency => dependency.Name != PluginContractInfo.ParentName) - .Where(dependency => !_slots.TryGetValue(dependency.Name, out var slot) - || slot.State != PluginState.Loaded) + var missing = package + .Manifest.Dependencies.Where(dependency => + dependency.Name != PluginContractInfo.ParentName + ) + .Where(dependency => + !_slots.TryGetValue(dependency.Name, out var slot) + || slot.State != PluginState.Loaded + ) .Select(dependency => dependency.Name) .ToArray(); if (missing.Length > 0) { - reports.Add(CoreText.Get( - "Manager_DependenciesNotLoaded", - package.Manifest.Name, - string.Join(", ", missing))); + reports.Add( + CoreText.Get( + "Manager_DependenciesNotLoaded", + package.Manifest.Name, + string.Join(", ", missing) + ) + ); continue; } - if (LoadOne(package, enable: true, reports, out var late) && late is { } lateFault) + if ( + LoadOne(package, enable: true, reports, out var late) + && late is { } lateFault + ) { lateFaults.Add(lateFault); } @@ -597,10 +651,13 @@ public bool Load(string packageDirectory) } else { - reports.Add(CoreText.Get( - "Manager_AlreadyRegistered", - package.Manifest.Name, - slot.State)); + reports.Add( + CoreText.Get( + "Manager_AlreadyRegistered", + package.Manifest.Name, + slot.State + ) + ); result = false; } } @@ -629,7 +686,8 @@ public bool Load(string packageDirectory) // 父级的日志回调可能拿父级的锁;出了 _gate 再写,避免与卸载路径互相等。 if (reusedLoader is not null) { - _loggerFactory.CreateLogger("Hosihikari") + _loggerFactory + .CreateLogger("Hosihikari") .LogInformation("{Message}", CoreText.Get("Manager_LoaderReused", reusedLoader)); } @@ -684,7 +742,8 @@ public bool Disable(string name) return result; } - private static string VerbText(bool enable) => CoreText.Get(enable ? "Verb_Enable" : "Verb_Disable"); + private static string VerbText(bool enable) => + CoreText.Get(enable ? "Verb_Enable" : "Verb_Disable"); /// /// 把钩子投到线程池再等。装着服务端线程 SynchronizationContext 时,直接在服务端线程上 @@ -701,7 +760,8 @@ private bool TryInvokeHook( string hook, Func> call, List reports, - out T result) + out T result + ) where T : struct { var name = slot.Manifest.Name; @@ -726,9 +786,11 @@ private bool TryInvokeHook( catch (OperationCanceledException) { // 预算到点与钩子自己取消是同一种结局:不再等它(FX-0059 / 0063)。 - reports.Add(budget.IsCancellationRequested - ? CoreText.Get("Manager_HookTimeout", name, hook, _hookTimeout) - : CoreText.Get("Manager_HookCanceled", name, hook)); + reports.Add( + budget.IsCancellationRequested + ? CoreText.Get("Manager_HookTimeout", name, hook, _hookTimeout) + : CoreText.Get("Manager_HookCanceled", name, hook) + ); result = default; return false; } @@ -747,7 +809,8 @@ private bool TryInvokeHook( Slot slot, string hook, Func call, - List reports) => + List reports + ) => TryInvokeHook( slot, hook, @@ -757,7 +820,8 @@ private bool TryInvokeHook( return true; }, reports, - out _); + out _ + ); /// /// 在专起的一根线程上跑钩子,而不是 。 @@ -768,7 +832,9 @@ private bool TryInvokeHook( /// private static Task RunOffPool(Func> call) { - var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously + ); var thread = new Thread(() => { try @@ -780,27 +846,30 @@ private static Task RunOffPool(Func> call) return; } - pending.AsTask().ContinueWith( - static (finished, state) => - { - var target = (TaskCompletionSource)state!; - if (finished.IsCompletedSuccessfully) + pending + .AsTask() + .ContinueWith( + static (finished, state) => { - target.TrySetResult(finished.Result); - } - else if (finished.IsCanceled) - { - target.TrySetCanceled(); - } - else - { - target.TrySetException(finished.Exception!); - } - }, - completion, - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); + var target = (TaskCompletionSource)state!; + if (finished.IsCompletedSuccessfully) + { + target.TrySetResult(finished.Result); + } + else if (finished.IsCanceled) + { + target.TrySetCanceled(); + } + else + { + target.TrySetException(finished.Exception!); + } + }, + completion, + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default + ); } catch (Exception ex) { @@ -838,7 +907,8 @@ private bool DriveHook( bool enable, ref List? reports, out Slot? faulted, - out PluginDiagnostic? fault) + out PluginDiagnostic? fault + ) { fault = null; faulted = null; @@ -855,7 +925,9 @@ private bool DriveHook( // 从没启用过的插件收到停用仍会调一次 OnDisable —— 父级就是这么驱动新交付的包的。 if (enable ? slot.Enabled : slot.Stopped) { - (reports ??= []).Add(CoreText.Get(enable ? "Manager_AlreadyEnabled" : "Manager_AlreadyDisabled", name)); + (reports ??= []).Add( + CoreText.Get(enable ? "Manager_AlreadyEnabled" : "Manager_AlreadyDisabled", name) + ); return true; } @@ -873,7 +945,12 @@ private bool DriveHook( if (enable) { var enabled = TryInvokeHook( - slot, "OnEnable", slot.Handle!.Plugin!.OnEnable, reportList, out var enableResult); + slot, + "OnEnable", + slot.Handle!.Plugin!.OnEnable, + reportList, + out var enableResult + ); // 钩子里报的故障(本线程或别的线程)与抛错同级:交给调用方在锁外卸掉。 if (TakePendingFault(slot.Id) is { } enableFault) { @@ -890,10 +967,13 @@ private bool DriveHook( if (!enableResult.Allowed) { - reportList.Add(CoreText.Get( - "Manager_EnableRefused", - name, - enableResult.Reason ?? CoreText.Get("Common_NoReason"))); + reportList.Add( + CoreText.Get( + "Manager_EnableRefused", + name, + enableResult.Reason ?? CoreText.Get("Common_NoReason") + ) + ); return false; } @@ -912,7 +992,12 @@ private bool DriveHook( } var stopped = TryInvokeHook( - slot, "OnDisable", slot.Handle!.Plugin!.OnDisable, reportList, out var disableResult); + slot, + "OnDisable", + slot.Handle!.Plugin!.OnDisable, + reportList, + out var disableResult + ); if (TakePendingFault(slot.Id) is { } disableFault) { // 已经停下就继续按停用算账;故障本身交给调用方卸掉。 @@ -936,15 +1021,16 @@ private bool DriveHook( { scope.Open(); } - catch (ObjectDisposedException) - { - } + catch (ObjectDisposedException) { } } - reportList.Add(CoreText.Get( - "Manager_DisableRefused", - name, - disableResult.Reason ?? CoreText.Get("Common_NoReason"))); + reportList.Add( + CoreText.Get( + "Manager_DisableRefused", + name, + disableResult.Reason ?? CoreText.Get("Common_NoReason") + ) + ); return false; } @@ -954,16 +1040,20 @@ private bool DriveHook( } catch (Exception ex) { - (reports ??= []).Add(CoreText.Get( - enable ? "Manager_EnableThrew" : "Manager_DisableThrew", - name, - ex.Demystify())); + (reports ??= []).Add( + CoreText.Get( + enable ? "Manager_EnableThrew" : "Manager_DisableThrew", + name, + ex.Demystify() + ) + ); faulted = slot; // 不带 Exception:异常对象攥着 MethodBase,会经诊断把插件的 ALC 钉住,回收验证过不去。 // 栈已经进了报告文本(Demystify),可读性不损失。 fault = PluginDiagnostic.Error( enable ? "enable-threw" : "disable-threw", - CoreText.Get(enable ? "Manager_EnableFault" : "Manager_DisableFault")); + CoreText.Get(enable ? "Manager_EnableFault" : "Manager_DisableFault") + ); return false; } } @@ -1012,7 +1102,9 @@ public ReloadResult Reload(string name) var unloaded = Unload(name); if (!unloaded.Released) { - return ReloadResult.Failed(unloaded.Error ?? CoreText.Get("Manager_ReloadUnloadFailed", name)); + return ReloadResult.Failed( + unloaded.Error ?? CoreText.Get("Manager_ReloadUnloadFailed", name) + ); } if (!Load(Path.Combine(_pluginsRoot, name))) @@ -1038,7 +1130,10 @@ public ReloadResult Reload(string name) continue; } - if (!_slots.TryGetValue(dependency.Name, out var slot) || slot.State != PluginState.Loaded) + if ( + !_slots.TryGetValue(dependency.Name, out var slot) + || slot.State != PluginState.Loaded + ) { return CoreText.Get("Manager_DependencyNotLoaded", dependency.Name); } @@ -1096,7 +1191,11 @@ internal void UnloadChildren() /// 而父级线程可能正握着那把锁等 ;在锁内回调会互相等死。 /// 钩子与回收验证各有一段预算(FX-0063);前者超时只在结果上标注,后者超时才是失败。 /// - private UnloadResult UnloadCore(string name, Guid? expectedInstanceId, ref List? reports) + private UnloadResult UnloadCore( + string name, + Guid? expectedInstanceId, + ref List? reports + ) { Slot slot; Task verification; @@ -1104,8 +1203,10 @@ private UnloadResult UnloadCore(string name, Guid? expectedInstanceId, ref List< var hookThrew = false; lock (_gate) { - if (!_slots.TryGetValue(name, out slot!) - || (expectedInstanceId is { } expected && slot.Id != expected)) + if ( + !_slots.TryGetValue(name, out slot!) + || (expectedInstanceId is { } expected && slot.Id != expected) + ) { return UnloadResult.Failed(CoreText.Get("Manager_NotLoaded", name)); } @@ -1118,7 +1219,8 @@ private UnloadResult UnloadCore(string name, Guid? expectedInstanceId, ref List< if (slot.State == PluginState.Loaded) { - var dependents = _slots.Values + var dependents = _slots + .Values // 待回收的插件已经放下实例,重试时仍要依赖在场,所以也算。 .Where(loaded => loaded.State is PluginState.Loaded or PluginState.Detached) .Where(p => p.Manifest.Dependencies.Any(d => d.Name == name)) @@ -1127,7 +1229,8 @@ private UnloadResult UnloadCore(string name, Guid? expectedInstanceId, ref List< if (dependents.Length > 0) { return UnloadResult.Failed( - CoreText.Get("Manager_HasDependents", string.Join(", ", dependents))); + CoreText.Get("Manager_HasDependents", string.Join(", ", dependents)) + ); } var refusal = Detach(slot, ref reports, out hookTimedOut, out hookThrew); @@ -1135,7 +1238,8 @@ private UnloadResult UnloadCore(string name, Guid? expectedInstanceId, ref List< { return UnloadResult.Failed( CoreText.Get("Manager_DisableRefusedByPlugin", name, refusal), - UnloadFailure.HookRefused); + UnloadFailure.HookRefused + ); } // 钩子超时只是那一段不再等;回收验证照常进行,结局如实标注是哪一段超的。 @@ -1144,8 +1248,7 @@ private UnloadResult UnloadCore(string name, Guid? expectedInstanceId, ref List< if (slot.State != PluginState.Detached) { - return UnloadResult.Failed( - CoreText.Get("Manager_StateAnomaly", name, slot.State)); + return UnloadResult.Failed(CoreText.Get("Manager_StateAnomaly", name, slot.State)); } if (slot.Verification is null) @@ -1163,21 +1266,22 @@ private UnloadResult UnloadCore(string name, Guid? expectedInstanceId, ref List< var timedOut = false; try { - released = _unloadVerificationTimeout == Timeout.InfiniteTimeSpan - ? verification.GetAwaiter().GetResult() - : verification.WaitAsync(_unloadVerificationTimeout).GetAwaiter().GetResult(); + released = + _unloadVerificationTimeout == Timeout.InfiniteTimeSpan + ? verification.GetAwaiter().GetResult() + : verification.WaitAsync(_unloadVerificationTimeout).GetAwaiter().GetResult(); } catch (TimeoutException) { (reports ??= []).Add( - CoreText.Get("Manager_UnloadTimeout", name, _unloadVerificationTimeout)); + CoreText.Get("Manager_UnloadTimeout", name, _unloadVerificationTimeout) + ); released = false; timedOut = true; } catch (Exception ex) { - (reports ??= []).Add( - CoreText.Get("Manager_UnloadVerifyThrew", name, ex.Demystify())); + (reports ??= []).Add(CoreText.Get("Manager_UnloadVerifyThrew", name, ex.Demystify())); released = false; } @@ -1207,15 +1311,19 @@ private UnloadResult UnloadCore(string name, Guid? expectedInstanceId, ref List< { return UnloadResult.Failed( CoreText.Get("Manager_UnloadTimeoutRetry", name, _unloadVerificationTimeout), - hookTimedOut ? UnloadFailure.HookAndReclamationTimedOut : UnloadFailure.ReclamationTimedOut, - hookTimedOut); + hookTimedOut + ? UnloadFailure.HookAndReclamationTimedOut + : UnloadFailure.ReclamationTimedOut, + hookTimedOut + ); } // 说"回收"而不是"ALC":释放句柄长什么样是 Loader 自己的事(FX-0010)。 return UnloadResult.Failed( CoreText.Get("Manager_UnloadVerifyFailedRetry", name), hookThrew ? UnloadFailure.HookThrew : UnloadFailure.ReclamationFailed, - hookTimedOut); + hookTimedOut + ); } } @@ -1269,9 +1377,11 @@ internal void ReportFault(string name, Guid instanceId, PluginDiagnostic diagnos var present = false; lock (_gate) { - if (_slots.TryGetValue(name, out var current) + if ( + _slots.TryGetValue(name, out var current) && current.Id == instanceId - && current.State == PluginState.Loaded) + && current.State == PluginState.Loaded + ) { present = true; (reports ??= []).Add(Describe("Manager_Fault", name, diagnostic)); @@ -1296,12 +1406,16 @@ internal void ReportFault(string name, Guid instanceId, PluginDiagnostic diagnos } else { - _reportFault(CoreText.Get( - "Manager_FaultUnloadIncomplete", - name, - result.Error ?? CoreText.Get("Common_Unknown"))); + _reportFault( + CoreText.Get( + "Manager_FaultUnloadIncomplete", + name, + result.Error ?? CoreText.Get("Common_Unknown") + ) + ); } } + /// /// 停用、卸载、放下句柄与作用域,只留下回收验证。单独一个不内联的方法,是为了让本方法返回后, /// 插件与它的 ALC 在栈上再无强引用 —— 回收验证的前提(FX-0023)。 @@ -1309,7 +1423,12 @@ internal void ReportFault(string name, Guid instanceId, PluginDiagnostic diagnos /// 停用被拒绝时返回原因,此时什么都不放开(FX-0030)。 /// [MethodImpl(MethodImplOptions.NoInlining)] - private string? Detach(Slot slot, ref List? reports, out bool hookTimedOut, out bool hookThrew) + private string? Detach( + Slot slot, + ref List? reports, + out bool hookTimedOut, + out bool hookThrew + ) { var name = slot.Manifest.Name; var handle = slot.Handle!; @@ -1327,7 +1446,15 @@ internal void ReportFault(string name, Guid instanceId, PluginDiagnostic diagnos { // 闸门在世界里已经关了,作用域照常关闭即可。 } - else if (!TryInvokeHook(slot, "OnDisable", plugin.OnDisable, reportList, out var disableResult)) + else if ( + !TryInvokeHook( + slot, + "OnDisable", + plugin.OnDisable, + reportList, + out var disableResult + ) + ) { // 超时只是不再等它:闸门保持关闭,停用按已发生记账,卸载继续(FX-0063)。 hookTimedOut = true; @@ -1416,15 +1543,19 @@ private void PublishState(string name, PluginState previous, PluginState current } catch (Exception ex) { - _loggerFactory.CreateLogger("Hosihikari.Events").LogError( - ex, - "{Message}", - CoreText.Get("Manager_StatePublishFailed", name)); + _loggerFactory + .CreateLogger("Hosihikari.Events") + .LogError( + ex, + "{Message}", + CoreText.Get("Manager_StatePublishFailed", name) + ); } }, CancellationToken.None, TaskContinuationOptions.None, - TaskScheduler.Default); + TaskScheduler.Default + ); } } @@ -1449,7 +1580,8 @@ private bool LoadOne( PluginPackage package, bool enable, List reports, - out (string Name, Guid Id, PluginDiagnostic Fault)? lateFault) + out (string Name, Guid Id, PluginDiagnostic Fault)? lateFault + ) { lateFault = null; var manifest = package.Manifest; @@ -1485,7 +1617,8 @@ private bool LoadOne( catch (Exception ex) { reports.Add( - CoreText.Get("Manager_DiagnosticsThrew", manifest.Name, ex.Demystify())); + CoreText.Get("Manager_DiagnosticsThrew", manifest.Name, ex.Demystify()) + ); return false; } @@ -1494,7 +1627,8 @@ private bool LoadOne( foreach (var problem in problems) { reports.Add( - $"{manifest.Name}: [{problem.Code}/{problem.Severity}] {problem.Message}"); + $"{manifest.Name}: [{problem.Code}/{problem.Severity}] {problem.Message}" + ); } return false; @@ -1516,7 +1650,8 @@ private bool LoadOne( this, slot.Id, isLoader, - reports.Add); + reports.Add + ); // 加载器与插件钩子拿到同一份视图:普通包的 OnLoad 也不能转成 ILoaderContext(FX-0059)。 var pluginContext = context.ForPlugin(); @@ -1529,11 +1664,14 @@ private bool LoadOne( var plugin = handle.Plugin; loadStarted = true; - if (!TryInvokeHook( + if ( + !TryInvokeHook( slot, "OnLoad", token => plugin.OnLoad(pluginContext, token), - reports)) + reports + ) + ) { // 取消或超时都按装载回滚处理(FX-0059),下面的 finally 收起已经跑过的部分。 return false; @@ -1548,21 +1686,21 @@ private bool LoadOne( if (enable) { enableStarted = true; - if (!TryInvokeHook( - slot, - "OnEnable", - plugin.OnEnable, - reports, - out var enableResult)) + if ( + !TryInvokeHook(slot, "OnEnable", plugin.OnEnable, reports, out var enableResult) + ) { // 自持态在装载里顺带启用:超时保持停用、仍算装上(FX-0059)。 } else if (!enableResult.Allowed) { - reports.Add(CoreText.Get( - "Manager_EnableRefusedStaysLoaded", - manifest.Name, - enableResult.Reason ?? CoreText.Get("Common_NoReason"))); + reports.Add( + CoreText.Get( + "Manager_EnableRefusedStaysLoaded", + manifest.Name, + enableResult.Reason ?? CoreText.Get("Common_NoReason") + ) + ); } else { @@ -1589,8 +1727,7 @@ private bool LoadOne( } catch (Exception ex) { - reports.Add( - CoreText.Get("Manager_LoadThrewRolledBack", manifest.Name, ex.Demystify())); + reports.Add(CoreText.Get("Manager_LoadThrewRolledBack", manifest.Name, ex.Demystify())); return false; } finally @@ -1621,10 +1758,13 @@ private bool LoadOne( { if (enableStarted) { - CleanupHook("OnDisable", async token => - { - await handle!.Plugin!.OnDisable(token).ConfigureAwait(false); - }); + CleanupHook( + "OnDisable", + async token => + { + await handle!.Plugin!.OnDisable(token).ConfigureAwait(false); + } + ); } if (loadStarted) @@ -1656,7 +1796,8 @@ void CleanupHook(string hook, Func cleanup) catch (Exception ex) { reports.Add( - CoreText.Get("Manager_LoadRollbackThrew", manifest.Name, ex.Demystify())); + CoreText.Get("Manager_LoadRollbackThrew", manifest.Name, ex.Demystify()) + ); } // 回滚钩子里报的故障同样进待报账;这里不取就再没人取(Codex 指出)。 @@ -1675,7 +1816,8 @@ void Cleanup(Action cleanup) catch (Exception ex) { reports.Add( - CoreText.Get("Manager_LoadRollbackThrew", manifest.Name, ex.Demystify())); + CoreText.Get("Manager_LoadRollbackThrew", manifest.Name, ex.Demystify()) + ); } } } diff --git a/src/PluginScope.cs b/src/PluginScope.cs index 353b1ff..62351c1 100644 --- a/src/PluginScope.cs +++ b/src/PluginScope.cs @@ -8,8 +8,11 @@ namespace Hosihikari.Internal; /// 卸载验证永远过不去 —— 而且订阅当时毫无异样,只有卸载时才暴露(FX-0004)。 /// 框架知道是哪一次订阅属于哪个插件,就不该把这件事留给作者自觉。 /// -internal sealed class PluginScope(IEventBus events, IScheduler scheduler, PluginServiceRegistry registry) - : IEventBus, IScheduler, IPluginServiceRegistry +internal sealed class PluginScope( + IEventBus events, + IScheduler scheduler, + PluginServiceRegistry registry +) : IEventBus, IScheduler, IPluginServiceRegistry { private readonly Lock _gate = new(); private readonly HashSet _owned = []; @@ -17,14 +20,22 @@ internal sealed class PluginScope(IEventBus events, IScheduler scheduler, Plugin private volatile bool _enabled; private bool _released; - public IDisposable Subscribe(Action handler, EventPriority priority = EventPriority.Normal) => - Track(() => events.Subscribe(@event => - { - if (_enabled) - { - handler(@event); - } - }, priority)); + public IDisposable Subscribe( + Action handler, + EventPriority priority = EventPriority.Normal + ) => + Track(() => + events.Subscribe( + @event => + { + if (_enabled) + { + handler(@event); + } + }, + priority + ) + ); public void Publish(TEvent @event) => events.Publish(@event); @@ -36,25 +47,30 @@ public IDisposable ScheduleOnce(TimeSpan delay, Action work) var completed = false; Handle? handle = null; - var tracked = Track(() => scheduler.ScheduleOnce(delay, () => - { - try - { - if (_enabled) - { - work(); - } - } - finally - { - lock (gate) + var tracked = Track(() => + scheduler.ScheduleOnce( + delay, + () => { - completed = true; - handle?.Dispose(); - handle = null; + try + { + if (_enabled) + { + work(); + } + } + finally + { + lock (gate) + { + completed = true; + handle?.Dispose(); + handle = null; + } + } } - } - })); + ) + ); lock (gate) { @@ -70,15 +86,21 @@ public IDisposable ScheduleOnce(TimeSpan delay, Action work) } public IDisposable SchedulePeriodic(TimeSpan interval, Action work) => - Track(() => scheduler.SchedulePeriodic(interval, () => - { - if (_enabled) - { - work(); - } - })); + Track(() => + scheduler.SchedulePeriodic( + interval, + () => + { + if (_enabled) + { + work(); + } + } + ) + ); - public bool Register(T service) where T : class + public bool Register(T service) + where T : class { lock (_gate) { @@ -93,7 +115,8 @@ public bool Register(T service) where T : class } } - public T? Get() where T : class => registry.Get(); + public T? Get() + where T : class => registry.Get(); /// 打开闸门:之后到达的事件与定时器回调才会交给插件(FX-0035)。 internal void Open() diff --git a/src/PluginServiceRegistry.cs b/src/PluginServiceRegistry.cs index 7532e9b..3eb739f 100644 --- a/src/PluginServiceRegistry.cs +++ b/src/PluginServiceRegistry.cs @@ -10,7 +10,8 @@ internal sealed class PluginServiceRegistry private readonly Dictionary _carrierServices = []; private readonly Lock _gate = new(); - internal bool Register(T service) where T : class + internal bool Register(T service) + where T : class { lock (_gate) { @@ -19,7 +20,8 @@ internal bool Register(T service) where T : class } } - internal T? Get() where T : class + internal T? Get() + where T : class { lock (_gate) { diff --git a/test/Bar/Bar.csproj b/test/Bar/Bar.csproj index 8e680f6..9102d5c 100644 --- a/test/Bar/Bar.csproj +++ b/test/Bar/Bar.csproj @@ -1,5 +1,4 @@  - net10.0 enable @@ -8,23 +7,34 @@ - + - + - - + + - diff --git a/test/Bar/BarPlugin.cs b/test/Bar/BarPlugin.cs index d3f5786..52ac363 100644 --- a/test/Bar/BarPlugin.cs +++ b/test/Bar/BarPlugin.cs @@ -17,13 +17,15 @@ public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationTo var conflicted = context.PluginServices.Register(this); File.WriteAllText( Path.Combine(context.DataDirectory, "peer.txt"), - $"{peer?.GetType().FullName ?? "(取不到)"} | 冲突登记={conflicted}"); + $"{peer?.GetType().FullName ?? "(取不到)"} | 冲突登记={conflicted}" + ); // 探针:Bar 这边的 Lib 是哪一份(FX-0026)。 var lib = typeof(Lib.Marker).Assembly; File.WriteAllText( Path.Combine(context.DataDirectory, "lib.txt"), - $"{lib.Location} | {System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(lib)?.Name}"); + $"{lib.Location} | {System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(lib)?.Name}" + ); return ValueTask.CompletedTask; } diff --git a/test/Bindings.Stub/Bindings.Stub.csproj b/test/Bindings.Stub/Bindings.Stub.csproj index 219643a..4e6b48a 100644 --- a/test/Bindings.Stub/Bindings.Stub.csproj +++ b/test/Bindings.Stub/Bindings.Stub.csproj @@ -1,5 +1,4 @@  - net10.0 enable @@ -10,13 +9,17 @@ - - + + - diff --git a/test/Foo/Foo.csproj b/test/Foo/Foo.csproj index a81c8ee..7f3f42a 100644 --- a/test/Foo/Foo.csproj +++ b/test/Foo/Foo.csproj @@ -1,5 +1,4 @@  - net10.0 enable @@ -8,29 +7,44 @@ - + - + - + - - + + - diff --git a/test/Foo/FooPlugin.cs b/test/Foo/FooPlugin.cs index 5ada485..b3e9ae8 100644 --- a/test/Foo/FooPlugin.cs +++ b/test/Foo/FooPlugin.cs @@ -27,21 +27,26 @@ public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationTo var lib = typeof(Lib.Marker).Assembly; File.WriteAllText( Path.Combine(context.DataDirectory, "lib.txt"), - $"{lib.Location} | {System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(lib)?.Name}"); + $"{lib.Location} | {System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(lib)?.Name}" + ); // 配置按「包内默认 → 包外覆盖」叠好交过来(FX-0018)。 File.WriteAllText( Path.Combine(context.DataDirectory, "greeting.txt"), - context.Configuration["greeting"] ?? "(没有)"); + context.Configuration["greeting"] ?? "(没有)" + ); // 一个 handler 故意抛,另一个照常收到 —— 隔离到 handler(FX-0014)。 context.Events.Subscribe(_ => throw new InvalidOperationException("故意抛出")); context.Events.Subscribe(payload => - File.WriteAllText(Path.Combine(context.DataDirectory, "heard.txt"), payload)); + File.WriteAllText(Path.Combine(context.DataDirectory, "heard.txt"), payload) + ); // 调度器跑在线程池上(FX-0007)。 - context.Scheduler.ScheduleOnce(TimeSpan.FromMilliseconds(50), () => - File.WriteAllText(Path.Combine(context.DataDirectory, "scheduled.txt"), "ran")); + context.Scheduler.ScheduleOnce( + TimeSpan.FromMilliseconds(50), + () => File.WriteAllText(Path.Combine(context.DataDirectory, "scheduled.txt"), "ran") + ); // 这两个句柄**故意不保存、不退订**:框架应当在卸载时自己收回(FX-0004)。 return ValueTask.CompletedTask; diff --git a/test/Lib/Lib.csproj b/test/Lib/Lib.csproj index 954f522..f76a3f9 100644 --- a/test/Lib/Lib.csproj +++ b/test/Lib/Lib.csproj @@ -1,10 +1,8 @@ - net10.0 enable enable Lib - diff --git a/test/NativeProbe/NativeProbe.csproj b/test/NativeProbe/NativeProbe.csproj index 4eeb9da..d929ae8 100644 --- a/test/NativeProbe/NativeProbe.csproj +++ b/test/NativeProbe/NativeProbe.csproj @@ -1,5 +1,4 @@  - net10.0 enable @@ -8,18 +7,29 @@ - + - + - - + + - diff --git a/test/NativeProbe/NativeProbePlugin.cs b/test/NativeProbe/NativeProbePlugin.cs index 1dfd6e3..b9407fd 100644 --- a/test/NativeProbe/NativeProbePlugin.cs +++ b/test/NativeProbe/NativeProbePlugin.cs @@ -1,5 +1,4 @@ using System.Runtime.InteropServices; - using Hosihikari; [assembly: EntryPoint] diff --git a/test/Reloadable/Reloadable.csproj b/test/Reloadable/Reloadable.csproj index 243b731..618a6f2 100644 --- a/test/Reloadable/Reloadable.csproj +++ b/test/Reloadable/Reloadable.csproj @@ -1,5 +1,4 @@  - net10.0 enable @@ -8,22 +7,37 @@ - + - + - + - - + + - diff --git a/test/Reloadable/ReloadablePlugin.cs b/test/Reloadable/ReloadablePlugin.cs index 1683e32..7c0c3f7 100644 --- a/test/Reloadable/ReloadablePlugin.cs +++ b/test/Reloadable/ReloadablePlugin.cs @@ -25,7 +25,10 @@ public ValueTask OnDisable(CancellationToken cancellationToken { if (_dataDirectory is { } directory) { - File.AppendAllText(Path.Combine(directory, "disable.log"), "disable" + Environment.NewLine); + File.AppendAllText( + Path.Combine(directory, "disable.log"), + "disable" + Environment.NewLine + ); } return ValueTask.FromResult(PluginHookResult.Allow()); diff --git a/test/Retained/Retained.csproj b/test/Retained/Retained.csproj index c4676c4..5a32cf1 100644 --- a/test/Retained/Retained.csproj +++ b/test/Retained/Retained.csproj @@ -1,5 +1,4 @@  - net10.0 enable @@ -8,22 +7,37 @@ - + - + - + - - + + - diff --git a/testing/Hosihikari.Testing.Smoke/Hosihikari.Testing.Smoke.csproj b/testing/Hosihikari.Testing.Smoke/Hosihikari.Testing.Smoke.csproj index 3d40541..a3bd853 100644 --- a/testing/Hosihikari.Testing.Smoke/Hosihikari.Testing.Smoke.csproj +++ b/testing/Hosihikari.Testing.Smoke/Hosihikari.Testing.Smoke.csproj @@ -1,5 +1,4 @@ - Exe net10.0 @@ -12,5 +11,4 @@ - diff --git a/testing/Hosihikari.Testing.Smoke/Program.cs b/testing/Hosihikari.Testing.Smoke/Program.cs index 0e6983c..0676dfc 100644 --- a/testing/Hosihikari.Testing.Smoke/Program.cs +++ b/testing/Hosihikari.Testing.Smoke/Program.cs @@ -17,15 +17,28 @@ using (var host = new PluginTestHost(probe, "Probe")) { host.RunLifecycle(); - checks.Add(("测试宿主拒绝越界的插件名", invalidHostRejected, invalidHostRejected ? "已拒绝" : "(没有拒绝)")); - checks.Add(( - "生命周期按 Load → Enable → Disable → Unload 驱动", - host.HookLog.SequenceEqual(["load", "enable", "disable", "unload"]), - string.Join(" → ", host.HookLog))); - checks.Add(( - "上下文给出包目录与数据目录", - Directory.Exists(host.Context.PackageDirectory) && Directory.Exists(host.Context.DataDirectory), - host.Context.PackageDirectory)); + checks.Add( + ( + "测试宿主拒绝越界的插件名", + invalidHostRejected, + invalidHostRejected ? "已拒绝" : "(没有拒绝)" + ) + ); + checks.Add( + ( + "生命周期按 Load → Enable → Disable → Unload 驱动", + host.HookLog.SequenceEqual(["load", "enable", "disable", "unload"]), + string.Join(" → ", host.HookLog) + ) + ); + checks.Add( + ( + "上下文给出包目录与数据目录", + Directory.Exists(host.Context.PackageDirectory) + && Directory.Exists(host.Context.DataDirectory), + host.Context.PackageDirectory + ) + ); checks.Add(("插件拿到上下文", probe.Context is not null, probe.Context?.Name ?? "(没有)")); var seen = 0; @@ -38,26 +51,40 @@ // 跨档:Lowest → Low → Normal → High → Highest → Monitor,同档按订阅顺序(FX-0060)。 var order = new List(); - foreach (var (priority, label) in new[] - { - (EventPriority.Monitor, "monitor"), - (EventPriority.Highest, "highest"), - (EventPriority.Normal, "normal"), - (EventPriority.Lowest, "lowest"), - (EventPriority.High, "high"), - (EventPriority.Low, "low"), - (EventPriority.Normal, "normal-2"), - (EventPriority.Monitor, "monitor-2"), - }) + foreach ( + var (priority, label) in new[] + { + (EventPriority.Monitor, "monitor"), + (EventPriority.Highest, "highest"), + (EventPriority.Normal, "normal"), + (EventPriority.Lowest, "lowest"), + (EventPriority.High, "high"), + (EventPriority.Low, "low"), + (EventPriority.Normal, "normal-2"), + (EventPriority.Monitor, "monitor-2"), + } + ) { host.Context.TestEvents.Subscribe(_ => order.Add(label), priority); } host.Context.TestEvents.Publish("order"); - checks.Add(( - "事件按档分发、同档按订阅顺序", - order.SequenceEqual(["lowest", "low", "normal", "normal-2", "high", "highest", "monitor", "monitor-2"]), - string.Join(" → ", order))); + checks.Add( + ( + "事件按档分发、同档按订阅顺序", + order.SequenceEqual([ + "lowest", + "low", + "normal", + "normal-2", + "high", + "highest", + "monitor", + "monitor-2", + ]), + string.Join(" → ", order) + ) + ); var badPriorityRefused = false; try @@ -69,13 +96,24 @@ badPriorityRefused = true; } - checks.Add(("越界档位抛 ArgumentOutOfRangeException", badPriorityRefused, - badPriorityRefused ? "已抛出" : "(没有抛)")); + checks.Add( + ( + "越界档位抛 ArgumentOutOfRangeException", + badPriorityRefused, + badPriorityRefused ? "已抛出" : "(没有抛)" + ) + ); var once = 0; host.Context.TestScheduler.ScheduleOnce(TimeSpan.Zero, () => once++); host.Context.TestScheduler.RunOnce(); - checks.Add(("一次性调度手动执行", once == 1 && host.Context.TestScheduler.PendingOnce == 0, $"once={once}")); + checks.Add( + ( + "一次性调度手动执行", + once == 1 && host.Context.TestScheduler.PendingOnce == 0, + $"once={once}" + ) + ); var periodic = 0; var cancel = host.Context.TestScheduler.SchedulePeriodic(TimeSpan.Zero, () => periodic++); @@ -88,13 +126,22 @@ var services = host.Context.TestServices; var first = services.Register(new ProbeService("first")); var duplicate = services.Register(new ProbeService("second")); - checks.Add(( - "服务注册先到先得", - first && !duplicate && services.Get()?.Name == "first", - services.Get()?.Name ?? "(没有)")); + checks.Add( + ( + "服务注册先到先得", + first && !duplicate && services.Get()?.Name == "first", + services.Get()?.Name ?? "(没有)" + ) + ); host.Context.ReportFault(PluginDiagnostic.Error("probe", "probe fault")); - checks.Add(("故障报告可检查", host.Context.Faults.Contains("probe fault"), string.Join(";", host.Context.Faults))); + checks.Add( + ( + "故障报告可检查", + host.Context.Faults.Contains("probe fault"), + string.Join(";", host.Context.Faults) + ) + ); } var refused = new RefusePlugin(); @@ -102,10 +149,13 @@ { host.Load(); var result = host.Enable(); - checks.Add(( - "拒绝启用保留原因", - !result.Allowed && result.Reason == "not now", - result.Reason ?? "(没有原因)")); + checks.Add( + ( + "拒绝启用保留原因", + !result.Allowed && result.Reason == "not now", + result.Reason ?? "(没有原因)" + ) + ); } var gate = new GatePlugin(); @@ -121,14 +171,20 @@ host.Unload(); host.Context.Events.Publish("unloaded"); - checks.Add(( - "启用闸门拦住启用前、停用后与卸载后的回调", - gate.Seen == 1 && gate.Scheduled == 1, - $"seen={gate.Seen} scheduled={gate.Scheduled}")); - checks.Add(( - "卸载释放插件登记的服务", - host.Context.TestServices.Get() is null, - host.Context.TestServices.Get()?.Name ?? "(已释放)")); + checks.Add( + ( + "启用闸门拦住启用前、停用后与卸载后的回调", + gate.Seen == 1 && gate.Scheduled == 1, + $"seen={gate.Seen} scheduled={gate.Scheduled}" + ) + ); + checks.Add( + ( + "卸载释放插件登记的服务", + host.Context.TestServices.Get() is null, + host.Context.TestServices.Get()?.Name ?? "(已释放)" + ) + ); } var thrower = new ThrowUnloadPlugin(); @@ -146,10 +202,13 @@ threw = true; } - checks.Add(( - "OnUnload 抛出仍释放作用域", - threw && host.Context.TestServices.Get() is null, - $"threw={threw} service={host.Context.TestServices.Get()?.Name ?? "已释放"}")); + checks.Add( + ( + "OnUnload 抛出仍释放作用域", + threw && host.Context.TestServices.Get() is null, + $"threw={threw} service={host.Context.TestServices.Get()?.Name ?? "已释放"}" + ) + ); } var unloadPublish = new UnloadPublishPlugin(); @@ -158,10 +217,9 @@ host.Load(); host.Enable(); host.Unload(); - checks.Add(( - "直接卸载时先关闸门再调 OnUnload", - unloadPublish.Seen == 0, - $"seen={unloadPublish.Seen}")); + checks.Add( + ("直接卸载时先关闸门再调 OnUnload", unloadPublish.Seen == 0, $"seen={unloadPublish.Seen}") + ); } using (var harness = new PluginManagerHarness()) @@ -192,14 +250,18 @@ "dependencies": [ { "name": "hosihikari" } ], "loader": "probe" } - """); + """ + ); var loaded = harness.Load("HarnessProbe"); var enabled = harness.Manager.Enable("HarnessProbe"); var unloaded = harness.Manager.Unload("HarnessProbe"); - checks.Add(( - "真实管理器辅助加载、启用并卸载", - loaded && enabled && unloaded.Released, - $"loaded={loaded} enabled={enabled} unloaded={unloaded.Released} {unloaded.Error} reports=[{string.Join(" | ", harness.Reports)}]")); + checks.Add( + ( + "真实管理器辅助加载、启用并卸载", + loaded && enabled && unloaded.Released, + $"loaded={loaded} enabled={enabled} unloaded={unloaded.Released} {unloaded.Error} reports=[{string.Join(" | ", harness.Reports)}]" + ) + ); } Console.WriteLine("=== Hosihikari.Testing 冒烟 ==="); @@ -241,7 +303,8 @@ public ValueTask OnDisable(CancellationToken cancellationToken sealed class RefusePlugin : IPlugin { - public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationToken) => ValueTask.CompletedTask; + public ValueTask OnLoad(IPluginContext context, CancellationToken cancellationToken) => + ValueTask.CompletedTask; public ValueTask OnEnable(CancellationToken cancellationToken) => ValueTask.FromResult(PluginHookResult.Refuse("not now")); @@ -320,10 +383,14 @@ public ValueTask OnUnload(CancellationToken cancellationToken) => sealed class ProbeLoader : IPluginLoader { public string Id => "probe"; + public bool CanLoad(PluginManifest manifest) => manifest.Loader == Id; - public PluginHandle? Load(PluginManifest manifest, string packageDirectory, IPluginContext context) => - new ProbeHandle(new ProbePlugin()); + public PluginHandle? Load( + PluginManifest manifest, + string packageDirectory, + IPluginContext context + ) => new ProbeHandle(new ProbePlugin()); } sealed class ProbeHandle(ProbePlugin plugin) : PluginHandle(plugin) diff --git a/testing/Hosihikari.Testing/Hosihikari.Testing.csproj b/testing/Hosihikari.Testing/Hosihikari.Testing.csproj index 6f7e9db..9a96853 100644 --- a/testing/Hosihikari.Testing/Hosihikari.Testing.csproj +++ b/testing/Hosihikari.Testing/Hosihikari.Testing.csproj @@ -1,5 +1,4 @@ - net10.0 enable @@ -41,5 +40,4 @@ - diff --git a/testing/Hosihikari.Testing/PluginManagerHarness.cs b/testing/Hosihikari.Testing/PluginManagerHarness.cs index 00c35f1..cc59cbf 100644 --- a/testing/Hosihikari.Testing/PluginManagerHarness.cs +++ b/testing/Hosihikari.Testing/PluginManagerHarness.cs @@ -14,7 +14,11 @@ public sealed class PluginManagerHarness : IDisposable public PluginManagerHarness(PluginManagerOptions? options = null) { - _root = Path.Combine(Path.GetTempPath(), "hosihikari-testing", Guid.NewGuid().ToString("N")); + _root = Path.Combine( + Path.GetTempPath(), + "hosihikari-testing", + Guid.NewGuid().ToString("N") + ); PluginsRoot = Path.Combine(_root, "plugins"); DataRoot = Path.Combine(_root, "data"); ConfigRoot = Path.Combine(_root, "config", "hosihikari"); @@ -29,7 +33,8 @@ public PluginManagerHarness(PluginManagerOptions? options = null) report => _reports.Enqueue(report), carrierServices: null, onRemoved: name => _removed.Enqueue(name), - options ?? new PluginManagerOptions()); + options ?? new PluginManagerOptions() + ); } public string Root => _root; @@ -44,22 +49,31 @@ public PluginManagerHarness(PluginManagerOptions? options = null) public string CreatePackage( string name, string manifestJson, - params (string Path, string Content)[] files) + params (string Path, string Content)[] files + ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentException.ThrowIfNullOrWhiteSpace(manifestJson); - if (Path.IsPathRooted(name) + if ( + Path.IsPathRooted(name) || name is "." or ".." - || name.IndexOfAny([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]) >= 0) + || name.IndexOfAny([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]) >= 0 + ) { - throw new ArgumentException("Test package name must be a single directory name", nameof(name)); + throw new ArgumentException( + "Test package name must be a single directory name", + nameof(name) + ); } var directory = Path.GetFullPath(Path.Combine(PluginsRoot, name)); var pluginRoot = Path.GetFullPath(PluginsRoot) + Path.DirectorySeparatorChar; if (!directory.StartsWith(pluginRoot, StringComparison.Ordinal)) { - throw new ArgumentException("Test package directory is outside the test root", nameof(name)); + throw new ArgumentException( + "Test package directory is outside the test root", + nameof(name) + ); } Directory.CreateDirectory(directory); @@ -67,10 +81,17 @@ public string CreatePackage( foreach (var (path, content) in files) { var target = Path.GetFullPath(Path.Combine(directory, path)); - if (!target.StartsWith(Path.GetFullPath(directory) + Path.DirectorySeparatorChar, StringComparison.Ordinal) - && !string.Equals(target, Path.GetFullPath(directory), StringComparison.Ordinal)) + if ( + !target.StartsWith( + Path.GetFullPath(directory) + Path.DirectorySeparatorChar, + StringComparison.Ordinal + ) && !string.Equals(target, Path.GetFullPath(directory), StringComparison.Ordinal) + ) { - throw new ArgumentException($"Test package path is outside the test root: {path}", nameof(files)); + throw new ArgumentException( + $"Test package path is outside the test root: {path}", + nameof(files) + ); } Directory.CreateDirectory(Path.GetDirectoryName(target)!); @@ -103,11 +124,7 @@ public void Dispose() Directory.Delete(_root, recursive: true); } } - catch (IOException) - { - } - catch (UnauthorizedAccessException) - { - } + catch (IOException) { } + catch (UnauthorizedAccessException) { } } } diff --git a/testing/Hosihikari.Testing/PluginTestHost.cs b/testing/Hosihikari.Testing/PluginTestHost.cs index d0874f3..8e16d13 100644 --- a/testing/Hosihikari.Testing/PluginTestHost.cs +++ b/testing/Hosihikari.Testing/PluginTestHost.cs @@ -17,7 +17,11 @@ public PluginTestHost(IPlugin plugin, string name = "TestPlugin") ArgumentException.ThrowIfNullOrWhiteSpace(name); Plugin = plugin; - _root = Path.Combine(Path.GetTempPath(), "hosihikari-testing", Guid.NewGuid().ToString("N")); + _root = Path.Combine( + Path.GetTempPath(), + "hosihikari-testing", + Guid.NewGuid().ToString("N") + ); Context = new TestPluginContext(name, _root); } @@ -46,7 +50,9 @@ public PluginHookResult Enable() Context.Scope.Open(); } - _hooks.Add(result.Allowed ? "enable" : $"enable:refused({result.Reason ?? "no reason given"})"); + _hooks.Add( + result.Allowed ? "enable" : $"enable:refused({result.Reason ?? "no reason given"})" + ); return result; } @@ -59,7 +65,9 @@ public PluginHookResult Disable() Context.Scope.Open(); } - _hooks.Add(result.Allowed ? "disable" : $"disable:refused({result.Reason ?? "no reason given"})"); + _hooks.Add( + result.Allowed ? "disable" : $"disable:refused({result.Reason ?? "no reason given"})" + ); return result; } @@ -84,13 +92,17 @@ public void RunLifecycle() var enabled = Enable(); if (!enabled.Allowed) { - throw new InvalidOperationException($"Enable refused: {enabled.Reason ?? "no reason given"}"); + throw new InvalidOperationException( + $"Enable refused: {enabled.Reason ?? "no reason given"}" + ); } var disabled = Disable(); if (!disabled.Allowed) { - throw new InvalidOperationException($"Disable refused: {disabled.Reason ?? "no reason given"}"); + throw new InvalidOperationException( + $"Disable refused: {disabled.Reason ?? "no reason given"}" + ); } Unload(); @@ -113,11 +125,7 @@ public void Dispose() Directory.Delete(_root, recursive: true); } } - catch (IOException) - { - } - catch (UnauthorizedAccessException) - { - } + catch (IOException) { } + catch (UnauthorizedAccessException) { } } } diff --git a/testing/Hosihikari.Testing/TestEventBus.cs b/testing/Hosihikari.Testing/TestEventBus.cs index aac9fac..2ca7454 100644 --- a/testing/Hosihikari.Testing/TestEventBus.cs +++ b/testing/Hosihikari.Testing/TestEventBus.cs @@ -9,20 +9,34 @@ namespace Hosihikari.Testing; public sealed class TestEventBus : IEventBus { private static readonly EventPriority[] Bands = - [EventPriority.Lowest, EventPriority.Low, EventPriority.Normal, EventPriority.High, EventPriority.Highest, EventPriority.Monitor]; + [ + EventPriority.Lowest, + EventPriority.Low, + EventPriority.Normal, + EventPriority.High, + EventPriority.Highest, + EventPriority.Monitor, + ]; private readonly Dictionary[]> _handlers = []; private readonly List _errors = []; public IReadOnlyList HandlerErrors => _errors; - public IDisposable Subscribe(Action handler, EventPriority priority = EventPriority.Normal) + public IDisposable Subscribe( + Action handler, + EventPriority priority = EventPriority.Normal + ) { ArgumentNullException.ThrowIfNull(handler); var bucket = Array.IndexOf(Bands, priority); if (bucket < 0) { - throw new ArgumentOutOfRangeException(nameof(priority), priority, "Unknown event priority"); + throw new ArgumentOutOfRangeException( + nameof(priority), + priority, + "Unknown event priority" + ); } if (!_handlers.TryGetValue(typeof(TEvent), out var buckets)) @@ -69,7 +83,8 @@ public void Publish(TEvent @event) } } - private static List[] CreateBuckets() => [.. Bands.Select(static _ => new List())]; + private static List[] CreateBuckets() => + [.. Bands.Select(static _ => new List())]; private sealed class Subscription(Action unsubscribe) : IDisposable { diff --git a/testing/Hosihikari.Testing/TestPluginContext.cs b/testing/Hosihikari.Testing/TestPluginContext.cs index e6eca8e..683b470 100644 --- a/testing/Hosihikari.Testing/TestPluginContext.cs +++ b/testing/Hosihikari.Testing/TestPluginContext.cs @@ -15,11 +15,16 @@ public TestPluginContext(string name, string root) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentException.ThrowIfNullOrWhiteSpace(root); - if (Path.IsPathRooted(name) + if ( + Path.IsPathRooted(name) || name is "." or ".." - || name.IndexOfAny([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]) >= 0) + || name.IndexOfAny([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]) >= 0 + ) { - throw new ArgumentException("Test plugin name must be a single directory name", nameof(name)); + throw new ArgumentException( + "Test plugin name must be a single directory name", + nameof(name) + ); } Name = name; diff --git a/testing/Hosihikari.Testing/TestPluginScope.cs b/testing/Hosihikari.Testing/TestPluginScope.cs index 78c8d02..9f251df 100644 --- a/testing/Hosihikari.Testing/TestPluginScope.cs +++ b/testing/Hosihikari.Testing/TestPluginScope.cs @@ -9,7 +9,8 @@ namespace Hosihikari.Testing; internal sealed class TestPluginScope( TestEventBus events, TestScheduler scheduler, - TestServiceRegistry registry) : IEventBus, IScheduler, IPluginServiceRegistry + TestServiceRegistry registry +) : IEventBus, IScheduler, IPluginServiceRegistry { private readonly object _gate = new(); private readonly HashSet _owned = []; @@ -17,14 +18,22 @@ internal sealed class TestPluginScope( private volatile bool _enabled; private bool _released; - public IDisposable Subscribe(Action handler, EventPriority priority = EventPriority.Normal) => - Track(() => events.Subscribe(@event => - { - if (_enabled) - { - handler(@event); - } - }, priority)); + public IDisposable Subscribe( + Action handler, + EventPriority priority = EventPriority.Normal + ) => + Track(() => + events.Subscribe( + @event => + { + if (_enabled) + { + handler(@event); + } + }, + priority + ) + ); public void Publish(TEvent @event) => events.Publish(@event); @@ -34,25 +43,30 @@ public IDisposable ScheduleOnce(TimeSpan delay, Action work) var completed = false; Handle? handle = null; - var tracked = Track(() => scheduler.ScheduleOnce(delay, () => - { - try - { - if (_enabled) - { - work(); - } - } - finally - { - lock (gate) + var tracked = Track(() => + scheduler.ScheduleOnce( + delay, + () => { - completed = true; - handle?.Dispose(); - handle = null; + try + { + if (_enabled) + { + work(); + } + } + finally + { + lock (gate) + { + completed = true; + handle?.Dispose(); + handle = null; + } + } } - } - })); + ) + ); lock (gate) { @@ -68,15 +82,21 @@ public IDisposable ScheduleOnce(TimeSpan delay, Action work) } public IDisposable SchedulePeriodic(TimeSpan interval, Action work) => - Track(() => scheduler.SchedulePeriodic(interval, () => - { - if (_enabled) - { - work(); - } - })); + Track(() => + scheduler.SchedulePeriodic( + interval, + () => + { + if (_enabled) + { + work(); + } + } + ) + ); - public bool Register(T service) where T : class + public bool Register(T service) + where T : class { lock (_gate) { @@ -91,7 +111,8 @@ public bool Register(T service) where T : class } } - public T? Get() where T : class => registry.Get(); + public T? Get() + where T : class => registry.Get(); internal void Open() { diff --git a/testing/Hosihikari.Testing/TestServiceRegistry.cs b/testing/Hosihikari.Testing/TestServiceRegistry.cs index afaac5c..da90803 100644 --- a/testing/Hosihikari.Testing/TestServiceRegistry.cs +++ b/testing/Hosihikari.Testing/TestServiceRegistry.cs @@ -7,14 +7,15 @@ public sealed class TestServiceRegistry : IPluginServiceRegistry { private readonly Dictionary _services = []; - public bool Register(T service) where T : class + public bool Register(T service) + where T : class { ArgumentNullException.ThrowIfNull(service); return _services.TryAdd(typeof(T), service); } - public T? Get() where T : class => - _services.TryGetValue(typeof(T), out var service) ? (T)service : null; + public T? Get() + where T : class => _services.TryGetValue(typeof(T), out var service) ? (T)service : null; internal bool Remove(Type type) => _services.Remove(type); } diff --git a/tools/Build/Hosihikari.Plugin.Build.csproj b/tools/Build/Hosihikari.Plugin.Build.csproj index d3c4004..b72ad3d 100644 --- a/tools/Build/Hosihikari.Plugin.Build.csproj +++ b/tools/Build/Hosihikari.Plugin.Build.csproj @@ -1,5 +1,4 @@  - net10.0 Hosihikari.Plugin.Build @@ -19,17 +18,25 @@ - - - - + + + + @@ -39,5 +46,4 @@ - diff --git a/tools/Build/build/Hosihikari.Plugin.Build.targets b/tools/Build/build/Hosihikari.Plugin.Build.targets index 5044c52..5dc75f1 100644 --- a/tools/Build/build/Hosihikari.Plugin.Build.targets +++ b/tools/Build/build/Hosihikari.Plugin.Build.targets @@ -1,34 +1,51 @@ - - $(MSBuildProjectDirectory)/dist + $(MSBuildProjectDirectory)/dist $(MSBuildThisFileDirectory)../tools/net10.0/Hosihikari.Plugin.Pack.dll - $(MSBuildProjectDirectory)/hosihikari.json + $(MSBuildProjectDirectory)/hosihikari.json $(IntermediateOutputPath)hosihikari/hosihikari.json - $(HosihikariGeneratedManifest) + $(HosihikariGeneratedManifest) - $(AssemblyName) - $(Version) - $(TargetFileName) - assembly - plugin - 3 - 1 + $(AssemblyName) + $(Version) + $(TargetFileName) + assembly + plugin + 3 + 1 - - + + - + <_HosihikariDependency Include="hosihikari" /> <_HosihikariDependency Include="$(HosihikariPluginDependencies)" /> @@ -53,16 +70,18 @@ File="$(HosihikariGeneratedManifest)" Lines="@(_HosihikariManifestLine)" Overwrite="true" - WriteOnlyWhenDifferent="true" /> + WriteOnlyWhenDifferent="true" + /> - + - diff --git a/tools/Build/buildMultiTargeting/Hosihikari.Plugin.Build.targets b/tools/Build/buildMultiTargeting/Hosihikari.Plugin.Build.targets index 9e64ae1..9dff0ad 100644 --- a/tools/Build/buildMultiTargeting/Hosihikari.Plugin.Build.targets +++ b/tools/Build/buildMultiTargeting/Hosihikari.Plugin.Build.targets @@ -1,5 +1,4 @@ - - diff --git a/tools/Pack/PackText.cs b/tools/Pack/PackText.cs index 837c6b2..16cb3e7 100644 --- a/tools/Pack/PackText.cs +++ b/tools/Pack/PackText.cs @@ -15,13 +15,13 @@ internal static class PackText { private const string ResourceBaseName = "Hosihikari.Plugin.Pack.Resources.PackStrings"; - private static readonly IStringLocalizer Localizer = - new ResourceManagerStringLocalizer( - new ResourceManager(ResourceBaseName, typeof(PackStrings).Assembly), - typeof(PackStrings).Assembly, - ResourceBaseName, - new ResourceNamesCache(), - NullLogger.Instance); + private static readonly IStringLocalizer Localizer = new ResourceManagerStringLocalizer( + new ResourceManager(ResourceBaseName, typeof(PackStrings).Assembly), + typeof(PackStrings).Assembly, + ResourceBaseName, + new ResourceNamesCache(), + NullLogger.Instance + ); internal static string Get(string key, params object[] arguments) => Localizer[key, arguments]; } diff --git a/tools/Pack/Packager.cs b/tools/Pack/Packager.cs index fc6bb0e..544b917 100644 --- a/tools/Pack/Packager.cs +++ b/tools/Pack/Packager.cs @@ -12,13 +12,21 @@ namespace Hosihikari.Internal.Pack; /// 是否成功。 /// 成功时的包目录。 /// 失败原因,逐条可读。 -public readonly record struct PackResult(bool Succeeded, string? PackageDirectory, IReadOnlyList Problems); +public readonly record struct PackResult( + bool Succeeded, + string? PackageDirectory, + IReadOnlyList Problems +); /// 一次 migrate 的结果。 /// 是否成功。 /// 失败原因,逐条可读。 /// 要人工补的字段。 -public readonly record struct MigrateResult(bool Succeeded, IReadOnlyList Problems, IReadOnlyList Notes); +public readonly record struct MigrateResult( + bool Succeeded, + IReadOnlyList Problems, + IReadOnlyList Notes +); /// /// 把一份构建输出 + 一份清单装配成插件包,并在这里检查那些**报错点离病因很远**的规则。 @@ -37,7 +45,8 @@ public static PackResult Pack( string sourceDirectory, string manifestPath, string outputRoot, - IReadOnlyList sharedLayer) + IReadOnlyList sharedLayer + ) { var problems = new List(); @@ -46,7 +55,8 @@ public static PackResult Pack( { manifest = JsonSerializer.Deserialize( File.ReadAllText(manifestPath), - new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + new JsonSerializerOptions { PropertyNameCaseInsensitive = true } + ); } catch (Exception ex) { @@ -60,9 +70,12 @@ public static PackResult Pack( } // name 直接参与包目录拼装,必须是一个目录名 —— 分隔符、. 与 .. 会跑出输出根。 - if (manifest.Name is "." or ".." - || manifest.Name.EndsWith('.') || manifest.Name.EndsWith(' ') - || manifest.Name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) + if ( + manifest.Name is "." or ".." + || manifest.Name.EndsWith('.') + || manifest.Name.EndsWith(' ') + || manifest.Name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 + ) { problems.Add(PackText.Get("InvalidName", manifest.Name)); return new PackResult(false, null, problems); @@ -91,36 +104,47 @@ public static PackResult Pack( } // 契约主版本(FX-0012)。 - if (manifest.EffectiveApiVersion?.ToString(CultureInfo.InvariantCulture) - != PluginContractInfo.CurrentApiVersion) + if ( + manifest.EffectiveApiVersion?.ToString(CultureInfo.InvariantCulture) + != PluginContractInfo.CurrentApiVersion + ) { - problems.Add(PackText.Get( - "ApiMismatch", - manifest.EffectiveApiVersion?.ToString(CultureInfo.InvariantCulture) - ?? PackText.Get("Undeclared"), - PluginContractInfo.CurrentApiVersion)); + problems.Add( + PackText.Get( + "ApiMismatch", + manifest.EffectiveApiVersion?.ToString(CultureInfo.InvariantCulture) + ?? PackText.Get("Undeclared"), + PluginContractInfo.CurrentApiVersion + ) + ); } // 清单 schema 版本(FX-0012)。 - if (manifest.EffectiveSchemaVersion?.ToString(CultureInfo.InvariantCulture) - != PluginContractInfo.CurrentManifestVersion) + if ( + manifest.EffectiveSchemaVersion?.ToString(CultureInfo.InvariantCulture) + != PluginContractInfo.CurrentManifestVersion + ) { - problems.Add(PackText.Get( - "ManifestVersionMismatch", - manifest.EffectiveSchemaVersion?.ToString(CultureInfo.InvariantCulture) - ?? PackText.Get("Undeclared"), - PluginContractInfo.CurrentManifestVersion)); + problems.Add( + PackText.Get( + "ManifestVersionMismatch", + manifest.EffectiveSchemaVersion?.ToString(CultureInfo.InvariantCulture) + ?? PackText.Get("Undeclared"), + PluginContractInfo.CurrentManifestVersion + ) + ); } // type 是父级的路由键(FX-0006)。写错的包在父级态下根本到不了我们手里, // 而且失败点离病因很远 —— 所以在这里就拦下。hosihikari.json 里可以省略。 - if (!string.IsNullOrWhiteSpace(manifest.ParentName) - && manifest.ParentName != PluginContractInfo.ParentName) + if ( + !string.IsNullOrWhiteSpace(manifest.ParentName) + && manifest.ParentName != PluginContractInfo.ParentName + ) { - problems.Add(PackText.Get( - "TypeMismatch", - PluginContractInfo.ParentName, - manifest.ParentName)); + problems.Add( + PackText.Get("TypeMismatch", PluginContractInfo.ParentName, manifest.ParentName) + ); } // 包类型(FX-0006):写错的在加载期会被当成插件,也在打包期拦。 @@ -136,9 +160,16 @@ public static PackResult Pack( // 对框架的依赖(FX-0006):缺了父级会把包排到垫片前面,判成 Unknown mod type。 // 载体包就是垫片自己,不依赖自己。 - if (kind != "carrier" + if ( + kind != "carrier" && !manifest.Dependencies.Any(dependency => - string.Equals(dependency?.Name, PluginContractInfo.ParentName, StringComparison.Ordinal))) + string.Equals( + dependency?.Name, + PluginContractInfo.ParentName, + StringComparison.Ordinal + ) + ) + ) { problems.Add(PackText.Get("MissingFrameworkDependency")); } @@ -204,7 +235,13 @@ public static PackResult Pack( try { Directory.CreateDirectory(staging); - foreach (var file in Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories)) + foreach ( + var file in Directory.EnumerateFiles( + sourceDirectory, + "*", + SearchOption.AllDirectories + ) + ) { var relative = Path.GetRelativePath(sourceDirectory, file); var target = Path.Combine(staging, relative); @@ -214,7 +251,10 @@ public static PackResult Pack( // 作者清单永远落成规范名:运行时只认 hosihikari.json,别的名字打出来的包装不上(Codex)。 File.Copy(manifestPath, Path.Combine(staging, ManifestFileName), overwrite: true); - File.WriteAllText(Path.Combine(staging, LegacyEnvelopeFileName), BuildEnvelope(manifest)); + File.WriteAllText( + Path.Combine(staging, LegacyEnvelopeFileName), + BuildEnvelope(manifest) + ); // 清单里声明的第三方包在**这里**还原 —— 供应链留在打包那一刻,服务端加载时不联网。 if (!RestorePackages(packages, staging, sharedLayer, problems)) @@ -258,7 +298,8 @@ public static PackResult Pack( private static List ReadPackages( PluginManifest manifest, string sourceDirectory, - List problems) + List problems + ) { var packages = new List(); if (manifest.Pack is { } pack) @@ -284,7 +325,11 @@ private static List ReadPackages( /// 跑 pack.prepack。字符串与数组都收(与 command 同形):字符串按单个程序名处理, /// 在包目录里执行,5 分钟不结束算失败(FX-0031)。装的是 node_modules、venv 这类构建期依赖。 /// - private static void Prepack(PluginManifest manifest, string sourceDirectory, List problems) + private static void Prepack( + PluginManifest manifest, + string sourceDirectory, + List problems + ) { if (manifest.Pack?.Prepack is not { } value) { @@ -299,9 +344,12 @@ private static void Prepack(PluginManifest manifest, string sourceDirectory, Lis else if (value.ValueKind == JsonValueKind.Array) { // 空字符串是合法参数(例如 `cmd /c ""`),只按类型过滤。 - command.AddRange(value.EnumerateArray() - .Where(item => item.ValueKind == JsonValueKind.String) - .Select(item => item.GetString()!)); + command.AddRange( + value + .EnumerateArray() + .Where(item => item.ValueKind == JsonValueKind.String) + .Select(item => item.GetString()!) + ); } if (command.Count == 0) @@ -347,7 +395,10 @@ private static void Prepack(PluginManifest manifest, string sourceDirectory, Lis } var remaining = deadline - Stopwatch.GetElapsedTime(started); - if (!Task.WhenAll(stdout, stderr).Wait(remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero)) + if ( + !Task.WhenAll(stdout, stderr) + .Wait(remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero) + ) { KillTree(process); problems.Add(PackText.Get("PrepackTimeout", PrepackTimeoutSeconds)); @@ -375,7 +426,8 @@ private static void KillTree(Process process) { process.Kill(entireProcessTree: true); } - catch (Exception ex) when (ex is InvalidOperationException or Win32Exception or NotSupportedException) + catch (Exception ex) + when (ex is InvalidOperationException or Win32Exception or NotSupportedException) { // 进程已经退出,或者平台不支持整棵树;这里只是尽力收尾。 } @@ -385,16 +437,19 @@ private static void ReadSourcePackages( string sourceDirectory, PluginManifest manifest, List packages, - List problems) + List problems + ) { var root = Path.GetFullPath(sourceDirectory); - var prefix = root.EndsWith(Path.DirectorySeparatorChar) ? root : root + Path.DirectorySeparatorChar; + var prefix = root.EndsWith(Path.DirectorySeparatorChar) + ? root + : root + Path.DirectorySeparatorChar; var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - var visited = new HashSet(OperatingSystem.IsWindows() - ? StringComparer.OrdinalIgnoreCase - : StringComparer.Ordinal); + var visited = new HashSet( + OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal + ); string Full(string path) { @@ -475,7 +530,9 @@ void Visit(string path) var fullBase = Path.Combine(root, baseDirectory); if (!Directory.Exists(fullBase)) { - problems.Add(PackText.Get("IncludeDirectoryMissing", path, include)); + problems.Add( + PackText.Get("IncludeDirectoryMissing", path, include) + ); continue; } @@ -524,7 +581,9 @@ private static string[] ExpandGlob(string packageRoot, string baseDirectory, str return Directory .EnumerateFiles(packageRoot, "*", SearchOption.AllDirectories) .Where(file => file.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)) - .Where(file => regex.IsMatch(Path.GetRelativePath(baseDirectory, file).Replace('\\', '/'))) + .Where(file => + regex.IsMatch(Path.GetRelativePath(baseDirectory, file).Replace('\\', '/')) + ) .OrderBy(file => file, StringComparer.Ordinal) .ToArray(); } @@ -576,14 +635,18 @@ private static bool RestorePackages( IReadOnlyList references, string packageDirectory, IReadOnlyList sharedLayer, - List problems) + List problems + ) { if (references.Count == 0) { return true; } - var workspace = Path.Combine(Path.GetTempPath(), "hosihikari-pack-" + Guid.NewGuid().ToString("N")); + var workspace = Path.Combine( + Path.GetTempPath(), + "hosihikari-pack-" + Guid.NewGuid().ToString("N") + ); try { Directory.CreateDirectory(workspace); @@ -595,20 +658,31 @@ private static bool RestorePackages( var parts = reference.Split('/', 2); var version = parts.Length > 1 ? parts[1] : "*"; return $" "; - })); + }) + ); var project = Path.Combine(workspace, "restore.csproj"); File.WriteAllText( project, - "" + Environment.NewLine - + " " + Environment.NewLine - + " net10.0" + Environment.NewLine - + " true" + Environment.NewLine - + " " + Environment.NewLine - + " " + Environment.NewLine - + items + Environment.NewLine - + " " + Environment.NewLine - + "" + Environment.NewLine); + "" + + Environment.NewLine + + " " + + Environment.NewLine + + " net10.0" + + Environment.NewLine + + " true" + + Environment.NewLine + + " " + + Environment.NewLine + + " " + + Environment.NewLine + + items + + Environment.NewLine + + " " + + Environment.NewLine + + "" + + Environment.NewLine + ); var output = Path.Combine(workspace, "out"); var start = new ProcessStartInfo("dotnet") @@ -616,7 +690,20 @@ private static bool RestorePackages( RedirectStandardOutput = true, RedirectStandardError = true, }; - foreach (var argument in new[] { "publish", project, "-c", "Release", "-o", output, "--nologo", "-v", "q" }) + foreach ( + var argument in new[] + { + "publish", + project, + "-c", + "Release", + "-o", + output, + "--nologo", + "-v", + "q", + } + ) { start.ArgumentList.Add(argument); } @@ -629,10 +716,9 @@ private static bool RestorePackages( var errorText = errorTask.Result; if (process.ExitCode != 0) { - problems.Add(PackText.Get( - "RestoreFailed", - string.Join(", ", references), - errorText.Trim())); + problems.Add( + PackText.Get("RestoreFailed", string.Join(", ", references), errorText.Trim()) + ); return false; } @@ -640,8 +726,12 @@ private static bool RestorePackages( // 递归复制是为了保留 runtimes//native 的本机资产(FX-0034)。 var restoreArtifacts = new HashSet(StringComparer.OrdinalIgnoreCase) { - "restore.dll", "restore.exe", "restore", "restore.pdb", - "restore.deps.json", "restore.runtimeconfig.json", + "restore.dll", + "restore.exe", + "restore", + "restore.pdb", + "restore.deps.json", + "restore.runtimeconfig.json", }; foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories)) { @@ -661,10 +751,7 @@ private static bool RestorePackages( } catch (Exception ex) { - problems.Add(PackText.Get( - "RestoreFailed", - string.Join(", ", references), - ex.Message)); + problems.Add(PackText.Get("RestoreFailed", string.Join(", ", references), ex.Message)); return false; } finally @@ -695,10 +782,15 @@ private static bool DeclaresEntryPoint(string entryPath, List problems) try { var full = Path.GetFullPath(entryPath); - var references = Directory.EnumerateFiles(Path.GetDirectoryName(full)!, "*.dll") + var references = Directory + .EnumerateFiles(Path.GetDirectoryName(full)!, "*.dll") // 契约不在构建输出里(复制进去会被这条规则自己拦下),所以显式补上。 .Append(typeof(PluginContractInfo).Assembly.Location) - .Concat(((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator)); + .Concat( + ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split( + Path.PathSeparator + ) + ); using var metadata = new MetadataLoadContext(new PathAssemblyResolver(references)); var inspection = metadata.LoadFromAssemblyPath(full); @@ -706,10 +798,7 @@ private static bool DeclaresEntryPoint(string entryPath, List problems) var declared = inspection.GetCustomAttributesData().Count(IsEntryPoint); if (declared != 1) { - problems.Add(PackText.Get( - "EntryCount", - Path.GetFileName(entryPath), - declared)); + problems.Add(PackText.Get("EntryCount", Path.GetFileName(entryPath), declared)); return false; } @@ -717,10 +806,7 @@ private static bool DeclaresEntryPoint(string entryPath, List problems) } catch (Exception ex) { - problems.Add(PackText.Get( - "EntryReadFailed", - Path.GetFileName(entryPath), - ex.Message)); + problems.Add(PackText.Get("EntryReadFailed", Path.GetFileName(entryPath), ex.Message)); return false; } } @@ -769,9 +855,16 @@ private static string BuildEnvelope(PluginManifest manifest) { writer.WriteStartObject(); writer.WriteString("name", PluginContractInfo.ParentName); - if (manifest.Dependencies.FirstOrDefault(dependency => - string.Equals(dependency?.Name, PluginContractInfo.ParentName, StringComparison.Ordinal)) - is { VersionRange: { Length: > 0 } parentRange }) + if ( + manifest.Dependencies.FirstOrDefault(dependency => + string.Equals( + dependency?.Name, + PluginContractInfo.ParentName, + StringComparison.Ordinal + ) + ) is + { VersionRange: { Length: > 0 } parentRange } + ) { writer.WriteString("version", parentRange); } @@ -781,9 +874,15 @@ private static string BuildEnvelope(PluginManifest manifest) foreach (var dependency in manifest.Dependencies) { - if (dependency is null + if ( + dependency is null || string.IsNullOrWhiteSpace(dependency.Name) - || string.Equals(dependency.Name, PluginContractInfo.ParentName, StringComparison.Ordinal)) + || string.Equals( + dependency.Name, + PluginContractInfo.ParentName, + StringComparison.Ordinal + ) + ) { continue; } @@ -812,7 +911,8 @@ private static string BuildEnvelope(PluginManifest manifest) private static void ValidateCarrier( PluginManifest manifest, string sourceDirectory, - List problems) + List problems + ) { if (manifest.Carrier is not { } carrier) { @@ -835,10 +935,15 @@ private static void ValidateCarrier( } var bootstrap = carrier.Bootstrap; - var hasBootstrap = bootstrap is not null - && (bootstrap.Assembly.Length > 0 || bootstrap.Type.Length > 0); - if (hasBootstrap - && (string.IsNullOrWhiteSpace(bootstrap!.Assembly) || string.IsNullOrWhiteSpace(bootstrap.Type))) + var hasBootstrap = + bootstrap is not null && (bootstrap.Assembly.Length > 0 || bootstrap.Type.Length > 0); + if ( + hasBootstrap + && ( + string.IsNullOrWhiteSpace(bootstrap!.Assembly) + || string.IsNullOrWhiteSpace(bootstrap.Type) + ) + ) { problems.Add(PackText.Get("CarrierBootstrapShape")); hasBootstrap = false; @@ -860,22 +965,34 @@ private static void ValidateCarrier( } // 只读元数据地看一遍,不把任何程序集装进可执行上下文。 - var references = Directory.EnumerateFiles(sourceDirectory, "*.dll", SearchOption.AllDirectories) + var references = Directory + .EnumerateFiles(sourceDirectory, "*.dll", SearchOption.AllDirectories) .Append(typeof(PluginContractInfo).Assembly.Location) .Append(typeof(ICarrierComponent).Assembly.Location) - .Concat(((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator)); + .Concat( + ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split( + Path.PathSeparator + ) + ); using var metadata = new MetadataLoadContext(new PathAssemblyResolver(references)); if (hasBootstrap) { - DeclaresCarrierBootstrap(metadata, Path.Combine(sourceDirectory, bootstrap!.Assembly), bootstrap, problems); + DeclaresCarrierBootstrap( + metadata, + Path.Combine(sourceDirectory, bootstrap!.Assembly), + bootstrap, + problems + ); } foreach (var component in carrier.Components) { - if (component is null + if ( + component is null || string.IsNullOrWhiteSpace(component.Assembly) - || string.IsNullOrWhiteSpace(component.Type)) + || string.IsNullOrWhiteSpace(component.Type) + ) { problems.Add(PackText.Get("CarrierComponentShape")); continue; @@ -926,7 +1043,12 @@ void Take(JsonElement item) if (item.GetString() is { } text) { // 1.x 允许一条字符串里写好几项:拆开、去空白、丢空项(Codex 指出)。 - foreach (var part in text.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + foreach ( + var part in text.Split( + ',', + StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries + ) + ) { packages.Add(part); } @@ -934,14 +1056,18 @@ void Take(JsonElement item) return; } } - else if (item.ValueKind == JsonValueKind.Object - && item.TryGetProperty("id", out var id) - && id.ValueKind == JsonValueKind.String - && id.GetString() is { Length: > 0 } name) + else if ( + item.ValueKind == JsonValueKind.Object + && item.TryGetProperty("id", out var id) + && id.ValueKind == JsonValueKind.String + && id.GetString() is { Length: > 0 } name + ) { - var version = item.TryGetProperty("version", out var raw) && raw.ValueKind == JsonValueKind.String - ? raw.GetString() - : null; + var version = + item.TryGetProperty("version", out var raw) + && raw.ValueKind == JsonValueKind.String + ? raw.GetString() + : null; packages.Add(string.IsNullOrEmpty(version) ? name : $"{name}/{version}"); return; } @@ -975,23 +1101,29 @@ private static bool IsInsidePackage(string sourceDirectory, string relative) var root = Path.GetFullPath(sourceDirectory); var full = Path.GetFullPath(Path.Combine(root, relative)); - return full.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) - || string.Equals(full, root, StringComparison.OrdinalIgnoreCase); + return full.StartsWith( + root + Path.DirectorySeparatorChar, + StringComparison.OrdinalIgnoreCase + ) || string.Equals(full, root, StringComparison.OrdinalIgnoreCase); } private static bool DeclaresCarrierBootstrap( MetadataLoadContext metadata, string assemblyPath, ManifestBootstrap bootstrap, - List problems) + List problems + ) { try { - var type = metadata.LoadFromAssemblyPath(Path.GetFullPath(assemblyPath)) + var type = metadata + .LoadFromAssemblyPath(Path.GetFullPath(assemblyPath)) .GetType(bootstrap.Type, throwOnError: false); if (type is null) { - problems.Add(PackText.Get("CarrierTypeMissing", bootstrap.Type, bootstrap.Assembly)); + problems.Add( + PackText.Get("CarrierTypeMissing", bootstrap.Type, bootstrap.Assembly) + ); return false; } @@ -1001,10 +1133,14 @@ private static bool DeclaresCarrierBootstrap( return false; } - if (type.ContainsGenericParameters + if ( + type.ContainsGenericParameters || type.GetConstructor( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, - Type.EmptyTypes) is null) + Type.EmptyTypes + ) + is null + ) { problems.Add(PackText.Get("CarrierTypeNotCreatable", bootstrap.Type)); return false; @@ -1020,25 +1156,26 @@ private static bool DeclaresCarrierBootstrap( } private static bool ImplementsConfigurator(Type type) => - type.GetInterfaces().Any(candidate => - candidate.FullName == typeof(ICarrierServicesConfigurator).FullName); + type.GetInterfaces() + .Any(candidate => candidate.FullName == typeof(ICarrierServicesConfigurator).FullName); private static bool DeclaresCarrierComponent( MetadataLoadContext metadata, string assemblyPath, ManifestCarrierComponent component, - List problems) + List problems + ) { try { - var type = metadata.LoadFromAssemblyPath(Path.GetFullPath(assemblyPath)) + var type = metadata + .LoadFromAssemblyPath(Path.GetFullPath(assemblyPath)) .GetType(component.Type, throwOnError: false); if (type is null) { - problems.Add(PackText.Get( - "CarrierTypeMissing", - component.Type, - component.Assembly)); + problems.Add( + PackText.Get("CarrierTypeMissing", component.Type, component.Assembly) + ); return false; } @@ -1051,10 +1188,14 @@ private static bool DeclaresCarrierComponent( } // 核心用无参构造函数装配:开泛型与没有公开无参构造的类型到运行期必然起不来(Copilot)。 - if (type.ContainsGenericParameters + if ( + type.ContainsGenericParameters || type.GetConstructor( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, - Type.EmptyTypes) is null) + Type.EmptyTypes + ) + is null + ) { problems.Add(PackText.Get("CarrierTypeNotCreatable", component.Type)); return false; @@ -1073,8 +1214,11 @@ private static bool ImplementsCarrierComponent(Type type) { for (var current = type; current is not null; current = current.BaseType) { - if (current.GetInterfaces().Any(candidate => - candidate.FullName == typeof(ICarrierComponent).FullName)) + if ( + current + .GetInterfaces() + .Any(candidate => candidate.FullName == typeof(ICarrierComponent).FullName) + ) { return true; } @@ -1111,7 +1255,8 @@ public static MigrateResult Migrate(string packageDirectory) { manifest = JsonSerializer.Deserialize( File.ReadAllText(legacyPath), - new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + new JsonSerializerOptions { PropertyNameCaseInsensitive = true } + ); } catch (JsonException ex) { @@ -1162,8 +1307,10 @@ private static string BuildManifest(PluginManifest manifest, List notes) writer.WriteString("loader", manifest.Loader); // 1.x 的 packageKind 改名成 kind(FX-0058)。 writer.WriteString("kind", manifest.PackageKind); - writer.WriteNumber("apiVersion", int.Parse( - PluginContractInfo.CurrentApiVersion, CultureInfo.InvariantCulture)); + writer.WriteNumber( + "apiVersion", + int.Parse(PluginContractInfo.CurrentApiVersion, CultureInfo.InvariantCulture) + ); if (manifest.Description is { } description) { @@ -1258,7 +1405,7 @@ private static bool IsSameOrUnder(string path, string root) ? normalizedRoot : normalizedRoot + Path.DirectorySeparatorChar; return string.Equals(normalizedPath, normalizedRoot, comparison) - || normalizedPath.StartsWith(prefix, comparison); + || normalizedPath.StartsWith(prefix, comparison); } /// 按名字认,因为在只读元数据里契约是另一套类型对象。 diff --git a/tools/Pack/Program.cs b/tools/Pack/Program.cs index dfda3be..80f0a39 100644 --- a/tools/Pack/Program.cs +++ b/tools/Pack/Program.cs @@ -144,7 +144,12 @@ static void PrintUsage() // Loader 包的装配:先按共享层清单剔除副本,再交给 Packager 做常规校验与复制。 // 共享清单 = 契约的基地清单 + 目标载体声明的那份(FX-0061);载体包用 --carrier 指定。 -static int PackLoader(string sourceDirectory, string manifestPath, string outputRoot, string? carrierDirectory) +static int PackLoader( + string sourceDirectory, + string manifestPath, + string outputRoot, + string? carrierDirectory +) { var shared = carrierDirectory is null ? AssemblyPluginLoader.SharedAssemblyFileNames @@ -153,7 +158,10 @@ static int PackLoader(string sourceDirectory, string manifestPath, string output .Select(name => Path.GetFileNameWithoutExtension(name)) .ToHashSet(StringComparer.OrdinalIgnoreCase); - var staging = Path.Combine(Path.GetTempPath(), "hosihikari-pack-" + Guid.NewGuid().ToString("N")); + var staging = Path.Combine( + Path.GetTempPath(), + "hosihikari-pack-" + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(staging); try { @@ -163,12 +171,16 @@ static int PackLoader(string sourceDirectory, string manifestPath, string output var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - var sourceRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(sourceDirectory)) + Path.DirectorySeparatorChar; + var sourceRoot = + Path.TrimEndingDirectorySeparator(Path.GetFullPath(sourceDirectory)) + + Path.DirectorySeparatorChar; var outputFull = Path.TrimEndingDirectorySeparator(Path.GetFullPath(outputRoot)); var skipRoot = outputFull.StartsWith(sourceRoot, comparison) ? outputFull + Path.DirectorySeparatorChar : null; - foreach (var file in Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories)) + foreach ( + var file in Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories) + ) { if (skipRoot is not null && Path.GetFullPath(file).StartsWith(skipRoot, comparison)) {