feat(cordis): 接入上下文组合与模组事务热替换

This commit is contained in:
2026-08-16 23:20:40 +08:00
commit ad256f109b
676 changed files with 52168 additions and 0 deletions
@@ -0,0 +1,40 @@
# ShrinkContext.AppAdapter
ShrinkApp ↔ ShrinkContext 的桥接层:把现有 `IShrinkAppModuleInstaller` 生态接入 Cordis 时空可组合性范式(阶段 2 过渡产物,方案见仓库根 `CORDIS_MIGRATION.md`)。
## 组成
| 类型 | 职责 |
|---|---|
| `ShrinkAppInstallerComponent` | 安装器 → 组件:`DependsOn` 映射为 `app.module.*` 注入键(依赖缺失**等待**而非抛错);发布模块键;apply = RegisterServices + InitializeAsync |
| `ShrinkAppLoaderHost` | 加载器驱动的 ShrinkApp 宿主:发现安装器(注入覆盖可测试)、经 `ShrinkContextLoader` 增量协调、`SetModuleDisabledAsync` 运行中按模块开关、`Active/WaitingModuleIds` 状态查询、启动发布 `ShrinkAppStartedEvent` |
| `ShrinkAppLoaderBootstrapper` | `hostingMode == ContextLoader` 时在 BeforeSceneLoad 自动创建常驻宿主,并把服务容器接回 `ShrinkApp.Services`Classic 模式完全不动 |
## 启用方式
`ShrinkAppSettings.hostingMode` 设为 `ContextLoader`(Inspector 或资产字段)。经典项目默认 `ClassicHost`,行为零变化。
```csharp
// 运行中按模块开关(宿主与其余模块不重启)
var host = ShrinkAppLoaderBootstrapper.Instance!.Host;
await host.SetModuleDisabledAsync("shrink.network", true);
```
## 行为差异(对照经典 ShrinkAppHost
| 场景 | ClassicHost | LoaderHost |
|---|---|---|
| 依赖缺失 | 排序期抛错 | 安装器保持 Waiting,依赖出现自动激活 |
| 重复 ModuleId | 宿主级异常 | 构造期抛错(一致);运行期替换退化为供给冲突失败 |
| 运行中禁用模块 | 不支持(需重启) | `SetModuleDisabledAsync` 增量协调,重启用会重新执行安装器初始化 |
| `ShrinkApp.IsRunning` | Host 驱动 | 以 `ShrinkAppLoaderHost.IsRunning` 为准(静态 IsRunning 为 false,过渡期已知差异) |
## 已知边界
- `ShrinkAppServices` 无注销能力:安装器停用不撤回已注册服务(重新启用会重跑 RegisterServices,同键覆盖)。
- 配置变化走条目重建而非组件自决 diff(`ShrinkContext.Core` 加载器原型语义)。
- 编排配置当前由代码构建条目;持久化配置资产(ScriptableObject/JSON)属后续切片。
## 测试
`Tests/` 覆盖:安装器组件 5 项(依赖等待/次序/供给冲突/退役/配置缺失)+ LoaderHost 6 项(启动事件、运行中开关、设置级初始禁用、未知模块、重复 ModuleId、Shutdown)。
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: db29c6e4804421b4392cb2ae3752790b
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b0b5a8bafa4a1464b8359913f50298b0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,62 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
using ShrinkApp;
namespace ShrinkContext.AppAdapter
{
/// <summary>
/// 把现有 <see cref="IShrinkAppModuleInstaller"/> 包装为 ShrinkContext 组件:
/// - inject 由 <c>DependsOn</c> 派生(模块依赖 → 模块键),依赖未就绪时安装器保持非活动等待,
/// 而不是像拓扑排序那样直接抛错;
/// - provide 发布模块键 <c>app.module.&lt;ModuleId&gt;</c>(安装器 Active 后对依赖者可见);
/// - apply 依次执行 RegisterServices + InitializeAsyncconfig 必须传入 <see cref="ShrinkAppServices"/>。
///
/// 已知边界(后续阶段补齐):ShrinkAppServices 尚无注销能力,
/// 安装器卸载时不会移除已注册的服务;重新激活会重复执行 RegisterServices(同键覆盖)。
/// </summary>
public sealed class ShrinkAppInstallerComponent : IShrinkComponent
{
/// <summary>模块键前缀:依赖声明 <c>DependsOn = ["a"]</c> 映射为 <c>app.module.a</c>。</summary>
public const string ModuleKeyPrefix = "app.module.";
private readonly IShrinkAppModuleInstaller _installer;
private readonly ShrinkAppSettings? _settings;
private readonly string[] _inject;
public ShrinkAppInstallerComponent(IShrinkAppModuleInstaller installer, ShrinkAppSettings? settings = null)
{
_installer = installer ?? throw new ArgumentNullException(nameof(installer));
_settings = settings;
_inject = (installer.DependsOn ?? Array.Empty<string>())
.Where(id => !string.IsNullOrWhiteSpace(id))
.Select(id => ModuleKeyPrefix + id.Trim())
.ToArray();
}
public string Name => "app-installer:" + _installer.ModuleId;
public IReadOnlyList<string> Inject => _inject;
public IReadOnlyList<string> Provide => new[] { ModuleKeyPrefix + _installer.ModuleId };
public IShrinkAppModuleInstaller Installer => _installer;
public async UniTask ApplyAsync(ShrinkCtx ctx, object? config)
{
if (config is not ShrinkAppServices services)
throw new InvalidOperationException(
$"ShrinkAppInstallerComponent '{_installer.ModuleId}' requires ShrinkAppServices as fiber config.");
// 先发布模块键再执行安装:装载期绑定对依赖者不可见(提供者须 Active),
// 供给冲突(重复 ModuleId)在安装器初始化之前即失败
ctx.Set(Provide[0], _installer.ModuleId);
var appContext = ShrinkAppContext.CreateStandalone(services, _settings);
_installer.RegisterServices(appContext);
await _installer.InitializeAsync(appContext);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9d8057e758d9edf46b18bd47145421c0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,64 @@
#nullable enable
using Cysharp.Threading.Tasks;
using ShrinkApp;
using UnityEngine;
namespace ShrinkContext.AppAdapter
{
/// <summary>
/// ShrinkApp 加载器宿主的自动引导:
/// hostingMode == ContextLoader 时在 BeforeSceneLoad 创建常驻 GameObject 并启动 ShrinkAppLoaderHost
/// 同时把服务容器接回 ShrinkApp 静态入口(InitializeForExternalHost),保证场景脚本照常访问 ShrinkApp.Services。
/// ClassicHost 模式下完全不动——经典路径零行为变化。
/// </summary>
public sealed class ShrinkAppLoaderBootstrapper : MonoBehaviour
{
private static ShrinkAppLoaderBootstrapper? _instance;
/// <summary>
/// Starter/组合包在 SubsystemRegistration 阶段设置的默认装配表。
/// AppAdapter 保持不依赖具体业务模块,组合根负责把原生组件挂到已发现的模块 id。
/// </summary>
public static System.Action<ShrinkAppLoaderHost>? DefaultComposition { get; set; }
public static ShrinkAppLoaderBootstrapper? Instance => _instance;
public ShrinkAppLoaderHost Host { get; private set; } = null!;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void AutoBootstrap()
{
if (ShrinkAppSettings.Instance.hostingMode != ShrinkAppHostingMode.ContextLoader)
return;
var gameObject = new GameObject("ShrinkAppLoaderHost");
DontDestroyOnLoad(gameObject);
gameObject.AddComponent<ShrinkAppLoaderBootstrapper>();
}
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(gameObject);
return;
}
_instance = this;
Host = new ShrinkAppLoaderHost();
DefaultComposition?.Invoke(Host);
global::ShrinkApp.ShrinkApp.InitializeForExternalHost(Host.Services);
Host.StartAsync().Forget(ex =>
{
Debug.LogException(ex);
Debug.LogError("[ShrinkApp.LoaderHost] 启动失败: " + ex.Message);
});
}
private void OnDestroy()
{
if (_instance == this)
_instance = null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f4021699debf79945a4e30e8a43d3049
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,228 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
using ShrinkApp;
using ShrinkEventBus;
using UnityEngine;
namespace ShrinkContext.AppAdapter
{
/// <summary>
/// 由 ShrinkContext 加载器驱动的 ShrinkApp 宿主(阶段 2 过渡路径,对应 ShrinkAppSettings.hostingMode = ContextLoader)。
///
/// 与经典 ShrinkAppHost 的行为差异:
/// - 依赖缺失的安装器保持非活动等待(Waiting),而不是排序期抛错;
/// - 支持运行中 SetModuleDisabledAsync 按模块 disable/enable,无需重启宿主;
/// - 重复 ModuleId 在构造期抛错(与经典一致),依赖排序由响应式余效应结构性保证。
///
/// 与 ShrinkAppHost 相同的语义:安装器单例实例、ModuleId 大小写不敏感、
/// disabledModuleIds 作为初始禁用集合、启动完成发布 ShrinkAppStartedEvent。
/// </summary>
public sealed class ShrinkAppLoaderHost
{
private sealed class ModuleRecord
{
public string ModuleId = string.Empty;
}
private readonly Dictionary<string, ModuleRecord> _modules = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _disabled = new(StringComparer.OrdinalIgnoreCase);
private readonly ShrinkComponentCatalog _catalog;
private bool _started;
public ShrinkAppLoaderHost(ShrinkAppSettings? settings = null,
IReadOnlyList<IShrinkAppModuleInstaller>? installers = null)
{
Settings = settings ?? ShrinkAppSettings.Instance;
Services = new ShrinkAppServices();
Context = new ShrinkContextRuntime();
var catalog = new ShrinkComponentCatalog();
foreach (var installer in installers ?? DiscoverDefaultInstallers())
{
if (installer == null || string.IsNullOrWhiteSpace(installer.ModuleId))
throw new InvalidOperationException(
$"Installer '{installer?.GetType().FullName ?? "<null>"}' has an empty ModuleId.");
var moduleId = installer.ModuleId.Trim();
if (!_modules.TryAdd(moduleId, new ModuleRecord { ModuleId = moduleId }))
throw new InvalidOperationException($"Duplicate installer ModuleId: {moduleId}");
// 工厂每次重建条目时包装同一个安装器实例(与经典宿主的单例安装器语义一致)
catalog.Register(moduleId, () => new ShrinkAppInstallerComponent(installer, Settings));
}
Loader = new ShrinkContextLoader(Context, catalog);
_catalog = catalog;
foreach (var rawId in Settings.disabledModuleIds ?? Array.Empty<string>())
{
if (!string.IsNullOrWhiteSpace(rawId))
_disabled.Add(rawId.Trim());
}
}
public ShrinkAppSettings Settings { get; }
public ShrinkAppServices Services { get; }
public ShrinkContextRuntime Context { get; }
public ShrinkContextLoader Loader { get; }
public bool IsRunning { get; private set; }
/// <summary>全部已注册模块 id(有序)。</summary>
public IReadOnlyList<string> ModuleIds =>
_modules.Values.Select(m => m.ModuleId).OrderBy(id => id, StringComparer.OrdinalIgnoreCase).ToArray();
public IReadOnlyList<string> ActiveModuleIds =>
ModuleIds.Where(IsModuleActive).ToArray();
/// <summary>已注册但当前非活动的模块(依赖缺失等待中;被禁用的模块不计入,见 IsModuleDisabled)。</summary>
public IReadOnlyList<string> WaitingModuleIds =>
ModuleIds.Where(IsModuleWaiting).ToArray();
public bool IsModuleActive(string moduleId) =>
TryGetLoaderFiber(moduleId, out var fiber) && fiber.State == ShrinkFiberState.Active;
public bool IsModuleWaiting(string moduleId) =>
TryGetLoaderFiber(moduleId, out var fiber) && fiber.State == ShrinkFiberState.Inactive;
public bool IsModuleDisabled(string moduleId) =>
!string.IsNullOrWhiteSpace(moduleId) && _disabled.Contains(moduleId.Trim());
/// <summary>查询模块当前纤程(被禁用模块返回 false)。</summary>
public bool TryGetModuleFiber(string moduleId, out ShrinkFiber fiber) =>
TryGetLoaderFiber(moduleId, out fiber!);
private bool TryGetLoaderFiber(string moduleId, out ShrinkFiber? fiber)
{
fiber = null;
if (string.IsNullOrWhiteSpace(moduleId))
return false;
if (!_modules.ContainsKey(moduleId.Trim()))
return false;
return Loader.TryGetFiber(moduleId.Trim(), out fiber!);
}
/// <summary>
/// 阶段 3:用原生 Cordis 组件替换指定模块的安装器包装(须在 StartAsync 之前调用)。
/// 目录同键覆盖——安装器不再被实例化包装,模块行为完全由原生组件定义。
/// </summary>
public void OverrideModuleComponent(string moduleId, Func<IShrinkComponent> componentFactory)
{
if (_started)
throw new InvalidOperationException("Module components can only be overridden before StartAsync.");
if (string.IsNullOrWhiteSpace(moduleId))
throw new ArgumentException("Module id must not be null or empty.", nameof(moduleId));
if (componentFactory == null)
throw new ArgumentNullException(nameof(componentFactory));
if (!_modules.ContainsKey(moduleId.Trim()))
throw new InvalidOperationException($"Unknown module id: '{moduleId}'.");
_catalog.Register(moduleId.Trim(), componentFactory);
}
/// <summary>
/// 向组合根加入没有旧安装器身份的原生组件(例如 Command-Network、EventBus 薄适配)。
/// 须在 StartAsync 前调用;模块 id 同时作为加载器条目 id 与组件目录键。
/// </summary>
public void AddModuleComponent(string moduleId, Func<IShrinkComponent> componentFactory)
{
if (_started)
throw new InvalidOperationException("Module components can only be added before StartAsync.");
if (string.IsNullOrWhiteSpace(moduleId))
throw new ArgumentException("Module id must not be null or empty.", nameof(moduleId));
if (componentFactory == null)
throw new ArgumentNullException(nameof(componentFactory));
var normalizedId = moduleId.Trim();
if (!_modules.TryAdd(normalizedId, new ModuleRecord { ModuleId = normalizedId }))
throw new InvalidOperationException($"Duplicate module id: '{normalizedId}'.");
_catalog.Register(normalizedId, componentFactory);
}
public async UniTask StartAsync()
{
if (_started)
return;
_started = true;
await Loader.ApplyAsync(BuildEntries());
IsRunning = true;
global::ShrinkApp.ShrinkApp.SetExternalHostRunning(true);
var active = ActiveModuleIds;
Debug.Log($"[ShrinkApp.LoaderHost] 启动完成:active={active.Count} " +
$"waiting={WaitingModuleIds.Count} disabled={_disabled.Count} " +
$"modules=[{string.Join(", ", active)}]");
EventBus.TriggerEvent(new ShrinkAppStartedEvent
{
ModuleIds = active.ToArray()
});
}
/// <summary>运行中按模块 disable/enable:增量协调,宿主与其余模块不重启。</summary>
public async UniTask SetModuleDisabledAsync(string moduleId, bool disabled)
{
EnsureStarted();
if (string.IsNullOrWhiteSpace(moduleId))
throw new ArgumentException("Module id must not be null or empty.", nameof(moduleId));
if (!TryGetRecord(moduleId, out _))
throw new InvalidOperationException($"Unknown module id: '{moduleId}'.");
if (disabled)
_disabled.Add(moduleId.Trim());
else
_disabled.Remove(moduleId.Trim());
await Loader.ApplyAsync(BuildEntries());
}
public async UniTask ShutdownAsync()
{
EnsureStarted();
await Context.ShutdownAsync();
IsRunning = false;
global::ShrinkApp.ShrinkApp.SetExternalHostRunning(false);
}
private List<ShrinkLoaderEntry> BuildEntries()
{
var entries = new List<ShrinkLoaderEntry>();
foreach (var record in _modules.Values.OrderBy(m => m.ModuleId, StringComparer.OrdinalIgnoreCase))
entries.Add(new ShrinkLoaderEntry(record.ModuleId, record.ModuleId, Services,
_disabled.Contains(record.ModuleId)));
return entries;
}
private bool TryGetRecord(string moduleId, out ModuleRecord record)
{
if (!string.IsNullOrWhiteSpace(moduleId))
return _modules.TryGetValue(moduleId.Trim(), out record!);
record = null!;
return false;
}
private void EnsureStarted()
{
if (!_started)
throw new InvalidOperationException("ShrinkAppLoaderHost has not been started yet.");
}
private static IReadOnlyList<IShrinkAppModuleInstaller> DiscoverDefaultInstallers()
{
var installers = new List<IShrinkAppModuleInstaller>();
foreach (var type in ShrinkAppInstallers.GetDiscoveredInstallerTypes())
{
if (Activator.CreateInstance(type) is IShrinkAppModuleInstaller installer)
installers.Add(installer);
else
throw new InvalidOperationException($"Failed to create installer: {type.FullName}");
}
return installers;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4a5dccbb74da10d46837de4ba1240299
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,15 @@
{
"name": "ShrinkContext.AppAdapter.Runtime",
"rootNamespace": "ShrinkContext.AppAdapter",
"references": [
"ShrinkContext.Core.Runtime",
"ShrinkApp.Core.Runtime",
"ShrinkEventBus.Runtime",
"UniTask"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"autoReferenced": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 784bc035ead25ce438bcd7b9369a11c8
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5898f3ec855a8e448892ff9976c9f6af
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,100 @@
#nullable enable
using NUnit.Framework;
using ShrinkApp.Starter.Basic;
using ShrinkCommand.Integration.App;
using ShrinkContext;
using ShrinkDataSaver.Integration.App;
using ShrinkNetwork;
using ShrinkNetwork.Integration.App;
using ShrinkApp;
using UnityEngine;
using Object = UnityEngine.Object;
namespace ShrinkContext.AppAdapter.Tests
{
/// <summary>
/// Basic Starter 默认装配表的端到端验证(阶段 3):
/// 三个功能模块走原生 Cordis 组件,四个跨包集成走按键注入的薄组件;
/// 提供者停用时依赖集成先退出,兼容服务门面也作为可逆效应注销。
/// </summary>
public class NativeWiringTests
{
[Test]
public void BasicComposition_UsesNativeComponents_AndRetiresDependentsReversibly()
{
var settings = ScriptableObject.CreateInstance<ShrinkAppSettings>();
ShrinkAppLoaderHost? host = null;
try
{
host = new ShrinkAppLoaderHost(settings);
ShrinkAppBasicContextComposition.Configure(host);
TestAwait.Run(host.StartAsync());
Assert.AreEqual(7, host.ModuleIds.Count);
Assert.AreEqual(7, host.ActiveModuleIds.Count);
Assert.IsTrue(host.IsModuleActive("shrink.network"));
Assert.IsTrue(host.IsModuleActive("shrink.command"));
Assert.IsTrue(host.IsModuleActive("shrink.datasaver"));
Assert.IsTrue(host.IsModuleActive("shrink.integration.command-network"));
Assert.IsTrue(host.IsModuleActive("shrink.integration.command-eventbus"));
Assert.IsTrue(host.IsModuleActive("shrink.integration.datasaver-eventbus"));
Assert.IsTrue(host.IsModuleActive("shrink.integration.network-eventbus"));
var root = host.Context.RootContext;
Assert.IsTrue(host.Context.TryGetRaw<ShrinkNetworkService>(root,
ShrinkNetworkAppComponent.ServiceKey, out _), "网络服务键由原生组件提供");
Assert.IsTrue(host.Context.TryGetRaw<ShrinkCommand.ShrinkCommandService>(root,
ShrinkCommandAppComponent.ServiceKey, out _), "命令服务键由原生组件提供");
Assert.IsTrue(host.Context.TryGetRaw<object>(root,
ShrinkDataSaverAppComponent.ServiceKey, out _), "存档服务键由原生组件提供");
Assert.IsTrue(host.Context.TryGetRaw<object>(root,
"shrink.integration.command-network", out _));
Assert.IsTrue(host.Context.TryGetRaw<object>(root,
"shrink.integration.command-eventbus", out _));
Assert.IsTrue(host.Context.TryGetRaw<object>(root,
"shrink.integration.datasaver-eventbus", out _));
Assert.IsTrue(host.Context.TryGetRaw<object>(root,
"shrink.integration.network-eventbus", out _));
Assert.IsTrue(host.Services.TryGet<ShrinkNetworkAppService>(out _));
Assert.IsTrue(host.Services.TryGet<ShrinkCommandAppService>(out _));
Assert.IsTrue(host.Services.TryGet<ShrinkDataSaverService>(out _));
TestAwait.Run(host.SetModuleDisabledAsync("shrink.command", true));
Assert.IsFalse(host.IsModuleActive("shrink.command"));
Assert.IsFalse(host.IsModuleActive("shrink.integration.command-network"));
Assert.IsFalse(host.IsModuleActive("shrink.integration.command-eventbus"));
Assert.IsTrue(host.IsModuleActive("shrink.network"), "无关提供者不得重载");
Assert.IsTrue(host.IsModuleActive("shrink.datasaver"), "无关提供者不得重载");
Assert.IsTrue(host.IsModuleActive("shrink.integration.network-eventbus"));
Assert.IsTrue(host.IsModuleActive("shrink.integration.datasaver-eventbus"));
Assert.IsFalse(host.Context.TryGetRaw<object>(root,
ShrinkCommandAppComponent.ServiceKey, out _));
Assert.IsFalse(host.Context.TryGetRaw<object>(root,
"shrink.integration.command-network", out _));
Assert.IsFalse(host.Context.TryGetRaw<object>(root,
"shrink.integration.command-eventbus", out _));
Assert.IsFalse(host.Services.TryGet<ShrinkCommandAppService>(out _),
"兼容门面应随组件退役注销");
TestAwait.Run(host.SetModuleDisabledAsync("shrink.command", false));
Assert.AreEqual(7, host.ActiveModuleIds.Count);
Assert.IsTrue(host.Services.TryGet<ShrinkCommandAppService>(out _));
TestAwait.Run(host.ShutdownAsync());
Assert.AreEqual(0, host.ActiveModuleIds.Count);
Assert.IsFalse(host.Services.TryGet<ShrinkNetworkAppService>(out _));
Assert.IsFalse(host.Services.TryGet<ShrinkCommandAppService>(out _));
Assert.IsFalse(host.Services.TryGet<ShrinkDataSaverService>(out _));
}
finally
{
if (host?.IsRunning == true)
TestAwait.Run(host.ShutdownAsync());
Object.DestroyImmediate(settings);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 92ef45fe59147f445bbb2ae4760732b7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,174 @@
#nullable enable
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using NUnit.Framework;
using ShrinkApp;
using ShrinkContext;
using UnityEngine;
using Object = UnityEngine.Object;
namespace ShrinkContext.AppAdapter.Tests
{
/// <summary>
/// ShrinkApp 安装器适配器:
/// 依赖缺失等待而非抛错(对照 ShrinkAppHost.SortInstallers 的行为差异)、
/// 依赖就绪顺序保证、重复 ModuleId 退化为供给冲突而非宿主级失败、服务注册可见性。
/// </summary>
public class ShrinkAppInstallerComponentTests
{
private ShrinkContextRuntime _runtime = null!;
private ShrinkAppServices _services = null!;
private ShrinkAppSettings _settings = null!;
private static long _sequence;
[SetUp]
public void SetUp()
{
_runtime = new ShrinkContextRuntime();
_services = new ShrinkAppServices();
_settings = ScriptableObject.CreateInstance<ShrinkAppSettings>();
}
[TearDown]
public void TearDown()
{
if (_settings != null)
Object.DestroyImmediate(_settings);
}
private ShrinkFiber UseInstaller(FakeInstaller installer)
{
return _runtime.Use(new ShrinkAppInstallerComponent(installer, _settings), _services);
}
[Test]
public void MissingDependency_WaitsInsteadOfThrowing()
{
var dependent = new FakeInstaller("app.b", "b-service") { DependsOn = new[] { "app.a" } };
var fiber = UseInstaller(dependent);
Assert.AreEqual(ShrinkFiberState.Inactive, fiber.State,
"依赖模块未就绪时安装器保持非活动(对照:ShrinkAppHost 在排序期直接抛依赖缺失)");
Assert.AreEqual(0, dependent.RegisterCount);
Assert.AreEqual(0, dependent.InitCount);
}
[Test]
public void DependencyArrives_DependentActivates_AfterProvider()
{
var provider = new FakeInstaller("app.a", "a-service");
var dependent = new FakeInstaller("app.b", "b-service") { DependsOn = new[] { "app.a" } };
var dependentFiber = UseInstaller(dependent);
var providerFiber = UseInstaller(provider);
Assert.AreEqual(ShrinkFiberState.Active, providerFiber.State);
Assert.AreEqual(ShrinkFiberState.Active, dependentFiber.State,
"依赖键由提供者发布后,依赖安装器被响应式激活");
// 激活次序由依赖关系保证:提供者先完成 Register+Init
Assert.AreEqual(1, provider.InitCount);
Assert.AreEqual(1, dependent.InitCount);
Assert.Less(provider.CompletedAt, dependent.CompletedAt,
"依赖者的初始化必须晚于其依赖的提供者(空间可组合性排序)");
Assert.IsTrue(_services.TryGet<FakeService>(out var service));
Assert.AreEqual("b-service", service!.Value);
}
[Test]
public void DuplicateModuleId_SecondFailsAsSupplyConflict_FirstStaysActive()
{
var first = new FakeInstaller("app.dup", "first");
var second = new FakeInstaller("app.dup", "second");
var firstFiber = UseInstaller(first);
var secondFiber = UseInstaller(second);
Assert.AreEqual(ShrinkFiberState.Active, firstFiber.State);
Assert.AreEqual(ShrinkFiberState.Inactive, secondFiber.State);
Assert.IsInstanceOf<ShrinkSupplyConflictException>(secondFiber.LastError,
"重复 ModuleId 退化为该纤程的供给冲突失败,而不是宿主级异常(对照 ShrinkHost 的 Duplicate installer 抛错)");
Assert.AreEqual(0, second.InitCount);
}
[Test]
public void RetireProvider_DependentInstallerDeactivates()
{
var provider = new FakeInstaller("app.a", "a-service");
var dependent = new FakeInstaller("app.b", "b-service") { DependsOn = new[] { "app.a" } };
var providerFiber = UseInstaller(provider);
var dependentFiber = UseInstaller(dependent);
Assert.AreEqual(ShrinkFiberState.Active, dependentFiber.State);
TestAwait.Run(_runtime.RetireAsync(providerFiber));
Assert.AreEqual(ShrinkFiberState.Inactive, dependentFiber.State,
"提供者退役后依赖安装器自动停用(服务注销为已知边界,见组件注释)");
}
[Test]
public void MissingServicesConfig_FailsWithClearError()
{
var installer = new FakeInstaller("app.x", "x");
var component = new ShrinkAppInstallerComponent(installer, _settings);
var fiber = _runtime.Use(component, config: null!);
Assert.AreEqual(ShrinkFiberState.Inactive, fiber.State);
Assert.IsInstanceOf<InvalidOperationException>(fiber.LastError);
StringAssert.Contains("ShrinkAppServices", fiber.LastError!.Message);
}
// ---- 测试替身 ----
private sealed class FakeInstaller : IShrinkAppModuleInstaller
{
public FakeInstaller(string moduleId, string serviceValue)
{
ModuleId = moduleId;
ServiceValue = serviceValue;
}
public string ModuleId { get; }
public int Order => 0;
public IReadOnlyList<string> DependsOn { get; set; } = Array.Empty<string>();
public int RegisterCount { get; private set; }
public int InitCount { get; private set; }
public long CompletedAt { get; private set; }
private string ServiceValue { get; }
public void RegisterServices(ShrinkAppContext context)
{
RegisterCount++;
context.Services.Register(new FakeService(ServiceValue));
}
public UniTask InitializeAsync(ShrinkAppContext context)
{
InitCount++;
CompletedAt = ++_sequence;
return UniTask.CompletedTask;
}
}
private sealed class FakeService
{
public FakeService(string value)
{
Value = value;
}
public string Value { get; }
}
}
/// <summary>跨程序集测试辅助(与 ShrinkContext.Core.Tests.TestAwait 同语义)。</summary>
public static class TestAwait
{
public static void Run(UniTask task)
{
task.GetAwaiter().GetResult();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4351747efa1ed6242a67b18f60388935
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,205 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
using NUnit.Framework;
using ShrinkApp;
using ShrinkContext;
using ShrinkEventBus;
using UnityEngine;
using Object = UnityEngine.Object;
namespace ShrinkContext.AppAdapter.Tests
{
/// <summary>
/// ShrinkAppLoaderHost 端到端:
/// 启动激活与 Started 事件、运行中 disable/enable 不重启宿主、设置级初始禁用、
/// 未知模块报错、重复 ModuleId 构造期失败、Shutdown。
/// </summary>
public class ShrinkAppLoaderHostTests
{
private ShrinkAppSettings _settings = null!;
[SetUp]
public void SetUp()
{
_settings = ScriptableObject.CreateInstance<ShrinkAppSettings>();
}
[TearDown]
public void TearDown()
{
if (_settings != null)
Object.DestroyImmediate(_settings);
}
private ShrinkAppLoaderHost CreateHost(params FakeInstaller[] installers)
{
return new ShrinkAppLoaderHost(_settings, installers);
}
[Test]
public void StartAsync_ActivatesModules_AndPublishesStartedEvent()
{
var host = CreateHost(
new FakeInstaller("app.a", "a"),
new FakeInstaller("app.b", "b") { DependsOn = new[] { "app.a" } });
ShrinkAppStartedEvent? started = null;
using (var subscription = EventBus.SubscribeEvent<ShrinkAppStartedEvent>(e => started = e))
{
TestAwait.Run(host.StartAsync());
}
Assert.IsTrue(host.IsRunning);
Assert.IsTrue(host.IsModuleActive("app.a"));
Assert.IsTrue(host.IsModuleActive("app.b"), "依赖模块在提供者激活后自动激活");
Assert.IsNotNull(started);
CollectionAssert.AreEquivalent(new[] { "app.a", "app.b" }, started!.ModuleIds);
}
[Test]
public void SetModuleDisabled_RetiresModuleAndDependents_EnableReloadsWithoutRestart()
{
var provider = new FakeInstaller("app.a", "a");
var dependent = new FakeInstaller("app.b", "b") { DependsOn = new[] { "app.a" } };
var bystander = new FakeInstaller("app.c", "c");
var host = CreateHost(provider, dependent, bystander);
TestAwait.Run(host.StartAsync());
Assert.AreEqual(3, host.ActiveModuleIds.Count);
TestAwait.Run(host.SetModuleDisabledAsync("app.a", true));
Assert.IsTrue(host.IsModuleDisabled("app.a"));
Assert.IsFalse(host.IsModuleActive("app.a"));
Assert.IsFalse(host.IsModuleActive("app.b"), "依赖者随提供者停用");
Assert.IsTrue(host.IsModuleActive("app.c"), "无关模块不受影响,宿主不重启");
Assert.IsTrue(host.IsRunning);
TestAwait.Run(host.SetModuleDisabledAsync("app.a", false));
Assert.IsTrue(host.IsModuleActive("app.a"));
Assert.IsTrue(host.IsModuleActive("app.b"), "重新启用后依赖链整体复活");
Assert.AreEqual(2, provider.InitCount, "重启用会重新执行安装器初始化(重建语义)");
Assert.AreEqual(1, bystander.InitCount, "未受影响的模块不重复初始化");
}
[Test]
public void DisabledViaSettings_ExcludedInitially_CanEnableAtRuntime()
{
_settings.disabledModuleIds = new[] { "app.a" };
var provider = new FakeInstaller("app.a", "a");
var dependent = new FakeInstaller("app.b", "b") { DependsOn = new[] { "app.a" } };
var host = CreateHost(provider, dependent);
TestAwait.Run(host.StartAsync());
Assert.IsTrue(host.IsModuleDisabled("app.a"));
Assert.IsFalse(host.TryGetModuleFiber("app.a", out _));
Assert.IsTrue(host.IsModuleWaiting("app.b"), "依赖被禁用模块的安装器保持等待而非报错");
CollectionAssert.AreEqual(new[] { "app.b" }, host.WaitingModuleIds);
TestAwait.Run(host.SetModuleDisabledAsync("app.a", false));
Assert.IsTrue(host.IsModuleActive("app.a"));
Assert.IsTrue(host.IsModuleActive("app.b"));
}
[Test]
public void UnknownModuleId_Throws()
{
var host = CreateHost(new FakeInstaller("app.a", "a"));
TestAwait.Run(host.StartAsync());
Assert.Throws<InvalidOperationException>(() =>
TestAwait.Run(host.SetModuleDisabledAsync("app.no-such", true)));
}
[Test]
public void DuplicateModuleIds_ThrowAtConstruction()
{
Assert.Throws<InvalidOperationException>(() =>
CreateHost(new FakeInstaller("app.dup", "a"), new FakeInstaller("app.dup", "b")));
}
[Test]
public void ShutdownAsync_RetiresEverything()
{
var provider = new FakeInstaller("app.a", "a");
var host = CreateHost(provider);
TestAwait.Run(host.StartAsync());
Assert.IsTrue(host.IsModuleActive("app.a"));
TestAwait.Run(host.ShutdownAsync());
Assert.IsFalse(host.IsRunning);
Assert.IsFalse(host.IsModuleActive("app.a"));
}
[Test]
public void OverrideModuleComponent_ReplacesInstallerWrapper()
{
var installer = new FakeInstaller("app.a", "a");
var host = CreateHost(installer);
host.OverrideModuleComponent("app.a", () => new NativeReplacementComponent());
TestAwait.Run(host.StartAsync());
Assert.IsTrue(host.IsModuleActive("app.a"));
Assert.AreEqual(0, installer.InitCount, "原生组件替换后安装器不再被包装执行");
Assert.IsTrue(host.TryGetModuleFiber("app.a", out var fiber));
Assert.IsInstanceOf<NativeReplacementComponent>(fiber.Component);
}
/// <summary>替换安装器的原生测试组件(发布同一模块键)。</summary>
private sealed class NativeReplacementComponent : IShrinkComponent
{
public string Name => "app.a";
public System.Collections.Generic.IReadOnlyList<string> Inject => System.Array.Empty<string>();
public System.Collections.Generic.IReadOnlyList<string> Provide =>
new[] { ShrinkAppInstallerComponent.ModuleKeyPrefix + "app.a" };
public UniTask ApplyAsync(ShrinkCtx ctx, object? config)
{
ctx.Set(Provide[0], Name);
return UniTask.CompletedTask;
}
}
private sealed class FakeInstaller : IShrinkAppModuleInstaller
{
public FakeInstaller(string moduleId, string serviceValue)
{
ModuleId = moduleId;
ServiceValue = serviceValue;
}
public string ModuleId { get; }
public int Order => 0;
public IReadOnlyList<string> DependsOn { get; set; } = Array.Empty<string>();
public int InitCount { get; private set; }
private string ServiceValue { get; }
public void RegisterServices(ShrinkAppContext context)
{
context.Services.Register(new FakeService(ServiceValue));
}
public UniTask InitializeAsync(ShrinkAppContext context)
{
InitCount++;
return UniTask.CompletedTask;
}
}
private sealed class FakeService
{
public FakeService(string value)
{
Value = value;
}
public string Value { get; }
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4aa1105e16f405b428d2c5a841521479
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,31 @@
{
"name": "ShrinkContext.AppAdapter.Tests",
"rootNamespace": "ShrinkContext.AppAdapter.Tests",
"references": [
"ShrinkContext.AppAdapter.Runtime",
"ShrinkContext.Core.Runtime",
"ShrinkApp.Core.Runtime",
"ShrinkApp.Starter.Basic.Runtime",
"ShrinkEventBus.Runtime",
"ShrinkNetwork.Integration.App",
"ShrinkCommand.Integration.App",
"ShrinkDataSaver.Integration.App",
"ShrinkNetwork.Runtime",
"ShrinkCommand.Runtime",
"UniTask",
"UnityEngine.TestRunner",
"UnityEditor.TestRunner"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"autoReferenced": false,
"defineConstraints": [
"UNITY_INCLUDE_TESTS"
],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 907201a93f40ce44781eaa942ed9dbac
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,23 @@
{
"name": "com.cneicy.shrink-context-app-adapter",
"version": "0.1.0",
"displayName": "ShrinkContext - ShrinkApp Adapter",
"description": "把现有 IShrinkAppModuleInstaller 包装为 ShrinkContext 组件:依赖缺失改为等待而非抛错,模块激活由响应式余效应驱动。",
"unity": "2022.3",
"dependencies": {
"com.cneicy.shrink-context-core": "0.1.0",
"com.cneicy.shrink-app-core": "0.1.0",
"com.cysharp.unitask": "2.5.10"
},
"keywords": [
"context",
"cordis",
"shrinkapp",
"adapter",
"installer"
],
"author": {
"name": "cneicy",
"url": "https://github.com/cneicy"
}
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2a898320ff524ef4d84a3f2021773a8d
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: