This commit is contained in:
@@ -0,0 +1,282 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace ShrinkContext.AppAdapter
|
||||
{
|
||||
[Serializable]
|
||||
public sealed class ShrinkAppCompositionIsolate
|
||||
{
|
||||
public string key = string.Empty;
|
||||
public string realm = string.Empty;
|
||||
|
||||
public ShrinkAppCompositionIsolate()
|
||||
{
|
||||
}
|
||||
|
||||
public ShrinkAppCompositionIsolate(string key, string realm)
|
||||
{
|
||||
this.key = key;
|
||||
this.realm = realm;
|
||||
}
|
||||
|
||||
internal ShrinkAppCompositionIsolate Clone() => new(key, realm);
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class ShrinkAppCompositionMetadata
|
||||
{
|
||||
public string name = string.Empty;
|
||||
public string value = string.Empty;
|
||||
|
||||
public ShrinkAppCompositionMetadata()
|
||||
{
|
||||
}
|
||||
|
||||
public ShrinkAppCompositionMetadata(string name, string value)
|
||||
{
|
||||
this.name = name;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
internal ShrinkAppCompositionMetadata Clone() => new(name, value);
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class ShrinkAppCompositionIntercept
|
||||
{
|
||||
public string key = string.Empty;
|
||||
public List<ShrinkAppCompositionMetadata> metadata = new();
|
||||
|
||||
public ShrinkAppCompositionIntercept()
|
||||
{
|
||||
}
|
||||
|
||||
public ShrinkAppCompositionIntercept(string key,
|
||||
IEnumerable<ShrinkAppCompositionMetadata>? metadata = null)
|
||||
{
|
||||
this.key = key;
|
||||
if (metadata != null)
|
||||
{
|
||||
foreach (var item in metadata)
|
||||
this.metadata.Add(item?.Clone() ?? throw new ArgumentException("Metadata must not contain null."));
|
||||
}
|
||||
}
|
||||
|
||||
internal ShrinkAppCompositionIntercept Clone() => new(key, metadata);
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class ShrinkAppCompositionEntry
|
||||
{
|
||||
public string id = string.Empty;
|
||||
public bool enabled = true;
|
||||
public List<ShrinkAppCompositionIsolate> isolate = new();
|
||||
public List<ShrinkAppCompositionIntercept> intercept = new();
|
||||
|
||||
public ShrinkAppCompositionEntry()
|
||||
{
|
||||
}
|
||||
|
||||
public ShrinkAppCompositionEntry(string id, bool enabled = true,
|
||||
IEnumerable<ShrinkAppCompositionIsolate>? isolate = null,
|
||||
IEnumerable<ShrinkAppCompositionIntercept>? intercept = null)
|
||||
{
|
||||
this.id = id;
|
||||
this.enabled = enabled;
|
||||
if (isolate != null)
|
||||
{
|
||||
foreach (var item in isolate)
|
||||
this.isolate.Add(item?.Clone() ?? throw new ArgumentException("Isolate must not contain null."));
|
||||
}
|
||||
|
||||
if (intercept != null)
|
||||
{
|
||||
foreach (var item in intercept)
|
||||
this.intercept.Add(item?.Clone() ?? throw new ArgumentException("Intercept must not contain null."));
|
||||
}
|
||||
}
|
||||
|
||||
internal string NormalizedId => id?.Trim() ?? string.Empty;
|
||||
|
||||
internal ShrinkAppCompositionEntry Clone() => new(id, enabled, isolate, intercept);
|
||||
|
||||
internal IReadOnlyDictionary<string, string>? BuildIsolate()
|
||||
{
|
||||
if (isolate == null || isolate.Count == 0)
|
||||
return null;
|
||||
|
||||
var result = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var item in isolate)
|
||||
result.Add(item.key.Trim(), item.realm.Trim());
|
||||
return result;
|
||||
}
|
||||
|
||||
internal IReadOnlyDictionary<string, IReadOnlyDictionary<string, object?>>? BuildIntercept()
|
||||
{
|
||||
if (intercept == null || intercept.Count == 0)
|
||||
return null;
|
||||
|
||||
var result = new Dictionary<string, IReadOnlyDictionary<string, object?>>(StringComparer.Ordinal);
|
||||
foreach (var item in intercept)
|
||||
{
|
||||
var values = new Dictionary<string, object?>(StringComparer.Ordinal);
|
||||
foreach (var pair in item.metadata)
|
||||
values.Add(pair.name.Trim(), pair.value);
|
||||
result.Add(item.key.Trim(), values);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 可序列化的期望组合。组件工厂仍由代码目录注册;文档只控制条目选择、isolate 与 intercept。
|
||||
/// intercept metadata 使用字符串值,领域策略负责解释其语义。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public sealed class ShrinkAppCompositionDocument
|
||||
{
|
||||
public bool includeUnlistedEntries = true;
|
||||
public List<ShrinkAppCompositionEntry> entries = new();
|
||||
|
||||
public ShrinkAppCompositionDocument()
|
||||
{
|
||||
}
|
||||
|
||||
public ShrinkAppCompositionDocument(bool includeUnlistedEntries,
|
||||
IEnumerable<ShrinkAppCompositionEntry>? entries = null)
|
||||
{
|
||||
this.includeUnlistedEntries = includeUnlistedEntries;
|
||||
if (entries != null)
|
||||
{
|
||||
foreach (var entry in entries)
|
||||
this.entries.Add(entry?.Clone() ?? throw new ArgumentException("Entries must not contain null."));
|
||||
}
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
entries ??= new List<ShrinkAppCompositionEntry>();
|
||||
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (entry == null)
|
||||
throw new ShrinkLoaderException("Composition entries must not contain null.");
|
||||
if (string.IsNullOrWhiteSpace(entry.id))
|
||||
throw new ShrinkLoaderException("Composition entry id must not be empty.");
|
||||
if (!ids.Add(entry.NormalizedId))
|
||||
throw new ShrinkLoaderException($"Duplicate composition entry id: '{entry.NormalizedId}'.");
|
||||
|
||||
ValidateIsolate(entry);
|
||||
ValidateIntercept(entry);
|
||||
}
|
||||
}
|
||||
|
||||
public ShrinkAppCompositionDocument Clone()
|
||||
{
|
||||
Validate();
|
||||
return new ShrinkAppCompositionDocument(includeUnlistedEntries, entries);
|
||||
}
|
||||
|
||||
public string ToJson(bool prettyPrint = true)
|
||||
{
|
||||
Validate();
|
||||
return JsonUtility.ToJson(this, prettyPrint);
|
||||
}
|
||||
|
||||
public static ShrinkAppCompositionDocument FromJson(string json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
throw new ArgumentException("Composition JSON must not be empty.", nameof(json));
|
||||
|
||||
var document = JsonUtility.FromJson<ShrinkAppCompositionDocument>(json);
|
||||
if (document == null)
|
||||
throw new ShrinkLoaderException("Composition JSON did not produce a document.");
|
||||
document.entries ??= new List<ShrinkAppCompositionEntry>();
|
||||
document.Validate();
|
||||
return document;
|
||||
}
|
||||
|
||||
private static void ValidateIsolate(ShrinkAppCompositionEntry entry)
|
||||
{
|
||||
entry.isolate ??= new List<ShrinkAppCompositionIsolate>();
|
||||
var keys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var item in entry.isolate)
|
||||
{
|
||||
if (item == null || string.IsNullOrWhiteSpace(item.key) || string.IsNullOrWhiteSpace(item.realm))
|
||||
throw new ShrinkLoaderException(
|
||||
$"Composition entry '{entry.NormalizedId}' has an empty isolate key or realm.");
|
||||
if (!keys.Add(item.key.Trim()))
|
||||
throw new ShrinkLoaderException(
|
||||
$"Composition entry '{entry.NormalizedId}' has duplicate isolate key '{item.key.Trim()}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateIntercept(ShrinkAppCompositionEntry entry)
|
||||
{
|
||||
entry.intercept ??= new List<ShrinkAppCompositionIntercept>();
|
||||
var keys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var item in entry.intercept)
|
||||
{
|
||||
if (item == null || string.IsNullOrWhiteSpace(item.key))
|
||||
throw new ShrinkLoaderException(
|
||||
$"Composition entry '{entry.NormalizedId}' has an empty intercept key.");
|
||||
if (!keys.Add(item.key.Trim()))
|
||||
throw new ShrinkLoaderException(
|
||||
$"Composition entry '{entry.NormalizedId}' has duplicate intercept key '{item.key.Trim()}'.");
|
||||
|
||||
item.metadata ??= new List<ShrinkAppCompositionMetadata>();
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var pair in item.metadata)
|
||||
{
|
||||
if (pair == null || string.IsNullOrWhiteSpace(pair.name))
|
||||
throw new ShrinkLoaderException(
|
||||
$"Composition entry '{entry.NormalizedId}' has empty intercept metadata.");
|
||||
if (!names.Add(pair.name.Trim()))
|
||||
throw new ShrinkLoaderException(
|
||||
$"Composition entry '{entry.NormalizedId}' has duplicate metadata '{pair.name.Trim()}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[CreateAssetMenu(fileName = DefaultResourceName, menuName = "ShrinkSDK/Cordis/Composition Profile")]
|
||||
public sealed class ShrinkAppCompositionProfile : ScriptableObject
|
||||
{
|
||||
public const string DefaultResourceName = "ShrinkAppComposition";
|
||||
|
||||
[SerializeField] private bool includeUnlistedEntries = true;
|
||||
[SerializeField] private List<ShrinkAppCompositionEntry> entries = new();
|
||||
[Tooltip("设置后以该 TextAsset 的 JSON 文档为准;留空则使用上面的序列化条目。")]
|
||||
[SerializeField] private TextAsset? jsonOverride;
|
||||
|
||||
public bool IncludeUnlistedEntries => includeUnlistedEntries;
|
||||
public IReadOnlyList<ShrinkAppCompositionEntry> Entries =>
|
||||
entries ??= new List<ShrinkAppCompositionEntry>();
|
||||
public TextAsset? JsonOverride => jsonOverride;
|
||||
|
||||
public ShrinkAppCompositionDocument ResolveDocument()
|
||||
{
|
||||
if (jsonOverride != null && !string.IsNullOrWhiteSpace(jsonOverride.text))
|
||||
return ShrinkAppCompositionDocument.FromJson(jsonOverride.text);
|
||||
return new ShrinkAppCompositionDocument(includeUnlistedEntries, entries);
|
||||
}
|
||||
|
||||
public string ToJson(bool prettyPrint = true) => ResolveDocument().ToJson(prettyPrint);
|
||||
|
||||
public void SetDocument(ShrinkAppCompositionDocument document)
|
||||
{
|
||||
var copy = (document ?? throw new ArgumentNullException(nameof(document))).Clone();
|
||||
includeUnlistedEntries = copy.includeUnlistedEntries;
|
||||
entries = copy.entries;
|
||||
jsonOverride = null;
|
||||
}
|
||||
|
||||
public void SetJsonOverride(TextAsset? value) => jsonOverride = value;
|
||||
|
||||
public static ShrinkAppCompositionProfile? LoadDefault() =>
|
||||
Resources.Load<ShrinkAppCompositionProfile>(DefaultResourceName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 469746f53f0218442b72603e3c1f6955
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
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.<ModuleId></c>(安装器 Active 后对依赖者可见);
|
||||
/// - apply 依次执行 RegisterServices + InitializeAsync,config 必须传入 <see cref="ShrinkAppServices"/>。
|
||||
///
|
||||
/// 兼容安装器只负责执行既有 RegisterServices + InitializeAsync。需要停用时撤回服务的模块应使用
|
||||
/// 原生 Context 组件,并通过 ShrinkAppServices.TryUnregister(instance) 登记对应逆操作。
|
||||
/// </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,67 @@
|
||||
#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 保持不依赖具体业务模块,组合根负责注册原生组件;若兼容 installer 已被发现则覆盖同 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);
|
||||
var profile = ShrinkAppCompositionProfile.LoadDefault();
|
||||
if (profile != null)
|
||||
Host.ApplyComposition(profile.ResolveDocument());
|
||||
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,300 @@
|
||||
#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 sealed class CompositionOptions
|
||||
{
|
||||
public bool Enabled;
|
||||
public IReadOnlyDictionary<string, string>? Isolate;
|
||||
public IReadOnlyDictionary<string, IReadOnlyDictionary<string, object?>>? Intercept;
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, ModuleRecord> _modules = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly HashSet<string> _disabled = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly HashSet<string> _settingsDisabled = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly ShrinkComponentCatalog _catalog;
|
||||
private Dictionary<string, CompositionOptions>? _compositionOptions;
|
||||
private bool _includeUnlistedEntries = true;
|
||||
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))
|
||||
{
|
||||
_settingsDisabled.Add(rawId.Trim());
|
||||
_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; }
|
||||
public ShrinkAppCompositionDocument? AppliedComposition { 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 is { State: ShrinkFiberState.Active };
|
||||
|
||||
public bool IsModuleWaiting(string moduleId) =>
|
||||
TryGetLoaderFiber(moduleId, out var fiber) && fiber is { State: ShrinkFiberState.Inactive };
|
||||
|
||||
public bool IsModuleDisabled(string moduleId) =>
|
||||
!string.IsNullOrWhiteSpace(moduleId) &&
|
||||
(_disabled.Contains(moduleId.Trim()) ||
|
||||
(!_includeUnlistedEntries && _compositionOptions != null &&
|
||||
!_compositionOptions.ContainsKey(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在启动前应用声明式条目策略。组件工厂必须已经由组合根注册;配置不能实例化任意类型。
|
||||
/// ShrinkAppSettings.disabledModuleIds 仍作为额外禁用集合保留。
|
||||
/// </summary>
|
||||
public void ApplyComposition(ShrinkAppCompositionDocument document)
|
||||
{
|
||||
if (_started)
|
||||
throw new InvalidOperationException("Composition can only be applied before StartAsync.");
|
||||
|
||||
var copy = (document ?? throw new ArgumentNullException(nameof(document))).Clone();
|
||||
var options = new Dictionary<string, CompositionOptions>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var entry in copy.entries)
|
||||
{
|
||||
var id = entry.NormalizedId;
|
||||
if (!_modules.ContainsKey(id))
|
||||
throw new ShrinkLoaderException(
|
||||
$"Composition entry '{id}' has no registered module/component factory.");
|
||||
|
||||
options.Add(id, new CompositionOptions
|
||||
{
|
||||
Enabled = entry.enabled,
|
||||
Isolate = entry.BuildIsolate(),
|
||||
Intercept = entry.BuildIntercept()
|
||||
});
|
||||
}
|
||||
|
||||
_compositionOptions = options;
|
||||
_includeUnlistedEntries = copy.includeUnlistedEntries;
|
||||
AppliedComposition = copy;
|
||||
|
||||
_disabled.Clear();
|
||||
foreach (var id in _settingsDisabled)
|
||||
_disabled.Add(id);
|
||||
foreach (var pair in options)
|
||||
{
|
||||
if (!pair.Value.Enabled)
|
||||
_disabled.Add(pair.Key);
|
||||
}
|
||||
}
|
||||
|
||||
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.Post(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}'.");
|
||||
|
||||
var normalizedId = moduleId.Trim();
|
||||
if (!disabled && !_includeUnlistedEntries && _compositionOptions != null &&
|
||||
!_compositionOptions.ContainsKey(normalizedId))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Module '{normalizedId}' is excluded by the active composition profile.");
|
||||
}
|
||||
|
||||
if (disabled)
|
||||
_disabled.Add(normalizedId);
|
||||
else
|
||||
_disabled.Remove(normalizedId);
|
||||
|
||||
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))
|
||||
{
|
||||
CompositionOptions? options = null;
|
||||
_compositionOptions?.TryGetValue(record.ModuleId, out options);
|
||||
if (!_includeUnlistedEntries && _compositionOptions != null && options == null)
|
||||
continue;
|
||||
|
||||
entries.Add(new ShrinkLoaderEntry(record.ModuleId, record.ModuleId, Services,
|
||||
_disabled.Contains(record.ModuleId), options?.Isolate, options?.Intercept));
|
||||
}
|
||||
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:
|
||||
Reference in New Issue
Block a user