Compare commits
46
Commits
v2.0.0
..
b14d6d0117
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b14d6d0117
|
||
|
|
0449e82c0c
|
||
|
|
901ad18453
|
||
|
|
95844e11ff
|
||
|
|
240d24ba7a
|
||
|
|
a92c9d2cea
|
||
|
|
c44a7e6dda
|
||
|
|
f9c249a4d1
|
||
|
|
4ec3011320
|
||
|
|
2b8e568efa
|
||
|
|
3265cbe9b8
|
||
|
|
8adc334bfa
|
||
|
|
c5e29cb313
|
||
|
|
3bcfa56fae
|
||
|
|
64ce75a341
|
||
|
|
8aa4c79604
|
||
|
|
a6011cd01d | ||
|
|
cdd9dbdb73 | ||
|
|
7d7c0de907 | ||
|
|
d7ae6016cb | ||
|
|
ba84865d7a | ||
|
|
58f21a02c2 | ||
|
|
5c5de37fdf | ||
|
|
85401b9485 | ||
|
|
8acccdcc4b
|
||
|
|
2cea8a7ff5
|
||
|
|
8c6c464ae1
|
||
|
|
93bd33c59b
|
||
|
|
c15c14e394
|
||
|
|
67a8216c64
|
||
|
|
7f7d938fc2
|
||
|
|
fbd014a582
|
||
|
|
0ff6cba0e7
|
||
|
|
c247a207da
|
||
|
|
ed8e896fe8
|
||
|
|
6c3ab86df2
|
||
|
|
7d9e0566dd
|
||
|
|
f64289406f
|
||
|
|
98acdda3b2
|
||
|
|
e0e009a12d
|
||
|
|
1edf2172fd
|
||
|
|
8b4e6f6b75
|
||
|
|
94d58dba12
|
||
|
|
f09625fb4d
|
||
|
|
8549ba5c80
|
||
|
|
3dfbccc9d6 |
No files matched your search
@@ -0,0 +1,123 @@
|
||||
name: Publish NuGet packages
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
env:
|
||||
NUGET_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: '1'
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||
LD_LIBRARY_PATH: /opt/dotnet-libs/usr/lib/x86_64-linux-gnu
|
||||
SSL_CERT_FILE: /opt/ca-certificates.crt
|
||||
steps:
|
||||
- name: Fetch exact tagged source
|
||||
env:
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag="${GITEA_REF#refs/tags/}"
|
||||
case "$tag" in
|
||||
v[0-9]*) ;;
|
||||
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
|
||||
esac
|
||||
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/${GITEA_REPOSITORY}/archive/${tag}.tar.gz"
|
||||
node --input-type=module <<'NODE'
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
|
||||
NODE
|
||||
mkdir release
|
||||
tar -xzf release.tar.gz --strip-components=1 -C release
|
||||
rm -f release.tar.gz
|
||||
printf '%s' "$tag" > release/.shrink-sdk-release-tag
|
||||
|
||||
- name: Install .NET 8 SDK
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node --input-type=module <<'NODE'
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { rootCertificates } from 'node:tls';
|
||||
|
||||
await writeFile('/opt/ca-certificates.crt', rootCertificates.join('\n'));
|
||||
|
||||
const metadataResponse = await fetch('https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/8.0/releases.json');
|
||||
if (!metadataResponse.ok) throw new Error(`Release metadata download failed: ${metadataResponse.status}`);
|
||||
const metadata = await metadataResponse.json();
|
||||
const sdkVersion = metadata['latest-sdk'];
|
||||
const release = metadata.releases.find(item => item.sdk?.version === sdkVersion);
|
||||
const file = release?.sdk?.files?.find(item => item.rid === 'linux-x64' && item.name.endsWith('.tar.gz'));
|
||||
if (!file) throw new Error(`Linux x64 SDK archive not found for ${sdkVersion}`);
|
||||
const archiveResponse = await fetch(file.url);
|
||||
if (!archiveResponse.ok) throw new Error(`SDK download failed: ${archiveResponse.status}`);
|
||||
await writeFile('/tmp/dotnet-sdk.tar.gz', new Uint8Array(await archiveResponse.arrayBuffer()));
|
||||
|
||||
const poolUrl = 'https://deb.debian.org/debian-security/pool/updates/main/o/openssl/';
|
||||
const poolResponse = await fetch(poolUrl);
|
||||
if (!poolResponse.ok) throw new Error(`OpenSSL package index download failed: ${poolResponse.status}`);
|
||||
const poolIndex = await poolResponse.text();
|
||||
const packages = [...poolIndex.matchAll(/href="(libssl3_[^"]+_amd64\.deb)"/g)].map(match => match[1]).sort();
|
||||
const packageName = packages.at(-1);
|
||||
if (!packageName) throw new Error('Debian libssl3 package was not found');
|
||||
const packageResponse = await fetch(poolUrl + packageName);
|
||||
if (!packageResponse.ok) throw new Error(`OpenSSL package download failed: ${packageResponse.status}`);
|
||||
await writeFile('/tmp/libssl3.deb', new Uint8Array(await packageResponse.arrayBuffer()));
|
||||
NODE
|
||||
mkdir -p /opt/dotnet
|
||||
tar -xzf /tmp/dotnet-sdk.tar.gz -C /opt/dotnet
|
||||
mkdir -p /opt/dotnet-libs
|
||||
dpkg-deb -x /tmp/libssl3.deb /opt/dotnet-libs
|
||||
rm -f /tmp/dotnet-sdk.tar.gz
|
||||
rm -f /tmp/libssl3.deb
|
||||
/opt/dotnet/dotnet --info
|
||||
|
||||
- name: Validate, pack and publish
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
: "${NUGET_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
||||
export PATH="/opt/dotnet:$PATH"
|
||||
cd release
|
||||
tag="$(cat .shrink-sdk-release-tag)"
|
||||
projects=()
|
||||
if [[ -d DotNet~ ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find DotNet~ -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
if [[ -d Godot~ ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find Godot~ -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
if [[ "${#projects[@]}" -eq 0 ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find . -maxdepth 1 -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
test "${#projects[@]}" -gt 0
|
||||
if [[ -f package.json ]]; then
|
||||
version="$(node -p "require('./package.json').version")"
|
||||
else
|
||||
version="$(dotnet msbuild "${projects[0]}" -getProperty:Version -nologo)"
|
||||
fi
|
||||
test "$tag" = "v$version"
|
||||
mkdir -p packages
|
||||
for project in "${projects[@]}"; do
|
||||
dotnet restore "$project" --configfile NuGet.Config
|
||||
dotnet pack "$project" --configuration Release --no-restore --output "$PWD/packages" --include-symbols --include-source
|
||||
done
|
||||
find packages -maxdepth 1 -name '*.nupkg' -type f | grep -q .
|
||||
dotnet nuget push 'packages/*.nupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||
if compgen -G 'packages/*.snupkg' > /dev/null; then
|
||||
dotnet nuget push 'packages/*.snupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||
fi
|
||||
@@ -15,22 +15,39 @@ jobs:
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
||||
steps:
|
||||
- name: Fetch tagged revision
|
||||
- name: Fetch exact tagged release archive
|
||||
env:
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
ref="${{ gitea.sha }}"
|
||||
test -n "$ref"
|
||||
git init .
|
||||
git remote add origin "https://git.crash.work/ShrinkSDK/ShrinkEventBus.git"
|
||||
git fetch --depth=1 origin "$ref"
|
||||
git checkout --detach FETCH_HEAD
|
||||
tag="${GITEA_REF#refs/tags/}"
|
||||
case "$tag" in
|
||||
v[0-9]*) ;;
|
||||
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
|
||||
esac
|
||||
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/ShrinkSDK/ShrinkEventBus/archive/${tag}.tar.gz"
|
||||
node --input-type=module <<'NODE'
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
|
||||
NODE
|
||||
mkdir release
|
||||
tar -xzf release.tar.gz --strip-components=1 -C release
|
||||
rm -f release.tar.gz
|
||||
printf '%s' "$tag" > release/.shrink-sdk-release-tag
|
||||
|
||||
- name: Validate immutable release version
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
tag="$(git describe --exact-match --tags HEAD)"
|
||||
cd release
|
||||
tag="$(cat .shrink-sdk-release-tag)"
|
||||
version="$(node -p "require('./package.json').version")"
|
||||
test "$tag" = "v$version"
|
||||
npm pack --dry-run
|
||||
@@ -40,10 +57,11 @@ jobs:
|
||||
run: |
|
||||
set -eu
|
||||
: "${NODE_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
||||
cd release
|
||||
npmrc="$HOME/.npmrc"
|
||||
cleanup() { rm -f "$npmrc"; }
|
||||
trap cleanup EXIT
|
||||
printf '%s\n' \
|
||||
'registry=https://git.crash.work/api/packages/ShrinkSDK/npm/' \
|
||||
'//git.crash.work/api/packages/ShrinkSDK/npm/:_authToken=${NODE_AUTH_TOKEN}' > "$npmrc"
|
||||
npm publish --registry=https://git.crash.work/api/packages/ShrinkSDK/npm/
|
||||
npm publish --registry=https://git.crash.work/api/packages/ShrinkSDK/npm/
|
||||
@@ -26,12 +26,17 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
machine_id_file="/root/.local/share/unity3d/Unity/.machine-id"
|
||||
if test -s "$machine_id_file"; then
|
||||
cat "$machine_id_file" > /etc/machine-id
|
||||
echo "Unity machine identity restored"
|
||||
fi
|
||||
git config --global url."https://ghfast.top/https://github.com/".insteadOf "https://github.com/"
|
||||
unity_bin="$(command -v unity-editor || command -v unity || command -v Unity || true)"
|
||||
test -n "$unity_bin"
|
||||
"$unity_bin" \
|
||||
-batchmode \
|
||||
-nographics \
|
||||
-quit \
|
||||
-projectPath "$PWD/Development~/UnityProject" \
|
||||
-runTests \
|
||||
-testPlatform EditMode \
|
||||
|
||||
+16
@@ -30,6 +30,16 @@
|
||||
/[Aa]ssets/Plugins/Editor/JetBrains*
|
||||
# Jetbrains Rider personal-layer settings
|
||||
*.DotSettings.user
|
||||
!DotNet~/*.csproj
|
||||
!DotNet~/**/*.csproj
|
||||
/DotNet~/**/[Bb]in/
|
||||
/DotNet~/**/[Oo]bj/
|
||||
/Godot~/**/[Bb]in/
|
||||
/Godot~/**/[Oo]bj/
|
||||
/artifacts/
|
||||
/packages/
|
||||
!DotNet~/**/*.csproj
|
||||
!Godot~/**/*.csproj
|
||||
|
||||
# Visual Studio cache directory
|
||||
.vs/
|
||||
@@ -41,6 +51,10 @@
|
||||
ExportedObj/
|
||||
.consulo/
|
||||
*.csproj
|
||||
!Tools~/DotNet/**/*.csproj
|
||||
!Samples~/DotNetConsole/*.csproj
|
||||
/Samples~/DotNetConsole/[Bb]in/
|
||||
/Samples~/DotNetConsole/[Oo]bj/
|
||||
*.unityproj
|
||||
*.sln
|
||||
*.suo
|
||||
@@ -107,3 +121,5 @@ InitTestScene*.unity*
|
||||
/Tools~/**/[Oo]bj/
|
||||
*.user
|
||||
*.DotSettings.user
|
||||
!DotNet~/*.csproj
|
||||
!DotNet~/**/*.csproj
|
||||
@@ -6,3 +6,9 @@ Tools~/
|
||||
*.sln
|
||||
*.user
|
||||
*.DotSettings.user
|
||||
DotNet~/
|
||||
Godot~/
|
||||
NuGet.Config
|
||||
Directory.Build.props
|
||||
NuGet.Config.meta
|
||||
Directory.Build.props.meta
|
||||
@@ -2,6 +2,41 @@
|
||||
|
||||
本文件记录 `ShrinkEventBus` 在当前工作区中的包内变更。
|
||||
|
||||
## [2.3.2] - 2026-11-06
|
||||
|
||||
### Performance
|
||||
|
||||
- 诊断观察者列表在订阅或退订时生成不可变快照,消除每次诊断派发的列表分配,保留逐个观察者的异常隔离。
|
||||
- 同步排队直接保存回调,移除额外闭包;主线程调度器复用泵送回调,保持延后事件的批次边界。
|
||||
|
||||
## [2.3.0] - 2026-11-06
|
||||
|
||||
### Added
|
||||
|
||||
- 新增 `EventBus.PostDeferred(bus, event)`,把 MainThread Bus 的事件推迟到下一次主线程泵送;重入发布不会在同一次泵送中立即执行。
|
||||
- 新增公开的 `EventBus.ObserveDiagnostics(...)` 与 `ShrinkEventDiagnostic`,供编辑器和外部工具读取分发时间、Bus、调度器、线程、耗时、结果与同步标记,不再依赖私有事件或反射。
|
||||
- `ShrinkPostFailure` 新增 `DeferredUnsupported`,用于 `Inline`、`DedicatedThread`、`TaskPool` 或宿主没有延后派发能力的情况。
|
||||
|
||||
### Changed
|
||||
|
||||
- Runtime Abstractions 0.2.0 新增 `IShrinkDeferredMainThreadDispatcher`;Unity PlayerLoop 与共享 `SynchronizationContext` 调度器实现该接口。
|
||||
- 诊断观察者逐个隔离异常,单个观察者失败不会阻断业务 handler 或其他观察者。
|
||||
|
||||
## [2.2.3] - 2026-10-03
|
||||
|
||||
- Unity 可独立通过 Git URL 安装,必装依赖仅保留 UniTask 和官方 Mono.Cecil。
|
||||
- Shared Runtime 与 Shared CodeGen 改为可选集成,由包版本宏自动启用。
|
||||
- 内置独立特性订阅织入器,支持实例、静态、UniTask 和 MonoBehaviour 生命周期绑定;安装 Shared CodeGen 后由共享生成器接管。
|
||||
- Unity 主线程调度契约改为 `IShrinkEventBusMainThreadDispatcher`;共享接口通过 `ShrinkSharedMainThreadDispatcher` 适配,.NET/Godot 接口不变。
|
||||
- 独立验证工程取消私有 registry 要求,增加外部消费程序集的生成绑定测试及可选调度适配测试。
|
||||
|
||||
## [2.0.1] - 2026-08-28
|
||||
|
||||
### Added
|
||||
|
||||
- `ShrinkEventSubscriberAttribute` 新增显式 `Lifetime`,选择 `AwakeToDestroy` 的 `MonoBehaviour` 会由 ILPostProcessor 在编译期织入生成绑定的 `Attach` 与 `Dispose`,禁用对象时保持订阅,销毁时自动释放。
|
||||
- 自动生命周期支持已有或缺失的 `Awake` / `OnDestroy`,并保留可重写基类生命周期调用;默认仍为 `Manual`,避免既有 2.0 使用方升级后重复订阅。
|
||||
|
||||
## [2.0.0] - 2026-08-23
|
||||
|
||||
### Added
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
#nullable enable
|
||||
#if !SHRINK_EVENTBUS_HAS_SHARED_CODEGEN
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Mono.Cecil;
|
||||
using Mono.Cecil.Cil;
|
||||
|
||||
namespace ShrinkEventBus.CodeGen
|
||||
{
|
||||
internal static class EventBusAssemblyWeaver
|
||||
{
|
||||
private const string EventRuntime = "ShrinkEventBus.Runtime";
|
||||
private const string Marker = "ShrinkEventBus.Generated.StandaloneWeaveMarker";
|
||||
|
||||
public static bool Weave(ModuleDefinition module)
|
||||
{
|
||||
if (!References(module, EventRuntime) || module.GetType(Marker) != null)
|
||||
return false;
|
||||
var instances = 0;
|
||||
var statics = 0;
|
||||
WeaveEventBus(module, ref instances, ref statics);
|
||||
if (instances == 0 && statics == 0)
|
||||
return false;
|
||||
module.Types.Add(new TypeDefinition("ShrinkEventBus.Generated", "StandaloneWeaveMarker",
|
||||
TypeAttributes.NotPublic | TypeAttributes.Abstract | TypeAttributes.Sealed, module.TypeSystem.Object));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void WeaveEventBus(ModuleDefinition module,
|
||||
ref int instanceCount, ref int staticCount)
|
||||
{
|
||||
var subscriberAttribute = RequireType(module, "ShrinkEventBus.ShrinkEventSubscriberAttribute", EventRuntime);
|
||||
var subscribeAttribute = RequireType(module, "ShrinkEventBus.ShrinkSubscribeAttribute", EventRuntime);
|
||||
var allTypes = AllTypes(module.Types).Where(type => !type.IsInterface).ToArray();
|
||||
foreach (var type in allTypes.Where(type => HasAttribute(type, subscriberAttribute)))
|
||||
{
|
||||
var instanceHandlers = type.Methods.Where(method => !method.IsStatic && HasAttribute(method, subscribeAttribute)).ToArray();
|
||||
if (instanceHandlers.Length > 0)
|
||||
{
|
||||
var lifetime = ReadInt(type.CustomAttributes.First(a => a.AttributeType.FullName == subscriberAttribute.FullName), "Lifetime", 0);
|
||||
if (InjectInstanceBinding(module, type, instanceHandlers, subscribeAttribute))
|
||||
instanceCount++;
|
||||
if (lifetime == 1)
|
||||
InjectAwakeToDestroyLifetime(type, module);
|
||||
else if (lifetime != 0)
|
||||
throw new InvalidOperationException($"{type.FullName}: unsupported subscriber lifetime.");
|
||||
}
|
||||
}
|
||||
|
||||
var staticTypes = allTypes.Where(type => HasAttribute(type, subscriberAttribute))
|
||||
.Where(type => type.Methods.Any(method => method.IsStatic && HasAttribute(method, subscribeAttribute)))
|
||||
.ToArray();
|
||||
if (staticTypes.Length > 0)
|
||||
{
|
||||
staticCount = staticTypes.Sum(type => type.Methods.Count(method => method.IsStatic && HasAttribute(method, subscribeAttribute)));
|
||||
InjectStaticBootstrap(module, staticTypes, subscriberAttribute, subscribeAttribute);
|
||||
}
|
||||
}
|
||||
|
||||
private static void InjectAwakeToDestroyLifetime(TypeDefinition type, ModuleDefinition module)
|
||||
{
|
||||
if (!InheritsFrom(type, "UnityEngine.MonoBehaviour"))
|
||||
throw new InvalidOperationException($"[ShrinkEventSubscriber(Lifetime = AwakeToDestroy)] requires MonoBehaviour: {type.FullName}.");
|
||||
|
||||
const string bindingFieldName = "__shrinkEventBusAwakeToDestroyBinding";
|
||||
if (type.Fields.Any(field => field.Name == bindingFieldName))
|
||||
throw new InvalidOperationException($"Reserved generated field already exists on {type.FullName}: {bindingFieldName}.");
|
||||
|
||||
var disposableType = new TypeReference("System", "IDisposable", module, module.TypeSystem.CoreLibrary);
|
||||
var bindingField = new FieldDefinition(bindingFieldName, FieldAttributes.Private, disposableType);
|
||||
type.Fields.Add(bindingField);
|
||||
var eventBusType = RequireType(module, "ShrinkEventBus.EventBus", EventRuntime);
|
||||
var attachMethod = ImportMethod(module, eventBusType,
|
||||
method => method.Name == "Attach" && method.IsStatic && method.Parameters.Count == 2);
|
||||
var disposeMethod = new MethodReference("Dispose", module.TypeSystem.Void, disposableType) { HasThis = true };
|
||||
InjectAwake(type, module, bindingField, attachMethod);
|
||||
InjectOnDestroy(type, module, bindingField, disposeMethod);
|
||||
}
|
||||
|
||||
private static void InjectAwake(TypeDefinition type, ModuleDefinition module,
|
||||
FieldDefinition bindingField, MethodReference attachMethod)
|
||||
{
|
||||
var awake = type.Methods.FirstOrDefault(method =>
|
||||
method.Name == "Awake" && !method.IsStatic && method.Parameters.Count == 0);
|
||||
if (awake != null)
|
||||
{
|
||||
InsertAttachAtStart(awake, module, bindingField, attachMethod);
|
||||
return;
|
||||
}
|
||||
|
||||
var baseAwake = FindBaseMethodReference(type, "Awake", module);
|
||||
awake = new MethodDefinition("Awake",
|
||||
baseAwake != null
|
||||
? MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual
|
||||
: MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot,
|
||||
module.TypeSystem.Void);
|
||||
awake.Body.InitLocals = true;
|
||||
var il = awake.Body.GetILProcessor();
|
||||
if (baseAwake != null)
|
||||
{
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Call, baseAwake);
|
||||
}
|
||||
EmitAttach(il, awake, module, bindingField, attachMethod);
|
||||
il.Emit(OpCodes.Ret);
|
||||
type.Methods.Add(awake);
|
||||
}
|
||||
|
||||
private static void InjectOnDestroy(TypeDefinition type, ModuleDefinition module,
|
||||
FieldDefinition bindingField, MethodReference disposeMethod)
|
||||
{
|
||||
var onDestroy = type.Methods.FirstOrDefault(method =>
|
||||
method.Name == "OnDestroy" && !method.IsStatic && method.Parameters.Count == 0);
|
||||
if (onDestroy != null)
|
||||
{
|
||||
InsertDisposeAtStart(onDestroy, bindingField, disposeMethod);
|
||||
return;
|
||||
}
|
||||
|
||||
var baseOnDestroy = FindBaseMethodReference(type, "OnDestroy", module);
|
||||
onDestroy = new MethodDefinition("OnDestroy",
|
||||
baseOnDestroy != null
|
||||
? MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual
|
||||
: MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot,
|
||||
module.TypeSystem.Void);
|
||||
var il = onDestroy.Body.GetILProcessor();
|
||||
EmitDispose(il, bindingField, disposeMethod);
|
||||
if (baseOnDestroy != null)
|
||||
{
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Call, baseOnDestroy);
|
||||
}
|
||||
il.Emit(OpCodes.Ret);
|
||||
type.Methods.Add(onDestroy);
|
||||
}
|
||||
|
||||
private static void InsertAttachAtStart(MethodDefinition method, ModuleDefinition module,
|
||||
FieldDefinition bindingField, MethodReference attachMethod)
|
||||
{
|
||||
if (!method.HasBody || method.Body.Instructions.Count == 0)
|
||||
throw new InvalidOperationException($"Awake has no body: {method.FullName}.");
|
||||
method.Body.InitLocals = true;
|
||||
var processor = method.Body.GetILProcessor();
|
||||
var instructions = BuildAttachInstructions(processor, method, module, bindingField, attachMethod);
|
||||
var first = method.Body.Instructions[0];
|
||||
foreach (var instruction in instructions)
|
||||
processor.InsertBefore(first, instruction);
|
||||
}
|
||||
|
||||
private static void EmitAttach(ILProcessor il, MethodDefinition method, ModuleDefinition module,
|
||||
FieldDefinition bindingField, MethodReference attachMethod)
|
||||
{
|
||||
foreach (var instruction in BuildAttachInstructions(il, method, module, bindingField, attachMethod))
|
||||
il.Append(instruction);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<Instruction> BuildAttachInstructions(ILProcessor il,
|
||||
MethodDefinition method, ModuleDefinition module, FieldDefinition bindingField,
|
||||
MethodReference attachMethod)
|
||||
{
|
||||
var defaultBusType = module.ImportReference(attachMethod.Parameters[1].ParameterType);
|
||||
var defaultBus = new VariableDefinition(defaultBusType);
|
||||
method.Body.Variables.Add(defaultBus);
|
||||
var attached = il.Create(OpCodes.Nop);
|
||||
return new[]
|
||||
{
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldfld, bindingField),
|
||||
il.Create(OpCodes.Brtrue_S, attached),
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldloca_S, defaultBus),
|
||||
il.Create(OpCodes.Initobj, defaultBusType),
|
||||
il.Create(OpCodes.Ldloc, defaultBus),
|
||||
il.Create(OpCodes.Call, attachMethod),
|
||||
il.Create(OpCodes.Stfld, bindingField),
|
||||
attached
|
||||
};
|
||||
}
|
||||
|
||||
private static void InsertDisposeAtStart(MethodDefinition method,
|
||||
FieldDefinition bindingField, MethodReference disposeMethod)
|
||||
{
|
||||
if (!method.HasBody || method.Body.Instructions.Count == 0)
|
||||
throw new InvalidOperationException($"OnDestroy has no body: {method.FullName}.");
|
||||
var processor = method.Body.GetILProcessor();
|
||||
var instructions = BuildDisposeInstructions(processor, bindingField, disposeMethod);
|
||||
var first = method.Body.Instructions[0];
|
||||
foreach (var instruction in instructions)
|
||||
processor.InsertBefore(first, instruction);
|
||||
}
|
||||
|
||||
private static void EmitDispose(ILProcessor il, FieldDefinition bindingField,
|
||||
MethodReference disposeMethod)
|
||||
{
|
||||
foreach (var instruction in BuildDisposeInstructions(il, bindingField, disposeMethod))
|
||||
il.Append(instruction);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<Instruction> BuildDisposeInstructions(ILProcessor il,
|
||||
FieldDefinition bindingField, MethodReference disposeMethod)
|
||||
{
|
||||
var disposed = il.Create(OpCodes.Nop);
|
||||
return new[]
|
||||
{
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldfld, bindingField),
|
||||
il.Create(OpCodes.Brfalse_S, disposed),
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldfld, bindingField),
|
||||
il.Create(OpCodes.Callvirt, disposeMethod),
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldnull),
|
||||
il.Create(OpCodes.Stfld, bindingField),
|
||||
disposed
|
||||
};
|
||||
}
|
||||
|
||||
private static MethodReference? FindBaseMethodReference(TypeDefinition type,
|
||||
string methodName, ModuleDefinition module)
|
||||
{
|
||||
try
|
||||
{
|
||||
var baseTypeReference = type.BaseType;
|
||||
while (baseTypeReference != null)
|
||||
{
|
||||
var baseType = baseTypeReference.Resolve();
|
||||
if (baseType == null) break;
|
||||
var method = baseType.Methods.FirstOrDefault(candidate =>
|
||||
candidate.Name == methodName && !candidate.IsStatic && candidate.IsVirtual &&
|
||||
candidate.Parameters.Count == 0);
|
||||
if (method != null)
|
||||
{
|
||||
if (baseTypeReference is GenericInstanceType genericBase)
|
||||
{
|
||||
return new MethodReference(method.Name, module.ImportReference(method.ReturnType),
|
||||
module.ImportReference(genericBase))
|
||||
{
|
||||
HasThis = method.HasThis,
|
||||
ExplicitThis = method.ExplicitThis,
|
||||
CallingConvention = method.CallingConvention
|
||||
};
|
||||
}
|
||||
return module.ImportReference(method);
|
||||
}
|
||||
baseTypeReference = baseType.BaseType;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool InheritsFrom(TypeDefinition type, string expectedFullName)
|
||||
{
|
||||
var current = type.BaseType;
|
||||
while (current != null)
|
||||
{
|
||||
if (current.FullName == expectedFullName) return true;
|
||||
try { current = current.Resolve()?.BaseType; }
|
||||
catch { return false; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool InjectInstanceBinding(ModuleDefinition module, TypeDefinition owner,
|
||||
IReadOnlyList<MethodDefinition> handlers, TypeReference subscribeAttribute)
|
||||
{
|
||||
var generatedInterface = RequireType(module, "ShrinkEventBus.IShrinkGeneratedSubscriber", EventRuntime);
|
||||
if (owner.Interfaces.Any(item => item.InterfaceType.FullName == generatedInterface.FullName))
|
||||
return false;
|
||||
var resolverType = RequireType(module, "ShrinkEventBus.IShrinkBusResolver", EventRuntime);
|
||||
var busKeyType = RequireType(module, "ShrinkEventBus.ShrinkBusKey", EventRuntime);
|
||||
var bindingType = RequireType(module, "ShrinkEventBus.ShrinkEventBinding", EventRuntime);
|
||||
var helperType = RequireType(module, "ShrinkEventBus.ShrinkGeneratedBinding", EventRuntime);
|
||||
var disposableType = RequireType(module, "System.IDisposable", module.TypeSystem.CoreLibrary.Name);
|
||||
var nullableBusKey = GenericType(module, "System.Nullable`1", true, busKeyType);
|
||||
var bindingCtor = ImportMethod(module, bindingType, method => method.IsConstructor && method.Parameters.Count == 0);
|
||||
var bindingAdd = ImportMethod(module, bindingType, method => method.Name == "Add" && method.Parameters.Count == 1);
|
||||
var interfaceMethod = ImportMethod(module, generatedInterface, method => method.Name == "AttachGenerated");
|
||||
var syncSubscribe = ImportMethod(module, helperType, method => method.Name == "Subscribe" && method.HasGenericParameters);
|
||||
var asyncSubscribe = ImportMethod(module, helperType, method => method.Name == "SubscribeAsync" && method.HasGenericParameters);
|
||||
var legacySubscribe = ImportMethod(module, helperType, method => method.Name == "SubscribeAsyncLegacy" && method.HasGenericParameters);
|
||||
var asyncHandlerType = RequireType(module, "ShrinkEventBus.ShrinkAsyncEventHandler`1", EventRuntime);
|
||||
|
||||
var generated = new MethodDefinition("ShrinkEventBus.IShrinkGeneratedSubscriber.AttachGenerated",
|
||||
MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual,
|
||||
disposableType);
|
||||
generated.Parameters.Add(new ParameterDefinition("resolver", ParameterAttributes.None, resolverType));
|
||||
generated.Parameters.Add(new ParameterDefinition("defaultBus", ParameterAttributes.Optional, nullableBusKey));
|
||||
generated.Overrides.Add(interfaceMethod);
|
||||
generated.Body.InitLocals = true;
|
||||
var bindingLocal = new VariableDefinition(bindingType);
|
||||
generated.Body.Variables.Add(bindingLocal);
|
||||
var il = generated.Body.GetILProcessor();
|
||||
il.Emit(OpCodes.Newobj, bindingCtor);
|
||||
il.Emit(OpCodes.Stloc, bindingLocal);
|
||||
var classDefaultBus = ReadString(owner.CustomAttributes.First(a => a.AttributeType.FullName == "ShrinkEventBus.ShrinkEventSubscriberAttribute"), "DefaultBus");
|
||||
foreach (var handler in handlers)
|
||||
EmitInstanceSubscription(module, il, handler, handler.CustomAttributes.First(a => a.AttributeType.FullName == subscribeAttribute.FullName), classDefaultBus,
|
||||
bindingLocal, bindingAdd, syncSubscribe, asyncSubscribe, legacySubscribe, asyncHandlerType);
|
||||
il.Emit(OpCodes.Ldloc, bindingLocal);
|
||||
il.Emit(OpCodes.Ret);
|
||||
owner.Interfaces.Add(new InterfaceImplementation(generatedInterface));
|
||||
owner.Methods.Add(generated);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void EmitInstanceSubscription(ModuleDefinition module, ILProcessor il, MethodDefinition handler,
|
||||
CustomAttribute attribute, string classDefaultBus, VariableDefinition bindingLocal, MethodReference bindingAdd,
|
||||
MethodReference syncSubscribe, MethodReference asyncSubscribe, MethodReference legacySubscribe, TypeReference asyncHandlerType)
|
||||
{
|
||||
var signature = ResolveEventHandler(module, handler, syncSubscribe, asyncSubscribe, legacySubscribe, asyncHandlerType);
|
||||
var bus = ReadString(attribute, "Bus");
|
||||
if (string.IsNullOrWhiteSpace(bus)) bus = classDefaultBus;
|
||||
il.Emit(OpCodes.Ldloc, bindingLocal);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Ldarg_2);
|
||||
il.Emit(OpCodes.Ldstr, bus ?? string.Empty);
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldftn, module.ImportReference(handler));
|
||||
il.Emit(OpCodes.Newobj, DelegateConstructor(module, signature.DelegateType));
|
||||
EmitOptions(il, attribute);
|
||||
il.Emit(OpCodes.Call, signature.Method);
|
||||
il.Emit(OpCodes.Callvirt, bindingAdd);
|
||||
}
|
||||
|
||||
private static void InjectStaticBootstrap(ModuleDefinition module, IReadOnlyList<TypeDefinition> types,
|
||||
TypeReference subscriberAttribute, TypeReference subscribeAttribute)
|
||||
{
|
||||
if (module.Types.Any(type => type.FullName == "ShrinkEventBus.Generated.ShrinkGeneratedStaticBindings"))
|
||||
return;
|
||||
var registry = RequireType(module, "ShrinkEventBus.ShrinkStaticBindingRegistry", EventRuntime);
|
||||
var syncRegister = ImportMethod(module, registry, method => method.Name == "Register" && method.HasGenericParameters);
|
||||
var asyncRegister = ImportMethod(module, registry, method => method.Name == "RegisterAsync" && method.HasGenericParameters);
|
||||
var legacyRegister = ImportMethod(module, registry, method => method.Name == "RegisterAsyncLegacy" && method.HasGenericParameters);
|
||||
var asyncHandlerType = RequireType(module, "ShrinkEventBus.ShrinkAsyncEventHandler`1", EventRuntime);
|
||||
var bootstrap = new TypeDefinition("ShrinkEventBus.Generated", "ShrinkGeneratedStaticBindings",
|
||||
TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.NotPublic, module.TypeSystem.Object);
|
||||
module.Types.Add(bootstrap);
|
||||
var register = new MethodDefinition("Register", MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig, module.TypeSystem.Void);
|
||||
bootstrap.Methods.Add(register);
|
||||
var il = register.Body.GetILProcessor();
|
||||
foreach (var type in types)
|
||||
{
|
||||
var classBus = ReadString(type.CustomAttributes.First(a => a.AttributeType.FullName == subscriberAttribute.FullName), "DefaultBus");
|
||||
foreach (var handler in type.Methods.Where(method => method.IsStatic && HasAttribute(method, subscribeAttribute)).ToArray())
|
||||
{
|
||||
var attribute = handler.CustomAttributes.First(a => a.AttributeType.FullName == subscribeAttribute.FullName);
|
||||
var signature = ResolveEventHandler(module, handler, syncRegister, asyncRegister, legacyRegister, asyncHandlerType);
|
||||
var bus = ReadString(attribute, "Bus");
|
||||
if (string.IsNullOrWhiteSpace(bus)) bus = classBus;
|
||||
var bridge = CreateStaticBridge(module, handler);
|
||||
il.Emit(OpCodes.Ldstr, bus ?? string.Empty);
|
||||
il.Emit(OpCodes.Ldnull);
|
||||
il.Emit(OpCodes.Ldftn, bridge);
|
||||
il.Emit(OpCodes.Newobj, DelegateConstructor(module, signature.DelegateType));
|
||||
EmitOptions(il, attribute);
|
||||
il.Emit(OpCodes.Call, signature.Method);
|
||||
}
|
||||
}
|
||||
il.Emit(OpCodes.Ret);
|
||||
var moduleType = module.Types.First(type => type.Name == "<Module>");
|
||||
var initializer = moduleType.Methods.FirstOrDefault(method => method.Name == ".cctor");
|
||||
if (initializer == null)
|
||||
{
|
||||
initializer = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig |
|
||||
MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, module.TypeSystem.Void);
|
||||
initializer.Body.GetILProcessor().Emit(OpCodes.Ret);
|
||||
moduleType.Methods.Add(initializer);
|
||||
}
|
||||
initializer.Body.GetILProcessor().InsertBefore(initializer.Body.Instructions[0], Instruction.Create(OpCodes.Call, register));
|
||||
}
|
||||
|
||||
private static (MethodReference Method, TypeReference DelegateType) ResolveEventHandler(ModuleDefinition module,
|
||||
MethodDefinition handler, MethodReference sync, MethodReference async, MethodReference legacy, TypeReference asyncHandlerType)
|
||||
{
|
||||
if (handler.Parameters.Count is < 1 or > 2)
|
||||
throw new InvalidOperationException($"{handler.FullName}: [ShrinkSubscribe] requires one event parameter and an optional CancellationToken.");
|
||||
var eventType = module.ImportReference(handler.Parameters[0].ParameterType);
|
||||
var eventInterface = RequireType(module, "ShrinkEventBus.IShrinkEvent", EventRuntime);
|
||||
if (!Implements(eventType, eventInterface.FullName))
|
||||
throw new InvalidOperationException($"{handler.FullName}: event parameter must implement IShrinkEvent.");
|
||||
|
||||
MethodReference open;
|
||||
TypeReference delegateType;
|
||||
if (handler.ReturnType.MetadataType == MetadataType.Void && handler.Parameters.Count == 1)
|
||||
{
|
||||
open = sync;
|
||||
delegateType = GenericType(module, "System.Action`1", false, eventType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" && handler.Parameters.Count == 1)
|
||||
{
|
||||
open = legacy;
|
||||
delegateType = GenericType(module, "System.Func`2", false, eventType, module.ImportReference(handler.ReturnType));
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" && handler.Parameters.Count == 2 &&
|
||||
handler.Parameters[1].ParameterType.FullName == "System.Threading.CancellationToken")
|
||||
{
|
||||
open = async;
|
||||
delegateType = new GenericInstanceType(asyncHandlerType) { GenericArguments = { eventType } };
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException($"Unsupported [ShrinkSubscribe] signature: {handler.FullName}.");
|
||||
var closed = new GenericInstanceMethod(open);
|
||||
closed.GenericArguments.Add(eventType);
|
||||
return (closed, delegateType);
|
||||
}
|
||||
|
||||
private static MethodReference CreateStaticBridge(ModuleDefinition module, MethodDefinition handler)
|
||||
{
|
||||
var bridge = new MethodDefinition($"ShrinkEventBus.GeneratedStaticHandler_{handler.MetadataToken.ToInt32():X8}",
|
||||
MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig, module.ImportReference(handler.ReturnType));
|
||||
foreach (var parameter in handler.Parameters)
|
||||
bridge.Parameters.Add(new ParameterDefinition(parameter.Name, parameter.Attributes, module.ImportReference(parameter.ParameterType)));
|
||||
var il = bridge.Body.GetILProcessor();
|
||||
foreach (var parameter in bridge.Parameters) il.Emit(OpCodes.Ldarg, parameter);
|
||||
il.Emit(OpCodes.Call, module.ImportReference(handler));
|
||||
il.Emit(OpCodes.Ret);
|
||||
handler.DeclaringType.Methods.Add(bridge);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
private static void EmitOptions(ILProcessor il, CustomAttribute attribute)
|
||||
{
|
||||
il.Emit(OpCodes.Ldc_I4, ReadInt(attribute, "Priority", 2));
|
||||
il.Emit(OpCodes.Ldc_I4, ReadInt(attribute, "NumericPriority", 0));
|
||||
il.Emit(ReadBool(attribute, "ReceiveCanceled", false) ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
|
||||
}
|
||||
|
||||
private static bool References(ModuleDefinition module, string assemblyName) =>
|
||||
module.AssemblyReferences.Any(reference => string.Equals(reference.Name, assemblyName, StringComparison.Ordinal));
|
||||
|
||||
private static TypeReference RequireType(ModuleDefinition module, string fullName, string assemblyName) =>
|
||||
FindType(module, fullName, assemblyName) ?? throw new InvalidOperationException($"Required type {fullName} was not found in {assemblyName}.");
|
||||
|
||||
private static TypeReference? FindType(ModuleDefinition module, string fullName, string assemblyName)
|
||||
{
|
||||
if (string.Equals(module.Assembly.Name.Name, assemblyName, StringComparison.Ordinal))
|
||||
return module.GetType(fullName);
|
||||
var reference = module.AssemblyReferences.FirstOrDefault(item => string.Equals(item.Name, assemblyName, StringComparison.Ordinal));
|
||||
if (reference == null) return null;
|
||||
var assembly = module.AssemblyResolver.Resolve(reference);
|
||||
return assembly?.MainModule.GetType(fullName) is { } definition ? module.ImportReference(definition) : null;
|
||||
}
|
||||
|
||||
private static MethodReference ImportMethod(ModuleDefinition module, TypeReference type, Func<MethodDefinition, bool> predicate)
|
||||
{
|
||||
var definition = type.Resolve() ?? throw new InvalidOperationException($"Unable to resolve {type.FullName}.");
|
||||
var method = definition.Methods.SingleOrDefault(predicate) ?? throw new InvalidOperationException($"Required method was not found on {type.FullName}.");
|
||||
return module.ImportReference(method);
|
||||
}
|
||||
|
||||
private static IEnumerable<TypeDefinition> AllTypes(IEnumerable<TypeDefinition> roots)
|
||||
{
|
||||
foreach (var type in roots)
|
||||
{
|
||||
yield return type;
|
||||
foreach (var nested in AllTypes(type.NestedTypes)) yield return nested;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasAttribute(ICustomAttributeProvider provider, TypeReference attribute) => HasAttribute(provider, attribute.FullName);
|
||||
private static bool HasAttribute(ICustomAttributeProvider provider, string fullName) => provider.CustomAttributes.Any(a => a.AttributeType.FullName == fullName);
|
||||
|
||||
private static bool Implements(TypeReference type, string interfaceFullName)
|
||||
{
|
||||
try
|
||||
{
|
||||
TypeDefinition? current = type.Resolve();
|
||||
while (current != null)
|
||||
{
|
||||
if (current.Interfaces.Any(item => item.InterfaceType.FullName == interfaceFullName)) return true;
|
||||
current = current.BaseType?.Resolve();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return false;
|
||||
}
|
||||
|
||||
private static TypeReference GenericType(ModuleDefinition module, string name, bool valueType, params TypeReference[] arguments)
|
||||
{
|
||||
var open = new TypeReference("System", name.Substring(name.LastIndexOf('.') + 1), module, module.TypeSystem.CoreLibrary, valueType);
|
||||
var result = new GenericInstanceType(open);
|
||||
foreach (var argument in arguments) result.GenericArguments.Add(argument);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static MethodReference DelegateConstructor(ModuleDefinition module, TypeReference delegateType)
|
||||
{
|
||||
var ctor = new MethodReference(".ctor", module.TypeSystem.Void, delegateType) { HasThis = true };
|
||||
ctor.Parameters.Add(new ParameterDefinition(module.TypeSystem.Object));
|
||||
ctor.Parameters.Add(new ParameterDefinition(module.TypeSystem.IntPtr));
|
||||
return ctor;
|
||||
}
|
||||
|
||||
private static string ReadString(CustomAttribute attribute, string name) =>
|
||||
attribute.Properties.FirstOrDefault(item => item.Name == name).Argument.Value as string ?? string.Empty;
|
||||
private static int ReadInt(CustomAttribute attribute, string name, int fallback) =>
|
||||
attribute.Properties.FirstOrDefault(item => item.Name == name) is { Name: not null } item ? Convert.ToInt32(item.Argument.Value) : fallback;
|
||||
private static bool ReadBool(CustomAttribute attribute, string name, bool fallback) =>
|
||||
attribute.Properties.FirstOrDefault(item => item.Name == name) is { Name: not null } item ? Convert.ToBoolean(item.Argument.Value) : fallback;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 578fc703a63d4b8e9a414eb8c19a472a
|
||||
@@ -1,13 +1,10 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Mono.Cecil;
|
||||
using Mono.Cecil.Cil;
|
||||
using Mono.Cecil.Rocks;
|
||||
using Mono.Cecil.Pdb;
|
||||
using Unity.CompilationPipeline.Common.Diagnostics;
|
||||
using Unity.CompilationPipeline.Common.ILPostProcessing;
|
||||
|
||||
@@ -15,515 +12,68 @@ namespace ShrinkEventBus.CodeGen
|
||||
{
|
||||
public sealed class EventBusILPostProcessor : ILPostProcessor
|
||||
{
|
||||
private const string RuntimeAssemblyName = "ShrinkEventBus.Runtime";
|
||||
public override ILPostProcessor GetInstance() => this;
|
||||
|
||||
public override bool WillProcess(ICompiledAssembly compiledAssembly)
|
||||
{
|
||||
if (!ReferencesAssembly(compiledAssembly, RuntimeAssemblyName))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
#if SHRINK_EVENTBUS_HAS_SHARED_CODEGEN
|
||||
// The shared processor owns event weaving when its package is installed.
|
||||
return false;
|
||||
#else
|
||||
return compiledAssembly.Name != "ShrinkEventBus.Runtime" &&
|
||||
compiledAssembly.References.Any(path =>
|
||||
Path.GetFileNameWithoutExtension(path) == "ShrinkEventBus.Runtime");
|
||||
#endif
|
||||
}
|
||||
|
||||
public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly)
|
||||
{
|
||||
var diagnostics = new List<DiagnosticMessage>();
|
||||
#if !SHRINK_EVENTBUS_HAS_SHARED_CODEGEN
|
||||
if (!WillProcess(compiledAssembly))
|
||||
return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, diagnostics);
|
||||
|
||||
var assemblyDefinition = AssemblyDefinitionFor(compiledAssembly);
|
||||
var module = assemblyDefinition.MainModule;
|
||||
|
||||
try
|
||||
{
|
||||
var generatedSubscriberType = FindType(module, "ShrinkEventBus.ShrinkEventSubscriberAttribute", RuntimeAssemblyName);
|
||||
var generatedSubscribeType = FindType(module, "ShrinkEventBus.ShrinkSubscribeAttribute", RuntimeAssemblyName);
|
||||
if (generatedSubscriberType == null || generatedSubscribeType == null)
|
||||
return GetResult(assemblyDefinition, diagnostics);
|
||||
|
||||
foreach (var type in GetAllTypes(module.Types)
|
||||
.Where(type => !type.IsInterface && !type.IsAbstract)
|
||||
.Where(type => HasAttribute(type, generatedSubscriberType))
|
||||
.Where(type => type.Methods.Any(method =>
|
||||
!method.IsStatic && HasAttribute(method, generatedSubscribeType))))
|
||||
using var resolver = new PostProcessorAssemblyResolver(compiledAssembly);
|
||||
using var pe = new MemoryStream(compiledAssembly.InMemoryAssembly.PeData);
|
||||
var pdbData = compiledAssembly.InMemoryAssembly.PdbData;
|
||||
var hasSymbols = pdbData != null && pdbData.Length > 0;
|
||||
using var pdb = hasSymbols ? new MemoryStream(pdbData!) : null;
|
||||
using var assembly = AssemblyDefinition.ReadAssembly(pe, new ReaderParameters
|
||||
{
|
||||
InjectGeneratedBinding(type, module, generatedSubscribeType);
|
||||
}
|
||||
|
||||
var staticSubscriberTypes = GetAllTypes(module.Types)
|
||||
.Where(type => HasAttribute(type, generatedSubscriberType))
|
||||
.Where(type => type.Methods.Any(method =>
|
||||
method.IsStatic && HasAttribute(method, generatedSubscribeType)))
|
||||
.ToArray();
|
||||
if (staticSubscriberTypes.Length > 0)
|
||||
InjectStaticBootstrap(module, staticSubscriberTypes, generatedSubscribeType);
|
||||
|
||||
AssemblyResolver = resolver,
|
||||
ReadingMode = ReadingMode.Immediate,
|
||||
ReflectionImporterProvider = new PostProcessorReflectionImporterProvider(),
|
||||
ReadSymbols = hasSymbols,
|
||||
SymbolStream = pdb,
|
||||
SymbolReaderProvider = hasSymbols ? new PortablePdbReaderProvider() : null
|
||||
});
|
||||
resolver.AddAssemblyDefinitionBeingOperatedOn(assembly);
|
||||
if (assembly.Name.HasPublicKey)
|
||||
throw new InvalidOperationException("Signed assemblies cannot be woven by the standalone EventBus processor.");
|
||||
if (!EventBusAssemblyWeaver.Weave(assembly.MainModule))
|
||||
return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, diagnostics);
|
||||
using var outputPe = new MemoryStream();
|
||||
using var outputPdb = new MemoryStream();
|
||||
assembly.Write(outputPe, new WriterParameters
|
||||
{
|
||||
WriteSymbols = hasSymbols,
|
||||
SymbolStream = hasSymbols ? outputPdb : null,
|
||||
SymbolWriterProvider = hasSymbols ? new PortablePdbWriterProvider() : null
|
||||
});
|
||||
return new ILPostProcessResult(new InMemoryAssembly(outputPe.ToArray(),
|
||||
hasSymbols ? outputPdb.ToArray() : Array.Empty<byte>()), diagnostics);
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch (Exception exception)
|
||||
{
|
||||
diagnostics.Add(new DiagnosticMessage
|
||||
{
|
||||
DiagnosticType = DiagnosticType.Error,
|
||||
MessageData = $"[ShrinkEventBus.CodeGen] {ex.Message}"
|
||||
MessageData = $"[ShrinkEventBus.CodeGen] {exception.Message}"
|
||||
});
|
||||
}
|
||||
|
||||
return GetResult(assemblyDefinition, diagnostics);
|
||||
}
|
||||
|
||||
private static bool ReferencesAssembly(ICompiledAssembly compiledAssembly, string assemblyName)
|
||||
{
|
||||
return compiledAssembly.References.Any(reference =>
|
||||
string.Equals(Path.GetFileNameWithoutExtension(reference), assemblyName, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static bool HasAttribute(ICustomAttributeProvider provider, TypeReference expectedAttributeType)
|
||||
{
|
||||
return provider.CustomAttributes.Any(attribute => attribute.AttributeType.FullName == expectedAttributeType.FullName);
|
||||
}
|
||||
|
||||
private static IEnumerable<TypeDefinition> GetAllTypes(IEnumerable<TypeDefinition> roots)
|
||||
{
|
||||
foreach (var type in roots)
|
||||
{
|
||||
yield return type;
|
||||
foreach (var nested in GetAllTypes(type.NestedTypes))
|
||||
yield return nested;
|
||||
}
|
||||
}
|
||||
|
||||
private static void InjectGeneratedBinding(TypeDefinition type, ModuleDefinition module,
|
||||
TypeReference subscribeAttributeType)
|
||||
{
|
||||
var generatedInterface = FindType(module,
|
||||
"ShrinkEventBus.IShrinkGeneratedSubscriber", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("IShrinkGeneratedSubscriber was not found.");
|
||||
if (type.Interfaces.Any(item => item.InterfaceType.FullName == generatedInterface.FullName))
|
||||
return;
|
||||
|
||||
var resolverType = FindType(module, "ShrinkEventBus.IShrinkBusResolver", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("IShrinkBusResolver was not found.");
|
||||
var busKeyType = FindType(module, "ShrinkEventBus.ShrinkBusKey", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkBusKey was not found.");
|
||||
var bindingType = FindType(module, "ShrinkEventBus.ShrinkEventBinding", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkEventBinding was not found.");
|
||||
var bindingHelperType = FindType(module, "ShrinkEventBus.ShrinkGeneratedBinding", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkGeneratedBinding was not found.");
|
||||
var priorityType = FindType(module, "ShrinkEventBus.ShrinkEventPriority", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkEventPriority was not found.");
|
||||
var asyncHandlerType = FindType(module, "ShrinkEventBus.ShrinkAsyncEventHandler`1", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkAsyncEventHandler was not found.");
|
||||
|
||||
var nullableBusKey = new GenericInstanceType(module.ImportReference(typeof(Nullable<>)));
|
||||
nullableBusKey.GenericArguments.Add(busKeyType);
|
||||
var disposableType = module.ImportReference(typeof(IDisposable));
|
||||
var bindingDefinition = bindingType.Resolve()
|
||||
?? throw new InvalidOperationException("ShrinkEventBinding could not be resolved.");
|
||||
var bindingCtor = module.ImportReference(bindingDefinition.Methods.Single(method =>
|
||||
method.IsConstructor && method.Parameters.Count == 0));
|
||||
var bindingAdd = module.ImportReference(bindingDefinition.Methods.Single(method =>
|
||||
method.Name == "Add" && method.Parameters.Count == 1));
|
||||
|
||||
var helperDefinition = bindingHelperType.Resolve()
|
||||
?? throw new InvalidOperationException("ShrinkGeneratedBinding could not be resolved.");
|
||||
var syncSubscribe = module.ImportReference(helperDefinition.Methods.Single(method =>
|
||||
method.Name == "Subscribe" && method.HasGenericParameters));
|
||||
var asyncSubscribe = module.ImportReference(helperDefinition.Methods.Single(method =>
|
||||
method.Name == "SubscribeAsync" && method.HasGenericParameters));
|
||||
var legacyAsyncSubscribe = module.ImportReference(helperDefinition.Methods.Single(method =>
|
||||
method.Name == "SubscribeAsyncLegacy" && method.HasGenericParameters));
|
||||
|
||||
var interfaceDefinition = generatedInterface.Resolve()
|
||||
?? throw new InvalidOperationException("IShrinkGeneratedSubscriber could not be resolved.");
|
||||
var interfaceMethod = module.ImportReference(interfaceDefinition.Methods.Single(method =>
|
||||
method.Name == "AttachGenerated"));
|
||||
|
||||
var generatedMethod = new MethodDefinition(
|
||||
"ShrinkEventBus.IShrinkGeneratedSubscriber.AttachGenerated",
|
||||
MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.HideBySig |
|
||||
MethodAttributes.NewSlot | MethodAttributes.Virtual,
|
||||
disposableType);
|
||||
generatedMethod.Parameters.Add(new ParameterDefinition("resolver", ParameterAttributes.None, resolverType));
|
||||
generatedMethod.Parameters.Add(new ParameterDefinition("defaultBus", ParameterAttributes.Optional,
|
||||
nullableBusKey));
|
||||
generatedMethod.Overrides.Add(interfaceMethod);
|
||||
generatedMethod.Body.InitLocals = true;
|
||||
var bindingLocal = new VariableDefinition(bindingType);
|
||||
generatedMethod.Body.Variables.Add(bindingLocal);
|
||||
var il = generatedMethod.Body.GetILProcessor();
|
||||
il.Emit(OpCodes.Newobj, bindingCtor);
|
||||
il.Emit(OpCodes.Stloc, bindingLocal);
|
||||
|
||||
var classDefaultBus = ReadStringProperty(
|
||||
type.CustomAttributes.First(attribute =>
|
||||
attribute.AttributeType.FullName == "ShrinkEventBus.ShrinkEventSubscriberAttribute"),
|
||||
"DefaultBus");
|
||||
|
||||
foreach (var handler in type.Methods.Where(method =>
|
||||
!method.IsStatic && HasAttribute(method, subscribeAttributeType)).ToArray())
|
||||
{
|
||||
EmitGeneratedSubscription(il, module, type, handler,
|
||||
handler.CustomAttributes.First(attribute =>
|
||||
attribute.AttributeType.FullName == subscribeAttributeType.FullName),
|
||||
classDefaultBus, bindingLocal, bindingAdd, syncSubscribe, asyncSubscribe,
|
||||
legacyAsyncSubscribe, asyncHandlerType);
|
||||
}
|
||||
|
||||
il.Emit(OpCodes.Ldloc, bindingLocal);
|
||||
il.Emit(OpCodes.Ret);
|
||||
type.Interfaces.Add(new InterfaceImplementation(generatedInterface));
|
||||
type.Methods.Add(generatedMethod);
|
||||
}
|
||||
|
||||
private static void EmitGeneratedSubscription(ILProcessor il, ModuleDefinition module,
|
||||
TypeDefinition ownerType, MethodDefinition handler, CustomAttribute attribute,
|
||||
string classDefaultBus, VariableDefinition bindingLocal, MethodReference bindingAdd,
|
||||
MethodReference syncSubscribe, MethodReference asyncSubscribe,
|
||||
MethodReference legacyAsyncSubscribe, TypeReference asyncHandlerType)
|
||||
{
|
||||
if (handler.Parameters.Count is < 1 or > 2)
|
||||
throw new InvalidOperationException(
|
||||
$"[ShrinkSubscribe] method {handler.FullName} must have one event parameter and an optional CancellationToken.");
|
||||
|
||||
var eventType = module.ImportReference(handler.Parameters[0].ParameterType);
|
||||
var eventInterface = FindType(module, "ShrinkEventBus.IShrinkEvent", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("IShrinkEvent was not found.");
|
||||
if (!ImplementsInterface(eventType, eventInterface.FullName))
|
||||
throw new InvalidOperationException(
|
||||
$"[ShrinkSubscribe] method {handler.FullName} event parameter must implement IShrinkEvent.");
|
||||
|
||||
var bus = ReadStringProperty(attribute, "Bus");
|
||||
if (string.IsNullOrWhiteSpace(bus))
|
||||
bus = classDefaultBus;
|
||||
var priority = ReadIntProperty(attribute, "Priority", 2);
|
||||
var numericPriority = ReadIntProperty(attribute, "NumericPriority", 0);
|
||||
var receiveCanceled = ReadBoolProperty(attribute, "ReceiveCanceled", false);
|
||||
|
||||
MethodReference openSubscribe;
|
||||
TypeReference delegateType;
|
||||
if (handler.ReturnType.FullName == module.TypeSystem.Void.FullName && handler.Parameters.Count == 1)
|
||||
{
|
||||
openSubscribe = syncSubscribe;
|
||||
delegateType = MakeGenericType(module, typeof(Action<>), eventType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" &&
|
||||
handler.Parameters.Count == 1)
|
||||
{
|
||||
openSubscribe = legacyAsyncSubscribe;
|
||||
var uniTaskType = FindType(module, "Cysharp.Threading.Tasks.UniTask", "UniTask")
|
||||
?? module.ImportReference(handler.ReturnType);
|
||||
delegateType = MakeGenericType(module, typeof(Func<,>), eventType, uniTaskType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" &&
|
||||
handler.Parameters.Count == 2 &&
|
||||
handler.Parameters[1].ParameterType.FullName == typeof(System.Threading.CancellationToken).FullName)
|
||||
{
|
||||
openSubscribe = asyncSubscribe;
|
||||
var closedAsyncHandler = new GenericInstanceType(asyncHandlerType);
|
||||
closedAsyncHandler.GenericArguments.Add(eventType);
|
||||
delegateType = closedAsyncHandler;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Unsupported [ShrinkSubscribe] signature: {handler.FullName}. Use void(T), UniTask(T), or UniTask(T, CancellationToken).");
|
||||
}
|
||||
|
||||
var closedSubscribe = new GenericInstanceMethod(openSubscribe);
|
||||
closedSubscribe.GenericArguments.Add(eventType);
|
||||
var delegateCtor = MakeDelegateConstructor(module, delegateType);
|
||||
|
||||
il.Emit(OpCodes.Ldloc, bindingLocal);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Ldarg_2);
|
||||
il.Emit(OpCodes.Ldstr, bus ?? string.Empty);
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldftn, module.ImportReference(handler));
|
||||
il.Emit(OpCodes.Newobj, delegateCtor);
|
||||
il.Emit(OpCodes.Ldc_I4, priority);
|
||||
il.Emit(OpCodes.Ldc_I4, numericPriority);
|
||||
il.Emit(receiveCanceled ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
|
||||
il.Emit(OpCodes.Call, closedSubscribe);
|
||||
il.Emit(OpCodes.Callvirt, bindingAdd);
|
||||
}
|
||||
|
||||
private static void InjectStaticBootstrap(ModuleDefinition module,
|
||||
IReadOnlyList<TypeDefinition> subscriberTypes, TypeReference subscribeAttributeType)
|
||||
{
|
||||
var registryType = FindType(module, "ShrinkEventBus.ShrinkStaticBindingRegistry", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkStaticBindingRegistry was not found.");
|
||||
var asyncHandlerType = FindType(module, "ShrinkEventBus.ShrinkAsyncEventHandler`1", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkAsyncEventHandler was not found.");
|
||||
var registryDefinition = registryType.Resolve()
|
||||
?? throw new InvalidOperationException("ShrinkStaticBindingRegistry could not be resolved.");
|
||||
var syncRegister = module.ImportReference(registryDefinition.Methods.Single(method =>
|
||||
method.Name == "Register" && method.HasGenericParameters));
|
||||
var asyncRegister = module.ImportReference(registryDefinition.Methods.Single(method =>
|
||||
method.Name == "RegisterAsync" && method.HasGenericParameters));
|
||||
var legacyAsyncRegister = module.ImportReference(registryDefinition.Methods.Single(method =>
|
||||
method.Name == "RegisterAsyncLegacy" && method.HasGenericParameters));
|
||||
|
||||
var bootstrap = new TypeDefinition("ShrinkEventBus.Generated",
|
||||
"ShrinkGeneratedStaticBindings",
|
||||
TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.NotPublic,
|
||||
module.TypeSystem.Object);
|
||||
module.Types.Add(bootstrap);
|
||||
|
||||
var register = new MethodDefinition("Register",
|
||||
MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig,
|
||||
module.TypeSystem.Void);
|
||||
bootstrap.Methods.Add(register);
|
||||
var il = register.Body.GetILProcessor();
|
||||
|
||||
foreach (var type in subscriberTypes)
|
||||
{
|
||||
var classDefaultBus = ReadStringProperty(
|
||||
type.CustomAttributes.First(attribute =>
|
||||
attribute.AttributeType.FullName == "ShrinkEventBus.ShrinkEventSubscriberAttribute"),
|
||||
"DefaultBus");
|
||||
foreach (var handler in type.Methods.Where(method =>
|
||||
method.IsStatic && HasAttribute(method, subscribeAttributeType)).ToArray())
|
||||
{
|
||||
EmitStaticGeneratedSubscription(il, module, handler,
|
||||
handler.CustomAttributes.First(attribute =>
|
||||
attribute.AttributeType.FullName == subscribeAttributeType.FullName),
|
||||
classDefaultBus, syncRegister, asyncRegister,
|
||||
legacyAsyncRegister, asyncHandlerType);
|
||||
}
|
||||
}
|
||||
|
||||
il.Emit(OpCodes.Ret);
|
||||
InjectModuleInitializer(module, register);
|
||||
}
|
||||
|
||||
private static void EmitStaticGeneratedSubscription(ILProcessor il, ModuleDefinition module,
|
||||
MethodDefinition handler, CustomAttribute attribute, string classDefaultBus,
|
||||
MethodReference syncRegister, MethodReference asyncRegister,
|
||||
MethodReference legacyAsyncRegister, TypeReference asyncHandlerType)
|
||||
{
|
||||
if (handler.Parameters.Count is < 1 or > 2)
|
||||
throw new InvalidOperationException(
|
||||
$"[ShrinkSubscribe] method {handler.FullName} must have one event parameter and an optional CancellationToken.");
|
||||
|
||||
var eventType = module.ImportReference(handler.Parameters[0].ParameterType);
|
||||
var eventInterface = FindType(module, "ShrinkEventBus.IShrinkEvent", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("IShrinkEvent was not found.");
|
||||
if (!ImplementsInterface(eventType, eventInterface.FullName))
|
||||
throw new InvalidOperationException(
|
||||
$"[ShrinkSubscribe] method {handler.FullName} event parameter must implement IShrinkEvent.");
|
||||
|
||||
var bus = ReadStringProperty(attribute, "Bus");
|
||||
if (string.IsNullOrWhiteSpace(bus))
|
||||
bus = classDefaultBus;
|
||||
var priority = ReadIntProperty(attribute, "Priority", 2);
|
||||
var numericPriority = ReadIntProperty(attribute, "NumericPriority", 0);
|
||||
var receiveCanceled = ReadBoolProperty(attribute, "ReceiveCanceled", false);
|
||||
|
||||
MethodReference openRegister;
|
||||
TypeReference delegateType;
|
||||
if (handler.ReturnType.FullName == module.TypeSystem.Void.FullName && handler.Parameters.Count == 1)
|
||||
{
|
||||
openRegister = syncRegister;
|
||||
delegateType = MakeGenericType(module, typeof(Action<>), eventType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" &&
|
||||
handler.Parameters.Count == 1)
|
||||
{
|
||||
openRegister = legacyAsyncRegister;
|
||||
var uniTaskType = FindType(module, "Cysharp.Threading.Tasks.UniTask", "UniTask")
|
||||
?? module.ImportReference(handler.ReturnType);
|
||||
delegateType = MakeGenericType(module, typeof(Func<,>), eventType, uniTaskType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" &&
|
||||
handler.Parameters.Count == 2 &&
|
||||
handler.Parameters[1].ParameterType.FullName == typeof(System.Threading.CancellationToken).FullName)
|
||||
{
|
||||
openRegister = asyncRegister;
|
||||
var closedAsyncHandler = new GenericInstanceType(asyncHandlerType);
|
||||
closedAsyncHandler.GenericArguments.Add(eventType);
|
||||
delegateType = closedAsyncHandler;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Unsupported static [ShrinkSubscribe] signature: {handler.FullName}.");
|
||||
}
|
||||
|
||||
var closedRegister = new GenericInstanceMethod(openRegister);
|
||||
closedRegister.GenericArguments.Add(eventType);
|
||||
var delegateCtor = MakeDelegateConstructor(module, delegateType);
|
||||
var handlerBridge = CreateStaticHandlerBridge(module, handler);
|
||||
|
||||
il.Emit(OpCodes.Ldstr, bus ?? string.Empty);
|
||||
il.Emit(OpCodes.Ldnull);
|
||||
il.Emit(OpCodes.Ldftn, module.ImportReference(handlerBridge));
|
||||
il.Emit(OpCodes.Newobj, delegateCtor);
|
||||
il.Emit(OpCodes.Ldc_I4, priority);
|
||||
il.Emit(OpCodes.Ldc_I4, numericPriority);
|
||||
il.Emit(receiveCanceled ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
|
||||
il.Emit(OpCodes.Call, closedRegister);
|
||||
}
|
||||
|
||||
private static MethodDefinition CreateStaticHandlerBridge(ModuleDefinition module,
|
||||
MethodDefinition handler)
|
||||
{
|
||||
var bridge = new MethodDefinition(
|
||||
$"ShrinkEventBus.GeneratedStaticHandler_{handler.MetadataToken.ToInt32():X8}",
|
||||
MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig,
|
||||
module.ImportReference(handler.ReturnType));
|
||||
for (var i = 0; i < handler.Parameters.Count; i++)
|
||||
{
|
||||
var parameter = handler.Parameters[i];
|
||||
bridge.Parameters.Add(new ParameterDefinition(parameter.Name, parameter.Attributes,
|
||||
module.ImportReference(parameter.ParameterType)));
|
||||
}
|
||||
|
||||
var il = bridge.Body.GetILProcessor();
|
||||
for (var i = 0; i < bridge.Parameters.Count; i++)
|
||||
il.Emit(OpCodes.Ldarg, bridge.Parameters[i]);
|
||||
il.Emit(OpCodes.Call, module.ImportReference(handler));
|
||||
il.Emit(OpCodes.Ret);
|
||||
handler.DeclaringType.Methods.Add(bridge);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
private static void InjectModuleInitializer(ModuleDefinition module, MethodReference register)
|
||||
{
|
||||
var moduleType = module.Types.First(type => type.Name == "<Module>");
|
||||
var initializer = moduleType.Methods.FirstOrDefault(method => method.Name == ".cctor");
|
||||
if (initializer == null)
|
||||
{
|
||||
initializer = new MethodDefinition(".cctor",
|
||||
MethodAttributes.Private | MethodAttributes.Static |
|
||||
MethodAttributes.HideBySig | MethodAttributes.SpecialName |
|
||||
MethodAttributes.RTSpecialName,
|
||||
module.TypeSystem.Void);
|
||||
initializer.Body.GetILProcessor().Emit(OpCodes.Ret);
|
||||
moduleType.Methods.Add(initializer);
|
||||
}
|
||||
|
||||
var processor = initializer.Body.GetILProcessor();
|
||||
processor.InsertBefore(initializer.Body.Instructions[0],
|
||||
processor.Create(OpCodes.Call, register));
|
||||
}
|
||||
|
||||
private static GenericInstanceType MakeGenericType(ModuleDefinition module, Type openType,
|
||||
params TypeReference[] arguments)
|
||||
{
|
||||
var result = new GenericInstanceType(module.ImportReference(openType));
|
||||
foreach (var argument in arguments)
|
||||
result.GenericArguments.Add(argument);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static MethodReference MakeDelegateConstructor(ModuleDefinition module, TypeReference delegateType)
|
||||
{
|
||||
var ctor = new MethodReference(".ctor", module.TypeSystem.Void, delegateType)
|
||||
{
|
||||
HasThis = true,
|
||||
CallingConvention = MethodCallingConvention.Default
|
||||
};
|
||||
ctor.Parameters.Add(new ParameterDefinition(module.TypeSystem.Object));
|
||||
ctor.Parameters.Add(new ParameterDefinition(module.TypeSystem.IntPtr));
|
||||
return ctor;
|
||||
}
|
||||
|
||||
private static bool ImplementsInterface(TypeReference type, string interfaceFullName)
|
||||
{
|
||||
TypeDefinition? current;
|
||||
try
|
||||
{
|
||||
current = type.Resolve();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
while (current != null)
|
||||
{
|
||||
if (current.Interfaces.Any(item => item.InterfaceType.FullName == interfaceFullName))
|
||||
return true;
|
||||
try
|
||||
{
|
||||
current = current.BaseType?.Resolve();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string ReadStringProperty(CustomAttribute attribute, string name)
|
||||
{
|
||||
foreach (var property in attribute.Properties)
|
||||
{
|
||||
if (property.Name == name)
|
||||
return property.Argument.Value as string ?? string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private static int ReadIntProperty(CustomAttribute attribute, string name, int defaultValue)
|
||||
{
|
||||
foreach (var property in attribute.Properties)
|
||||
{
|
||||
if (property.Name == name)
|
||||
return Convert.ToInt32(property.Argument.Value);
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
private static bool ReadBoolProperty(CustomAttribute attribute, string name, bool defaultValue)
|
||||
{
|
||||
foreach (var property in attribute.Properties)
|
||||
{
|
||||
if (property.Name == name)
|
||||
return Convert.ToBoolean(property.Argument.Value);
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
private static TypeReference? FindType(ModuleDefinition module, string fullName, string assemblyName)
|
||||
{
|
||||
var resolved = Type.GetType($"{fullName}, {assemblyName}", false);
|
||||
return resolved == null ? null : module.ImportReference(resolved);
|
||||
}
|
||||
|
||||
private static AssemblyDefinition AssemblyDefinitionFor(ICompiledAssembly compiledAssembly)
|
||||
{
|
||||
var assemblyResolver = new PostProcessorAssemblyResolver(compiledAssembly);
|
||||
var readerParameters = new ReaderParameters
|
||||
{
|
||||
SymbolStream = new MemoryStream(compiledAssembly.InMemoryAssembly.PdbData.ToArray()),
|
||||
SymbolReaderProvider = new PdbReaderProvider(),
|
||||
AssemblyResolver = assemblyResolver,
|
||||
ReflectionImporterProvider = new PostProcessorReflectionImporterProvider(),
|
||||
ReadingMode = ReadingMode.Immediate
|
||||
};
|
||||
|
||||
var assemblyDefinition = AssemblyDefinition.ReadAssembly(
|
||||
new MemoryStream(compiledAssembly.InMemoryAssembly.PeData.ToArray()),
|
||||
readerParameters);
|
||||
assemblyResolver.AddAssemblyDefinitionBeingOperatedOn(assemblyDefinition);
|
||||
return assemblyDefinition;
|
||||
}
|
||||
|
||||
private static ILPostProcessResult GetResult(AssemblyDefinition assemblyDefinition, List<DiagnosticMessage> diagnostics)
|
||||
{
|
||||
var pe = new MemoryStream();
|
||||
var pdb = new MemoryStream();
|
||||
assemblyDefinition.Write(pe, new WriterParameters
|
||||
{
|
||||
SymbolWriterProvider = new PdbWriterProvider(),
|
||||
SymbolStream = pdb,
|
||||
WriteSymbols = true
|
||||
});
|
||||
return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), diagnostics);
|
||||
#endif
|
||||
return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, diagnostics);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,9 @@ namespace ShrinkEventBus.CodeGen
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var assembly in _cache.Values)
|
||||
assembly.Dispose();
|
||||
_cache.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,29 @@
|
||||
{
|
||||
"name": "Unity.ShrinkEventBus.CodeGen",
|
||||
"rootNamespace": "ShrinkEventBus.CodeGen",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [
|
||||
"Mono.Cecil.dll",
|
||||
"Mono.Cecil.Mdb.dll",
|
||||
"Mono.Cecil.Pdb.dll",
|
||||
"Mono.Cecil.Rocks.dll"
|
||||
],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
"name": "Unity.ShrinkEventBus.CodeGen",
|
||||
"rootNamespace": "ShrinkEventBus.CodeGen",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [
|
||||
"Mono.Cecil.dll",
|
||||
"Mono.Cecil.Mdb.dll",
|
||||
"Mono.Cecil.Pdb.dll",
|
||||
"Mono.Cecil.Rocks.dll"
|
||||
],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.cneicy.shrink-shared-codegen",
|
||||
"expression": "0.2.1",
|
||||
"define": "SHRINK_EVENTBUS_HAS_SHARED_CODEGEN"
|
||||
}
|
||||
],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Collections;
|
||||
using System.Threading;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using NUnit.Framework;
|
||||
using ShrinkEventBus;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
namespace EventBusConsumer
|
||||
{
|
||||
internal readonly struct Ping : IShrinkEvent { }
|
||||
|
||||
[ShrinkEventSubscriber]
|
||||
internal sealed class Subscriber
|
||||
{
|
||||
public int SyncHits;
|
||||
public int AsyncHits;
|
||||
[ShrinkSubscribe] private void OnPing(Ping value) => SyncHits++;
|
||||
[ShrinkSubscribe] private async UniTask OnPingAsync(Ping value, CancellationToken token)
|
||||
{
|
||||
await UniTask.Yield(cancellationToken: token);
|
||||
AsyncHits++;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ConsumerTests
|
||||
{
|
||||
[UnityTest]
|
||||
public IEnumerator ConsumerAssemblyGeneratesBindingsAndDisposesThem()
|
||||
{
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var bus = host.CreateBus(ShrinkBusKey.Game, ShrinkBusOptions.Inline());
|
||||
var target = new Subscriber();
|
||||
Assert.IsInstanceOf<IShrinkGeneratedSubscriber>(target);
|
||||
var binding = host.Attach(target, ShrinkBusKey.Game);
|
||||
yield return bus.PostAsync(new Ping()).ToCoroutine();
|
||||
Assert.AreEqual(1, target.SyncHits);
|
||||
Assert.AreEqual(1, target.AsyncHits);
|
||||
binding.Dispose();
|
||||
yield return bus.PostAsync(new Ping()).ToCoroutine();
|
||||
Assert.AreEqual(1, target.SyncHits);
|
||||
Assert.AreEqual(1, target.AsyncHits);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "EventBus.Consumer.Tests",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"UniTask"
|
||||
],
|
||||
"optionalUnityReferences": [
|
||||
"TestAssemblies"
|
||||
],
|
||||
"defineConstraints": [
|
||||
"UNITY_INCLUDE_TESTS"
|
||||
],
|
||||
"autoReferenced": false
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
{
|
||||
"scopedRegistries": [
|
||||
{
|
||||
"name": "ShrinkSDK",
|
||||
"url": "https://git.crash.work/api/packages/ShrinkSDK/npm/",
|
||||
"scopes": [
|
||||
"com.cneicy"
|
||||
]
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"com.unity.test-framework": "1.1.33",
|
||||
"com.cneicy.shrink-eventbus": "file:../../.."
|
||||
}
|
||||
"com.cneicy.shrink-eventbus": "file:../../..",
|
||||
"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b"
|
||||
},
|
||||
"testables": [
|
||||
"com.cneicy.shrink-eventbus"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<Deterministic>true</Deterministic>
|
||||
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
|
||||
<Authors>ShrinkSDK</Authors>
|
||||
<Company>ShrinkSDK</Company>
|
||||
<RepositoryUrl>https://git.crash.work/ShrinkSDK</RepositoryUrl>
|
||||
<IncludeSymbols>true</IncludeSymbols>
|
||||
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bb9607b086e27c14c9be7469aac61d0d
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
<AssemblyName>ShrinkEventBus.Runtime</AssemblyName>
|
||||
<RootNamespace>ShrinkEventBus</RootNamespace>
|
||||
<PackageId>ShrinkSDK.EventBus</PackageId>
|
||||
<Version>2.3.2</Version>
|
||||
<Description>ShrinkSDK typed event bus runtime.</Description>
|
||||
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="..\Runtime\**\*.cs"
|
||||
Exclude="..\Runtime\ShrinkMonoEventScope.cs" />
|
||||
<PackageReference Include="UniTask" Version="2.5.10" />
|
||||
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.2.0" PrivateAssets="compile;runtime;contentfiles;native" />
|
||||
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.2.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 27180d887eae401ca4e2547c96534ec4
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: eae196d52d4a4091bdf0aa90888b6c97
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "ShrinkEventBus.Integration.Runtime",
|
||||
"rootNamespace": "ShrinkEventBus.Integration",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"ShrinkRuntime.Abstractions"
|
||||
],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [
|
||||
"SHRINK_EVENTBUS_HAS_SHARED_RUNTIME"
|
||||
],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.cneicy.shrink-runtime-abstractions",
|
||||
"expression": "0.1.0",
|
||||
"define": "SHRINK_EVENTBUS_HAS_SHARED_RUNTIME"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 86c48423db2e41e1b208c468296b7faf
|
||||
@@ -0,0 +1,20 @@
|
||||
#if SHRINK_EVENTBUS_HAS_SHARED_RUNTIME
|
||||
using System;
|
||||
using ShrinkSDK.Runtime;
|
||||
|
||||
namespace ShrinkEventBus.Integration
|
||||
{
|
||||
public sealed class ShrinkSharedMainThreadDispatcher : IShrinkEventBusMainThreadDispatcher
|
||||
{
|
||||
private readonly IShrinkMainThreadDispatcher _dispatcher;
|
||||
|
||||
public ShrinkSharedMainThreadDispatcher(IShrinkMainThreadDispatcher dispatcher)
|
||||
{
|
||||
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
|
||||
}
|
||||
|
||||
public bool IsMainThread => _dispatcher.IsMainThread;
|
||||
public bool TryPost(Action action) => _dispatcher.TryPost(action);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f818313cb4e3447f9622b71decefa86c
|
||||
@@ -0,0 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bc17b8a03b8d4abe8068d9310fe12f19
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
@@ -0,0 +1,43 @@
|
||||
#if SHRINK_EVENTBUS_HAS_SHARED_RUNTIME
|
||||
using System;
|
||||
using NUnit.Framework;
|
||||
using ShrinkSDK.Runtime;
|
||||
|
||||
namespace ShrinkEventBus.Integration.Tests
|
||||
{
|
||||
public sealed class SharedDispatcherTests
|
||||
{
|
||||
private sealed class Dispatcher : IShrinkMainThreadDispatcher
|
||||
{
|
||||
public bool IsMainThread => false;
|
||||
public Action Pending;
|
||||
public bool TryPost(Action action) { Pending = action; return true; }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AdapterPreservesAffinityAndPostsThroughSharedDispatcher()
|
||||
{
|
||||
var original = ShrinkEventBusRuntime.MainThreadDispatcher;
|
||||
try
|
||||
{
|
||||
var dispatcher = new Dispatcher();
|
||||
var adapter = new ShrinkSharedMainThreadDispatcher(dispatcher);
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(adapter);
|
||||
Assert.IsFalse(ShrinkEventBusRuntime.MainThreadDispatcher.IsMainThread);
|
||||
var hits = 0;
|
||||
Assert.IsTrue(ShrinkEventBusRuntime.MainThreadDispatcher.TryPost(() => hits++));
|
||||
Assert.AreEqual(0, hits);
|
||||
dispatcher.Pending();
|
||||
Assert.AreEqual(1, hits);
|
||||
}
|
||||
finally { ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(original); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AdapterRejectsNullDispatcher()
|
||||
{
|
||||
Assert.Throws<ArgumentNullException>(() => new ShrinkSharedMainThreadDispatcher(null));
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 87e04bff7dc943dd9a8205b37e631c19
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "ShrinkEventBus.Integration.Runtime.Tests",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"ShrinkEventBus.Integration.Runtime",
|
||||
"ShrinkRuntime.Abstractions"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"optionalUnityReferences": [
|
||||
"TestAssemblies"
|
||||
],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [
|
||||
"UNITY_INCLUDE_TESTS",
|
||||
"SHRINK_EVENTBUS_HAS_SHARED_RUNTIME"
|
||||
],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.cneicy.shrink-runtime-abstractions",
|
||||
"expression": "0.1.0",
|
||||
"define": "SHRINK_EVENTBUS_HAS_SHARED_RUNTIME"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4062d02e94ea4577957d4185688d1454
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<packageSources>
|
||||
<clear />
|
||||
<add key="ShrinkSDK" value="https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json" />
|
||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||
</packageSources>
|
||||
</configuration>
|
||||
@@ -0,0 +1,32 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cc42bc8ffa8649949aa6d63f9a225d27
|
||||
PluginImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
iconMap: {}
|
||||
executionOrder: {}
|
||||
defineConstraints: []
|
||||
isPreloaded: 0
|
||||
isOverridable: 0
|
||||
isExplicitlyReferenced: 0
|
||||
validateReferences: 1
|
||||
platformData:
|
||||
- first:
|
||||
Any:
|
||||
second:
|
||||
enabled: 0
|
||||
settings: {}
|
||||
- first:
|
||||
Editor: Editor
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
DefaultValueInitialized: true
|
||||
- first:
|
||||
Windows Store Apps: WindowsStoreApps
|
||||
second:
|
||||
enabled: 1
|
||||
settings: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,7 +1,69 @@
|
||||
# ShrinkEventBus 2.0
|
||||
# ShrinkEventBus
|
||||
|
||||
ShrinkEventBus 2.0 是面向 Unity、普通 C# 宿主和 Entities/Burst 生产端的统一事件总线。运行时只有一种事件模型、一个订阅入口和一组发布 API;不同 Bus 只表达生命周期、所有权与调度策略。
|
||||
|
||||
Godot 和普通 .NET 项目安装 `ShrinkSDK.EventBus`;可打包源码位于 `DotNet~`,订阅注册由 `ShrinkSDK.CodeGen` 在构建时织入。
|
||||
|
||||
## Unity 安装
|
||||
|
||||
要求 Unity 2022.3 或更新版本。在 Package Manager 中使用 **Add package from git URL**,依次安装:
|
||||
|
||||
```text
|
||||
https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b
|
||||
https://github.com/cneicy/ShrinkEventBus.git
|
||||
```
|
||||
|
||||
第一个地址固定 UniTask 2.5.10。Mono.Cecil 1.11.4 由 Unity 官方 registry 自动解析;无需配置 ShrinkSDK registry。需要锁定 EventBus 版本时,在 Git URL 后添加 `#<commit>`。
|
||||
|
||||
### 可选 ShrinkSDK 集成
|
||||
|
||||
| 已安装的共享包 | 行为 |
|
||||
|---|---|
|
||||
| 无 | 使用包内调度接口和 EventBus 专用 ILPostProcessor |
|
||||
| Runtime Abstractions 0.2.0+ | 额外启用共享主线程调度器适配程序集,并支持显式延后发布 |
|
||||
| Shared CodeGen 0.2.1+ | 停用包内织入,交给共享 CodeGen 统一生成订阅 |
|
||||
| 两者都有 | 同时启用上述两项集成 |
|
||||
|
||||
通过 asmdef `versionDefines` 自动生成 `SHRINK_EVENTBUS_HAS_SHARED_RUNTIME` 和 `SHRINK_EVENTBUS_HAS_SHARED_CODEGEN`,不需要手工设置宏。两个共享包由完整工程自行安装,EventBus 不再强制拉取它们。
|
||||
|
||||
Unity 自定义调度器现在实现 `IShrinkEventBusMainThreadDispatcher`。已有的共享 `IShrinkMainThreadDispatcher` 实现使用以下适配方式:
|
||||
|
||||
```csharp
|
||||
using ShrinkEventBus;
|
||||
using ShrinkEventBus.Integration;
|
||||
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(
|
||||
new ShrinkSharedMainThreadDispatcher(sharedDispatcher));
|
||||
```
|
||||
|
||||
使用自定义 asmdef 的业务程序集还需引用 `ShrinkEventBus.Integration.Runtime`。默认 UniTask PlayerLoop 调度无需配置;请在创建需要自定义调度的 Bus 前完成配置。此调整只影响 Unity,现有 .NET/Godot 配置接口保持不变。
|
||||
|
||||
### 最小使用示例
|
||||
|
||||
业务 asmdef 引用 `ShrinkEventBus.Runtime`,使用 UniTask 时再引用 `UniTask`。无需 `partial`、反射注册或手工生成绑定:
|
||||
|
||||
```csharp
|
||||
using ShrinkEventBus;
|
||||
using UnityEngine;
|
||||
|
||||
public readonly struct PlayerJoined : IShrinkEvent { }
|
||||
|
||||
[ShrinkEventSubscriber]
|
||||
public sealed class PlayerHandlers
|
||||
{
|
||||
[ShrinkSubscribe]
|
||||
private void OnJoined(PlayerJoined value) => Debug.Log("Player joined");
|
||||
}
|
||||
|
||||
// 在 Unity 主线程执行;binding 应由实际宿主持有并在生命周期结束时释放。
|
||||
using (var binding = EventBus.Attach(new PlayerHandlers()))
|
||||
{
|
||||
EventBus.Post(new PlayerJoined());
|
||||
}
|
||||
```
|
||||
|
||||
包内 `Development~/UnityProject` 是独立验证工程,包含外部消费程序集的同步/异步订阅测试。使用 Unity Test Runner 运行 EditMode 和 PlayMode 测试;包本身的测试通过 manifest 的 `testables` 开启。
|
||||
|
||||
## 核心契约
|
||||
|
||||
```csharp
|
||||
@@ -80,7 +142,18 @@ Bus 解析顺序:方法 `Bus`、类型 `DefaultBus`、`Attach` 传入默认 Bu
|
||||
using var binding = EventBus.Attach(new PlayerHandlers());
|
||||
```
|
||||
|
||||
MonoBehaviour 不需要继承 SDK 基类。可自行在 `OnEnable/OnDisable` 中 Attach/Dispose,也可以在 GameObject 上添加 `ShrinkMonoEventScope`,由它统一绑定同对象或子层级中的生成 subscriber。
|
||||
MonoBehaviour 不需要继承 SDK 基类。需要从 `Awake` 持续订阅到 `OnDestroy` 时,可以显式选择编译期生命周期织入:
|
||||
|
||||
```csharp
|
||||
[ShrinkEventSubscriber(Lifetime = ShrinkSubscriberLifetime.AwakeToDestroy)]
|
||||
public sealed class PlayerHandlers : MonoBehaviour
|
||||
{
|
||||
[ShrinkSubscribe]
|
||||
private void OnJoined(PlayerJoinedEvent value) { }
|
||||
}
|
||||
```
|
||||
|
||||
默认 `Lifetime` 为 `Manual`,普通对象与由 Context、Scene 或 Mod 宿主管理的实例继续自行持有 `EventBus.Attach(...)` 返回的绑定。需要随启用状态反复订阅的 MonoBehaviour 可以自行在 `OnEnable/OnDisable` 中 Attach/Dispose,也可以在 GameObject 上添加 `ShrinkMonoEventScope`,由它统一绑定同对象或子层级中的生成 subscriber。
|
||||
|
||||
静态类型同样只使用特性:
|
||||
|
||||
@@ -93,23 +166,31 @@ public static class GlobalHandlers
|
||||
}
|
||||
```
|
||||
|
||||
Unity ILPostProcessor 会生成直接调用桥和静态模块初始化注册;纯 .NET incremental generator 要求 subscriber 是 `partial`,并生成 ValueTask handler 绑定。生产路径不枚举程序集和方法,不使用 `MethodInfo.Invoke`、`DynamicInvoke` 或 `object[]` 参数。
|
||||
Unity ILPostProcessor 会生成直接调用桥和静态模块初始化注册;NuGet 包通过 `ShrinkSDK.CodeGen` 生成绑定。生产路径不枚举程序集和方法,不使用 `MethodInfo.Invoke`、`DynamicInvoke` 或 `object[]` 参数。
|
||||
|
||||
## Unity 与纯 .NET
|
||||
|
||||
Unity 包依赖 UniTask:
|
||||
Unity 和正式 NuGet 包 `ShrinkSDK.EventBus` 均使用 UniTask,可直接 `await`:
|
||||
|
||||
```csharp
|
||||
UniTask<ShrinkPostResult> PostAsync<TEvent>(...)
|
||||
```
|
||||
|
||||
纯 .NET 实现在 `Tools~/DotNet/ShrinkEventBus.Core`:
|
||||
普通 C# 项目无需安装 Unity 或 Godot。使用 .NET 8 或更新 SDK 新建控制台项目后配置包源并安装:
|
||||
|
||||
```csharp
|
||||
ValueTask<ShrinkPostResult> PostAsync<TEvent>(...)
|
||||
```shell
|
||||
dotnet new console -n EventBusDemo
|
||||
cd EventBusDemo
|
||||
dotnet new nugetconfig
|
||||
dotnet nuget add source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --name ShrinkSDK --configfile nuget.config
|
||||
dotnet add package ShrinkSDK.EventBus --version 2.3.2
|
||||
```
|
||||
|
||||
两边共享事件与特性契约,awaitable 和调度实现按宿主选择,不把 UniTask/ValueTask 写进事件数据。
|
||||
UniTask、Runtime.Abstractions 和构建时 CodeGen 会随包自动还原,不需要手动添加分析器或项目引用。完整可运行示例见 [Samples~/DotNetConsole](Samples~/DotNetConsole/Program.cs),可用它替换新项目的 `Program.cs` 后执行 `dotnet run -c Release`。
|
||||
|
||||
控制台和后台服务建议显式创建 `Inline`、`DedicatedThread` 或 `TaskPool` Bus。`MainThread` 跨线程派发及 `PostDeferred` 需要宿主提供可用的主线程调度器;普通控制台没有 Unity/Godot 的帧循环。
|
||||
|
||||
`Tools~/DotNet/ShrinkEventBus.Core` 是独立的 ValueTask 工具实现,不是上述正式 NuGet 包的运行时。事件数据不应依赖 UniTask/ValueTask。
|
||||
|
||||
## ECS/Burst
|
||||
|
||||
@@ -126,6 +207,29 @@ Burst Job 只写 unmanaged 事实事件到 NativeQueue;Playback 在托管/ECS
|
||||
|
||||
`ShrinkBusOptions` 配置队列容量、溢出策略、最大并发、关闭排空和超时。关键业务默认使用 `Reject`;`DropNewest/DropOldest` 只适用于明确允许丢失的数据;`Wait` 只由 `PostAsync` 使用。
|
||||
|
||||
## 延后发布与诊断
|
||||
|
||||
MainThread Bus 可以用 `PostDeferred` 把事件推迟到下一次主线程泵送:
|
||||
|
||||
```csharp
|
||||
var result = EventBus.PostDeferred(gameBus, new PlayerReadyEvent());
|
||||
if (!result.Accepted)
|
||||
Debug.LogWarning($"deferred post rejected: {result.Failure}");
|
||||
```
|
||||
|
||||
延后发布只接受 `MainThread` 调度且宿主实现了 `IShrinkDeferredMainThreadDispatcher` 的 Bus;其他调度器返回 `DeferredUnsupported`,不会退化成同步分发。队列仍遵守 `QueueCapacity` 与 `OverflowPolicy`,重入发布的事件留到下一次泵送。
|
||||
|
||||
需要外部工具观察分发时使用公开诊断订阅:
|
||||
|
||||
```csharp
|
||||
using var subscription = EventBus.ObserveDiagnostics(diagnostic =>
|
||||
{
|
||||
Debug.Log($"{diagnostic.BusKey} {diagnostic.EventType.Name} {diagnostic.Result.Failure}");
|
||||
});
|
||||
```
|
||||
|
||||
`ShrinkEventDiagnostic` 提供时间、事件类型、Bus、调度器、分发模式、线程、耗时、发布结果和同步标记,不暴露事件对象。观察者抛出的异常会记录并隔离,不影响业务分发或其他观察者。
|
||||
|
||||
## UI Toolkit 调试器
|
||||
|
||||
菜单:`ShrinkSDK/事件总线/事件查看器`。
|
||||
@@ -134,6 +238,8 @@ Burst Job 只写 unmanaged 事实事件到 NativeQueue;Playback 在托管/ECS
|
||||
|
||||
它只观察静态 `EventBus` 宿主管理的 Bus,不捕获独立 `ShrinkEventBusHost`;性能基准仍使用独立 Host,避免 UI 采样进入被测热路径。
|
||||
|
||||
Godot 项目安装 `ShrinkSDK.EventBus.Godot` 后可在编辑器中使用同一套诊断数据的独立调试窗口。
|
||||
|
||||
## Benchmark
|
||||
|
||||
实现位于 `Benchmark/ShrinkEventBusBenchmark.cs`,入口:
|
||||
@@ -168,4 +274,14 @@ ShrinkEventBusBenchmark.Run(
|
||||
- 外部 Mod DLL 必须携带生成合同;没有合同的生产 DLL 不自动反射注册。
|
||||
- Editor 诊断是可选观察层,不参与正式无诊断热路径。
|
||||
|
||||
架构审计与来源说明见 `Docs/JustAnyProjectArchitectureAudit.md` 和根目录 `DESIGN.md`。
|
||||
Unity 独立安装不包含 Entities/Burst 适配包;需要时由宿主额外安装。
|
||||
|
||||
## 可复用能力
|
||||
|
||||
<!-- shrink:capabilities -->
|
||||
Capability: 按类型发布事实和请求,支持同步、异步、优先级和可撤回订阅
|
||||
Aliases: 事件 事件未触发 消息 订阅 通知 event bus
|
||||
Limits: EventBus 不等于业务状态机或资源计量;并行派发须由业务明确选择
|
||||
Extension: IShrinkEvent、ShrinkSubscribe、BusOptions 和拥有者 Attach/Dispose
|
||||
Evidence: [EventBus](Runtime/EventBus.cs); [ShrinkSubscribeAttribute](Runtime/ShrinkEventAttributes.cs); [ShrinkGeneratedBinding](Runtime/ShrinkEventBindings.cs)
|
||||
<!-- /shrink:capabilities -->
|
||||
+93
-8
@@ -57,6 +57,8 @@ namespace ShrinkEventBus
|
||||
private static readonly IShrinkEventBus DefaultBus = CreateDefaultBus();
|
||||
private static Action<IShrinkEvent, Type, ShrinkBusKey>? _posted;
|
||||
private static Action<ShrinkEventTrace>? _detailedPosted;
|
||||
private static readonly object DetailedObserverGate = new();
|
||||
private static Action<ShrinkEventTrace>[]? _detailedObserverSnapshot;
|
||||
|
||||
internal static event Action<IShrinkEvent, Type, ShrinkBusKey> Posted
|
||||
{
|
||||
@@ -78,14 +80,41 @@ namespace ShrinkEventBus
|
||||
|
||||
internal static event Action<ShrinkEventTrace> DetailedPosted
|
||||
{
|
||||
add => _detailedPosted += value;
|
||||
remove => _detailedPosted -= value;
|
||||
add
|
||||
{
|
||||
lock (DetailedObserverGate)
|
||||
{
|
||||
_detailedPosted += value;
|
||||
PublishDetailedObserverSnapshot();
|
||||
}
|
||||
}
|
||||
remove
|
||||
{
|
||||
lock (DetailedObserverGate)
|
||||
{
|
||||
_detailedPosted -= value;
|
||||
PublishDetailedObserverSnapshot();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void PublishDetailedObserverSnapshot()
|
||||
{
|
||||
var invocationList = _detailedPosted?.GetInvocationList();
|
||||
Action<ShrinkEventTrace>[]? snapshot = null;
|
||||
if (invocationList != null)
|
||||
{
|
||||
snapshot = new Action<ShrinkEventTrace>[invocationList.Length];
|
||||
for (var i = 0; i < snapshot.Length; i++)
|
||||
snapshot[i] = (Action<ShrinkEventTrace>)invocationList[i];
|
||||
}
|
||||
Volatile.Write(ref _detailedObserverSnapshot, snapshot);
|
||||
}
|
||||
|
||||
internal static bool HasDetailedPostedObservers
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get => Volatile.Read(ref _detailedPosted) != null;
|
||||
get => Volatile.Read(ref _detailedObserverSnapshot) != null;
|
||||
}
|
||||
|
||||
public static IShrinkEventBus Default => DefaultBus;
|
||||
@@ -133,6 +162,30 @@ namespace ShrinkEventBus
|
||||
CancellationToken cancellationToken = default)
|
||||
where TEvent : IShrinkEvent => DefaultBus.PostAsync(eventData, cancellationToken);
|
||||
|
||||
public static ShrinkPostResult PostDeferred<TEvent>(IShrinkEventBus bus, TEvent eventData)
|
||||
where TEvent : IShrinkEvent
|
||||
{
|
||||
if (bus == null)
|
||||
throw new ArgumentNullException(nameof(bus));
|
||||
return bus is ShrinkEventBusInstance instance
|
||||
? instance.PostDeferred(in eventData)
|
||||
: ShrinkPostResult.Rejected(ShrinkPostFailure.DeferredUnsupported);
|
||||
}
|
||||
|
||||
public static IDisposable ObserveDiagnostics(Action<ShrinkEventDiagnostic> observer)
|
||||
{
|
||||
if (observer == null)
|
||||
throw new ArgumentNullException(nameof(observer));
|
||||
|
||||
void Handler(ShrinkEventTrace trace) => observer(new ShrinkEventDiagnostic(
|
||||
trace.TimestampUtc, trace.EventType, trace.BusKey, trace.Scheduler,
|
||||
trace.DispatchMode, trace.ThreadId, trace.ElapsedTimestampTicks,
|
||||
trace.Result, trace.IsAsync));
|
||||
|
||||
DetailedPosted += Handler;
|
||||
return new DiagnosticSubscription(Handler);
|
||||
}
|
||||
|
||||
public static IDisposable Attach(object target, ShrinkBusKey? defaultBus = null)
|
||||
{
|
||||
if (target == null)
|
||||
@@ -143,6 +196,14 @@ namespace ShrinkEventBus
|
||||
return generated.AttachGenerated(Resolver, defaultBus ?? ShrinkBusKey.Game);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<(Type EventType, System.Reflection.MethodInfo Handler)> CaptureBindings(IShrinkEventBus bus)
|
||||
{
|
||||
if (bus is ShrinkEventBusInstance instance) return instance.CaptureBindings();
|
||||
throw new NotSupportedException("This event bus does not expose binding diagnostics.");
|
||||
}
|
||||
|
||||
public static IReadOnlyList<IShrinkEventBus> CaptureNamedBuses() => new List<IShrinkEventBus>(Buses.Values);
|
||||
|
||||
internal static IReadOnlyList<(ShrinkBusKey Key, ShrinkBusOptions Options, int Subscribers)> Snapshot()
|
||||
{
|
||||
var snapshot = new List<(ShrinkBusKey, ShrinkBusOptions, int)>(Buses.Count);
|
||||
@@ -180,16 +241,40 @@ namespace ShrinkEventBus
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static void NotifyDetailedPosted(ShrinkEventTrace trace)
|
||||
{
|
||||
var observers = Volatile.Read(ref _detailedPosted);
|
||||
var observers = Volatile.Read(ref _detailedObserverSnapshot);
|
||||
if (observers == null)
|
||||
return;
|
||||
try
|
||||
for (var i = 0; i < observers.Length; i++)
|
||||
{
|
||||
observers(trace);
|
||||
try
|
||||
{
|
||||
observers[i](trace);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
UnityEngine.Debug.LogException(exception);
|
||||
#else
|
||||
System.Diagnostics.Trace.TraceError(exception.ToString());
|
||||
#endif
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
}
|
||||
|
||||
private sealed class DiagnosticSubscription : IDisposable
|
||||
{
|
||||
private Action<ShrinkEventTrace>? _handler;
|
||||
|
||||
public DiagnosticSubscription(Action<ShrinkEventTrace> handler)
|
||||
{
|
||||
UnityEngine.Debug.LogException(exception);
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
var handler = Interlocked.Exchange(ref _handler, null);
|
||||
if (handler != null)
|
||||
DetailedPosted -= handler;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
using System;
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public interface IShrinkEventBusMainThreadDispatcher
|
||||
{
|
||||
bool IsMainThread { get; }
|
||||
bool TryPost(Action action);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9ff0b939fcee4292a6183fd899974c9c
|
||||
+143
-50
@@ -1,21 +1,39 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Cysharp.Threading.Tasks;
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
using MainThreadDispatcherContract = ShrinkEventBus.IShrinkEventBusMainThreadDispatcher;
|
||||
#else
|
||||
using MainThreadDispatcherContract = ShrinkSDK.Runtime.IShrinkMainThreadDispatcher;
|
||||
#endif
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
internal interface IShrinkBusScheduler : IDisposable
|
||||
{
|
||||
bool IsOnSchedulerThread { get; }
|
||||
bool SupportsDeferred { get; }
|
||||
bool TryPost(Action action);
|
||||
ShrinkDeferredPostStatus TryPostDeferred(Action action);
|
||||
UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken);
|
||||
UniTask ShutdownAsync(bool drain, TimeSpan timeout);
|
||||
}
|
||||
|
||||
internal enum ShrinkDeferredPostStatus
|
||||
{
|
||||
Accepted,
|
||||
QueueFull,
|
||||
SchedulerRejected,
|
||||
Unsupported,
|
||||
Stopped
|
||||
}
|
||||
|
||||
internal sealed class ShrinkQueueFullException : InvalidOperationException
|
||||
{
|
||||
public ShrinkQueueFullException(string schedulerName)
|
||||
@@ -41,15 +59,29 @@ namespace ShrinkEventBus
|
||||
internal sealed class ShrinkSchedulerWorkItem
|
||||
{
|
||||
private readonly UniTaskCompletionSource? _completion;
|
||||
private readonly Delegate _action;
|
||||
|
||||
public ShrinkSchedulerWorkItem(Action action)
|
||||
{
|
||||
_action = action ?? throw new ArgumentNullException(nameof(action));
|
||||
}
|
||||
|
||||
public ShrinkSchedulerWorkItem(Func<UniTask> action, bool awaitable)
|
||||
{
|
||||
Action = action ?? throw new ArgumentNullException(nameof(action));
|
||||
_action = action ?? throw new ArgumentNullException(nameof(action));
|
||||
if (awaitable)
|
||||
_completion = new UniTaskCompletionSource();
|
||||
}
|
||||
|
||||
public Func<UniTask> Action { get; }
|
||||
public UniTask Invoke()
|
||||
{
|
||||
if (_action is Action synchronousAction)
|
||||
{
|
||||
synchronousAction();
|
||||
return UniTask.CompletedTask;
|
||||
}
|
||||
return ((Func<UniTask>)_action)();
|
||||
}
|
||||
public UniTask Completion => _completion?.Task ?? UniTask.CompletedTask;
|
||||
|
||||
public void Complete() => _completion?.TrySetResult();
|
||||
@@ -75,6 +107,7 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
public bool IsEmpty => _queue.IsEmpty;
|
||||
public int Count => _queue.Count;
|
||||
|
||||
public bool TryEnqueue(ShrinkSchedulerWorkItem item)
|
||||
{
|
||||
@@ -150,7 +183,7 @@ namespace ShrinkEventBus
|
||||
{
|
||||
try
|
||||
{
|
||||
await item.Action();
|
||||
await item.Invoke();
|
||||
item.Complete();
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
@@ -168,7 +201,7 @@ namespace ShrinkEventBus
|
||||
{
|
||||
try
|
||||
{
|
||||
item.Action().GetAwaiter().GetResult();
|
||||
item.Invoke().GetAwaiter().GetResult();
|
||||
item.Complete();
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
@@ -186,6 +219,7 @@ namespace ShrinkEventBus
|
||||
internal sealed class ShrinkInlineScheduler : IShrinkBusScheduler
|
||||
{
|
||||
public bool IsOnSchedulerThread => true;
|
||||
public bool SupportsDeferred => false;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
@@ -193,6 +227,9 @@ namespace ShrinkEventBus
|
||||
return true;
|
||||
}
|
||||
|
||||
public ShrinkDeferredPostStatus TryPostDeferred(Action action) =>
|
||||
ShrinkDeferredPostStatus.Unsupported;
|
||||
|
||||
public UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
@@ -206,35 +243,52 @@ namespace ShrinkEventBus
|
||||
internal sealed class ShrinkMainThreadScheduler : IShrinkBusScheduler
|
||||
{
|
||||
private readonly ShrinkSchedulerQueue _queue;
|
||||
private readonly MainThreadDispatcherContract _dispatcher;
|
||||
private readonly ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher? _deferredDispatcher;
|
||||
private readonly object _gate = new();
|
||||
private readonly Action _pump;
|
||||
private int _pumpScheduled;
|
||||
private int _disposed;
|
||||
private bool _discardPending;
|
||||
|
||||
public ShrinkMainThreadScheduler(string name, ShrinkBusOptions options)
|
||||
{
|
||||
_queue = new ShrinkSchedulerQueue(name, options);
|
||||
_dispatcher = ShrinkEventBusRuntime.MainThreadDispatcher;
|
||||
_deferredDispatcher = _dispatcher as ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher;
|
||||
_pump = () => PumpAsync().Forget();
|
||||
}
|
||||
|
||||
public bool IsOnSchedulerThread => PlayerLoopHelper.IsMainThread;
|
||||
public bool IsOnSchedulerThread => _dispatcher.IsMainThread;
|
||||
public bool SupportsDeferred => _deferredDispatcher != null;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return false;
|
||||
if (Volatile.Read(ref _disposed) != 0) return false;
|
||||
if (IsOnSchedulerThread)
|
||||
{
|
||||
action();
|
||||
return true;
|
||||
}
|
||||
return Enqueue(action) == ShrinkDeferredPostStatus.Accepted;
|
||||
}
|
||||
|
||||
var item = new ShrinkSchedulerWorkItem(() =>
|
||||
public ShrinkDeferredPostStatus TryPostDeferred(Action action)
|
||||
{
|
||||
if (action == null) throw new ArgumentNullException(nameof(action));
|
||||
if (_deferredDispatcher == null) return ShrinkDeferredPostStatus.Unsupported;
|
||||
return Enqueue(action);
|
||||
}
|
||||
|
||||
private ShrinkDeferredPostStatus Enqueue(Action action)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
action();
|
||||
return UniTask.CompletedTask;
|
||||
}, awaitable: false);
|
||||
if (!_queue.TryEnqueue(item))
|
||||
return false;
|
||||
SchedulePump();
|
||||
return true;
|
||||
if (_disposed != 0) return ShrinkDeferredPostStatus.Stopped;
|
||||
var item = new ShrinkSchedulerWorkItem(action);
|
||||
if (!_queue.TryEnqueue(item)) return ShrinkDeferredPostStatus.QueueFull;
|
||||
return SchedulePump() ? ShrinkDeferredPostStatus.Accepted : ShrinkDeferredPostStatus.SchedulerRejected;
|
||||
}
|
||||
}
|
||||
|
||||
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
|
||||
@@ -247,19 +301,24 @@ namespace ShrinkEventBus
|
||||
await action();
|
||||
return;
|
||||
}
|
||||
|
||||
var item = new ShrinkSchedulerWorkItem(action, awaitable: true);
|
||||
await _queue.EnqueueAsync(item, cancellationToken);
|
||||
SchedulePump();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed != 0) _queue.DropPending();
|
||||
else SchedulePump();
|
||||
}
|
||||
await item.Completion.AttachExternalCancellation(cancellationToken);
|
||||
}
|
||||
|
||||
public async UniTask ShutdownAsync(bool drain, TimeSpan timeout)
|
||||
{
|
||||
Interlocked.Exchange(ref _disposed, 1);
|
||||
if (!drain)
|
||||
_queue.DropPending();
|
||||
else
|
||||
lock (_gate)
|
||||
{
|
||||
_disposed = 1;
|
||||
if (!drain) { _discardPending = true; _queue.DropPending(); }
|
||||
}
|
||||
if (drain)
|
||||
await ShrinkSchedulerShutdown.WaitUntilDrainedAsync(
|
||||
_queue, () => Volatile.Read(ref _pumpScheduled) != 0, timeout);
|
||||
_queue.Dispose();
|
||||
@@ -267,31 +326,66 @@ namespace ShrinkEventBus
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
_queue.Dispose();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed != 0) return;
|
||||
_disposed = 1;
|
||||
_discardPending = true;
|
||||
_queue.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void SchedulePump()
|
||||
// All queued work shares one FIFO and capacity. Prefer the deferred dispatcher
|
||||
// so a normal worker-thread post cannot pull deferred events into an inline pump.
|
||||
private bool SchedulePump()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _pumpScheduled, 1) != 0)
|
||||
return;
|
||||
UniTask.Void(PumpAsync);
|
||||
}
|
||||
|
||||
private async UniTaskVoid PumpAsync()
|
||||
{
|
||||
await UniTask.SwitchToMainThread();
|
||||
if (_pumpScheduled != 0) return true;
|
||||
_pumpScheduled = 1;
|
||||
bool accepted;
|
||||
try
|
||||
{
|
||||
while (_queue.TryDequeue(out var item))
|
||||
await ShrinkSchedulerWorkItemRunner.RunAsync(item);
|
||||
accepted = _deferredDispatcher != null
|
||||
? _deferredDispatcher.TryPostDeferred(_pump)
|
||||
: _dispatcher.TryPost(_pump);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_pumpScheduled = 0;
|
||||
_queue.DropPending();
|
||||
throw;
|
||||
}
|
||||
if (accepted) return true;
|
||||
_pumpScheduled = 0;
|
||||
_queue.DropPending();
|
||||
return false;
|
||||
}
|
||||
|
||||
private async UniTask PumpAsync()
|
||||
{
|
||||
ShrinkSchedulerWorkItem[] batch;
|
||||
var count = 0;
|
||||
lock (_gate)
|
||||
{
|
||||
var capacity = _queue.Count;
|
||||
batch = ArrayPool<ShrinkSchedulerWorkItem>.Shared.Rent(Math.Max(1, capacity));
|
||||
while (count < capacity && _queue.TryDequeue(out var item)) batch[count++] = item;
|
||||
}
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (_discardPending) batch[i].Drop(nameof(ShrinkMainThreadScheduler));
|
||||
else await ShrinkSchedulerWorkItemRunner.RunAsync(batch[i]);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _pumpScheduled, 0);
|
||||
if (!_queue.IsEmpty && Volatile.Read(ref _disposed) == 0)
|
||||
SchedulePump();
|
||||
ArrayPool<ShrinkSchedulerWorkItem>.Shared.Return(batch, clearArray: true);
|
||||
lock (_gate)
|
||||
{
|
||||
_pumpScheduled = 0;
|
||||
if (!_queue.IsEmpty) SchedulePump();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -310,22 +404,21 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
public bool IsOnSchedulerThread => false;
|
||||
public bool SupportsDeferred => false;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return false;
|
||||
var item = new ShrinkSchedulerWorkItem(() =>
|
||||
{
|
||||
action();
|
||||
return UniTask.CompletedTask;
|
||||
}, awaitable: false);
|
||||
var item = new ShrinkSchedulerWorkItem(action);
|
||||
if (!_queue.TryEnqueue(item))
|
||||
return false;
|
||||
ScheduleWorkers();
|
||||
return true;
|
||||
}
|
||||
|
||||
public ShrinkDeferredPostStatus TryPostDeferred(Action action) => ShrinkDeferredPostStatus.Unsupported;
|
||||
|
||||
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
@@ -406,6 +499,7 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
public bool IsOnSchedulerThread => Thread.CurrentThread.ManagedThreadId == Volatile.Read(ref _threadId);
|
||||
public bool SupportsDeferred => false;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
@@ -417,17 +511,15 @@ namespace ShrinkEventBus
|
||||
return true;
|
||||
}
|
||||
|
||||
var item = new ShrinkSchedulerWorkItem(() =>
|
||||
{
|
||||
action();
|
||||
return UniTask.CompletedTask;
|
||||
}, awaitable: false);
|
||||
var item = new ShrinkSchedulerWorkItem(action);
|
||||
if (!_queue.TryEnqueue(item))
|
||||
return false;
|
||||
_signal.Set();
|
||||
return true;
|
||||
}
|
||||
|
||||
public ShrinkDeferredPostStatus TryPostDeferred(Action action) => ShrinkDeferredPostStatus.Unsupported;
|
||||
|
||||
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
@@ -453,7 +545,8 @@ namespace ShrinkEventBus
|
||||
var waitMs = timeout == Timeout.InfiniteTimeSpan
|
||||
? Timeout.Infinite
|
||||
: Math.Max(0, (int)Math.Min(int.MaxValue, timeout.TotalMilliseconds));
|
||||
var stopped = await UniTask.RunOnThreadPool(() => _stopped.Wait(waitMs));
|
||||
var stopped = await Task.Run(() => _stopped.Wait(waitMs))
|
||||
.AsUniTask(useCurrentSynchronizationContext: false);
|
||||
if (!stopped)
|
||||
{
|
||||
_queue.DropPending();
|
||||
@@ -538,7 +631,7 @@ namespace ShrinkEventBus
|
||||
queue.DropPending();
|
||||
return;
|
||||
}
|
||||
await UniTask.Delay(1, ignoreTimeScale: true);
|
||||
await Task.Delay(1).AsUniTask(useCurrentSynchronizationContext: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,18 @@ using System;
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public enum ShrinkSubscriberLifetime
|
||||
{
|
||||
Manual = 0,
|
||||
AwakeToDestroy = 1
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
|
||||
public sealed class ShrinkEventSubscriberAttribute : Attribute
|
||||
{
|
||||
public string OwnerId { get; set; } = string.Empty;
|
||||
public string DefaultBus { get; set; } = string.Empty;
|
||||
public ShrinkSubscriberLifetime Lifetime { get; set; } = ShrinkSubscriberLifetime.Manual;
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "ShrinkEventBus.Runtime",
|
||||
"rootNamespace": "ShrinkEventBus",
|
||||
"references": [
|
||||
"UniTask"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": false,
|
||||
"autoReferenced": true
|
||||
}
|
||||
"name": "ShrinkEventBus.Runtime",
|
||||
"rootNamespace": "ShrinkEventBus",
|
||||
"references": [
|
||||
"UniTask",
|
||||
"ShrinkRuntime.Abstractions"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": false,
|
||||
"autoReferenced": true
|
||||
}
|
||||
@@ -14,6 +14,7 @@ namespace ShrinkEventBus
|
||||
internal interface IShrinkEventChannel
|
||||
{
|
||||
int Count { get; }
|
||||
void CaptureBindings(List<(Type EventType, System.Reflection.MethodInfo Handler)> bindings);
|
||||
bool RemoveSubscription(long subscriptionId);
|
||||
void Clear();
|
||||
void DetachSlot(int slot);
|
||||
@@ -87,6 +88,15 @@ namespace ShrinkEventBus
|
||||
private Action<TEvent>? _syncDispatcher;
|
||||
|
||||
public int Count => _snapshot.Length;
|
||||
public void CaptureBindings(List<(Type EventType, System.Reflection.MethodInfo Handler)> bindings)
|
||||
{
|
||||
var snapshot = _snapshot;
|
||||
foreach (var entry in snapshot)
|
||||
{
|
||||
var method = entry.SyncHandler?.Method ?? entry.AsyncHandler?.Method;
|
||||
if (method != null) bindings.Add((typeof(TEvent), method));
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(long subscriptionId, long registrationOrder, Action<TEvent> handler,
|
||||
ShrinkSubscribeDescriptor descriptor)
|
||||
|
||||
@@ -75,7 +75,7 @@ namespace ShrinkEventBus
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public virtual ShrinkPostResult Post<TEvent>(in TEvent eventData) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (eventData is null)
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return TraceWithoutDispatch(in eventData,
|
||||
@@ -84,6 +84,35 @@ namespace ShrinkEventBus
|
||||
if (_isInline || _scheduler.IsOnSchedulerThread)
|
||||
return Dispatch(in eventData);
|
||||
|
||||
return PostScheduled(in eventData);
|
||||
}
|
||||
|
||||
internal ShrinkPostResult PostDeferred<TEvent>(in TEvent eventData) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return TraceWithoutDispatch(in eventData,
|
||||
ShrinkPostResult.Rejected(ShrinkPostFailure.BusStopped), false);
|
||||
if (Options.Scheduler != ShrinkBusSchedulerKind.MainThread || !_scheduler.SupportsDeferred)
|
||||
return TraceWithoutDispatch(in eventData,
|
||||
ShrinkPostResult.Rejected(ShrinkPostFailure.DeferredUnsupported), false);
|
||||
|
||||
var queuedEvent = eventData;
|
||||
var status = _scheduler.TryPostDeferred(() => Dispatch(in queuedEvent));
|
||||
if (status == ShrinkDeferredPostStatus.Accepted) return new ShrinkPostResult(true, false, false);
|
||||
var failure = status switch
|
||||
{
|
||||
ShrinkDeferredPostStatus.Unsupported => ShrinkPostFailure.DeferredUnsupported,
|
||||
ShrinkDeferredPostStatus.Stopped => ShrinkPostFailure.BusStopped,
|
||||
ShrinkDeferredPostStatus.SchedulerRejected => ShrinkPostFailure.SchedulerRejected,
|
||||
_ => ShrinkPostFailure.QueueFull
|
||||
};
|
||||
return TraceWithoutDispatch(in eventData, ShrinkPostResult.Rejected(failure), false);
|
||||
}
|
||||
|
||||
private ShrinkPostResult PostScheduled<TEvent>(in TEvent eventData) where TEvent : IShrinkEvent
|
||||
{
|
||||
var queuedEvent = eventData;
|
||||
if (_scheduler.TryPost(() => Dispatch(in queuedEvent)))
|
||||
return new ShrinkPostResult(true, false, false);
|
||||
@@ -94,7 +123,7 @@ namespace ShrinkEventBus
|
||||
public virtual UniTask<ShrinkPostResult> PostAsync<TEvent>(TEvent eventData,
|
||||
CancellationToken cancellationToken = default) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (eventData is null)
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return UniTask.FromResult(TraceWithoutDispatch(in eventData,
|
||||
@@ -168,6 +197,13 @@ namespace ShrinkEventBus
|
||||
return new EventSubscription(this, subscriptionId);
|
||||
}
|
||||
|
||||
internal IReadOnlyList<(Type EventType, System.Reflection.MethodInfo Handler)> CaptureBindings()
|
||||
{
|
||||
var bindings = new List<(Type, System.Reflection.MethodInfo)>();
|
||||
lock (_channelGate) foreach (var channel in _channels.Values) channel.CaptureBindings(bindings);
|
||||
return bindings;
|
||||
}
|
||||
|
||||
internal int SubscriberCount
|
||||
{
|
||||
get
|
||||
@@ -195,7 +231,7 @@ namespace ShrinkEventBus
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected ShrinkPostResult Dispatch<TEvent>(in TEvent eventData) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (_postObserver != null && EventBus.HasDetailedPostedObservers)
|
||||
if (EventBus.HasDetailedPostedObservers)
|
||||
return DispatchObserved(in eventData);
|
||||
|
||||
var channel = ShrinkEventChannelSlots<TEvent>.Get(_busSlot);
|
||||
@@ -210,7 +246,7 @@ namespace ShrinkEventBus
|
||||
protected async UniTask<ShrinkPostResult> DispatchAsync<TEvent>(TEvent eventData,
|
||||
CancellationToken cancellationToken) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (_postObserver != null && EventBus.HasDetailedPostedObservers)
|
||||
if (EventBus.HasDetailedPostedObservers)
|
||||
return await DispatchAsyncObserved(eventData, cancellationToken);
|
||||
|
||||
var channel = ShrinkEventChannelSlots<TEvent>.Get(_busSlot);
|
||||
@@ -246,8 +282,8 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
var elapsedTicks = Stopwatch.GetTimestamp() - startedAt;
|
||||
if (EventBus.HasPostedObservers)
|
||||
_postObserver!(eventData, typeof(TEvent), Key);
|
||||
if (_postObserver != null && EventBus.HasPostedObservers)
|
||||
_postObserver(eventData, typeof(TEvent), Key);
|
||||
EventBus.NotifyDetailedPosted(new ShrinkEventTrace(DateTime.UtcNow, typeof(TEvent), Key,
|
||||
Options, threadId, elapsedTicks, result, false));
|
||||
return result;
|
||||
@@ -257,7 +293,7 @@ namespace ShrinkEventBus
|
||||
protected ShrinkPostResult TraceWithoutDispatch<TEvent>(in TEvent eventData,
|
||||
ShrinkPostResult result, bool isAsync) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (_postObserver != null && EventBus.HasDetailedPostedObservers)
|
||||
if (EventBus.HasDetailedPostedObservers)
|
||||
{
|
||||
EventBus.NotifyDetailedPosted(new ShrinkEventTrace(DateTime.UtcNow, typeof(TEvent), Key,
|
||||
Options, Thread.CurrentThread.ManagedThreadId, 0L, result, isAsync));
|
||||
@@ -297,8 +333,8 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
var elapsedTicks = Stopwatch.GetTimestamp() - startedAt;
|
||||
if (EventBus.HasPostedObservers)
|
||||
_postObserver!(eventData, typeof(TEvent), Key);
|
||||
if (_postObserver != null && EventBus.HasPostedObservers)
|
||||
_postObserver(eventData, typeof(TEvent), Key);
|
||||
EventBus.NotifyDetailedPosted(new ShrinkEventTrace(DateTime.UtcNow, typeof(TEvent), Key,
|
||||
Options, threadId, elapsedTicks, result, true));
|
||||
return result;
|
||||
@@ -367,7 +403,7 @@ namespace ShrinkEventBus
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override ShrinkPostResult Post<TEvent>(in TEvent eventData)
|
||||
{
|
||||
if (eventData is null)
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (IsDisposed)
|
||||
return TraceWithoutDispatch(in eventData,
|
||||
@@ -378,7 +414,7 @@ namespace ShrinkEventBus
|
||||
public override UniTask<ShrinkPostResult> PostAsync<TEvent>(TEvent eventData,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (eventData is null)
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (IsDisposed)
|
||||
return UniTask.FromResult(TraceWithoutDispatch(in eventData,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
using MainThreadDispatcherContract = ShrinkEventBus.IShrinkEventBusMainThreadDispatcher;
|
||||
#else
|
||||
using MainThreadDispatcherContract = ShrinkSDK.Runtime.IShrinkMainThreadDispatcher;
|
||||
#endif
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public static class ShrinkEventBusRuntime
|
||||
{
|
||||
private static MainThreadDispatcherContract _mainThreadDispatcher = CreateDefaultDispatcher();
|
||||
|
||||
public static MainThreadDispatcherContract MainThreadDispatcher =>
|
||||
Volatile.Read(ref _mainThreadDispatcher);
|
||||
|
||||
public static void ConfigureMainThreadDispatcher(MainThreadDispatcherContract dispatcher)
|
||||
{
|
||||
if (dispatcher == null)
|
||||
throw new ArgumentNullException(nameof(dispatcher));
|
||||
Volatile.Write(ref _mainThreadDispatcher, dispatcher);
|
||||
}
|
||||
|
||||
private static MainThreadDispatcherContract CreateDefaultDispatcher()
|
||||
{
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
return new ShrinkUnityMainThreadDispatcher();
|
||||
#else
|
||||
return new ShrinkSynchronizationContextDispatcher(
|
||||
SynchronizationContext.Current,
|
||||
Thread.CurrentThread.ManagedThreadId);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
internal sealed class ShrinkUnityMainThreadDispatcher : MainThreadDispatcherContract,
|
||||
ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher
|
||||
{
|
||||
public bool IsMainThread => Cysharp.Threading.Tasks.PlayerLoopHelper.IsMainThread;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
Cysharp.Threading.Tasks.PlayerLoopHelper.AddContinuation(
|
||||
Cysharp.Threading.Tasks.PlayerLoopTiming.Update,
|
||||
action);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryPostDeferred(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
Cysharp.Threading.Tasks.PlayerLoopHelper.AddContinuation(
|
||||
Cysharp.Threading.Tasks.PlayerLoopTiming.Update,
|
||||
action);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#else
|
||||
internal sealed class ShrinkSynchronizationContextDispatcher : MainThreadDispatcherContract,
|
||||
ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher
|
||||
{
|
||||
private readonly SynchronizationContext? _context;
|
||||
private readonly int _threadId;
|
||||
|
||||
public ShrinkSynchronizationContextDispatcher(SynchronizationContext? context, int threadId)
|
||||
{
|
||||
_context = context;
|
||||
_threadId = threadId;
|
||||
}
|
||||
|
||||
public bool IsMainThread => Thread.CurrentThread.ManagedThreadId == _threadId;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
if (IsMainThread)
|
||||
{
|
||||
action();
|
||||
return true;
|
||||
}
|
||||
if (_context == null)
|
||||
return false;
|
||||
_context.Post(static state => ((Action)state!).Invoke(), action);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryPostDeferred(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
if (_context == null)
|
||||
return false;
|
||||
_context.Post(static state => ((Action)state!).Invoke(), action);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3badb120248f61b4e9af7b571431a681
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -61,7 +61,9 @@ namespace ShrinkEventBus
|
||||
QueueFull = 2,
|
||||
Canceled = 3,
|
||||
HandlerException = 4,
|
||||
InvalidEvent = 5
|
||||
InvalidEvent = 5,
|
||||
DeferredUnsupported = 6,
|
||||
SchedulerRejected = 7
|
||||
}
|
||||
|
||||
public readonly struct ShrinkPostResult
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public readonly struct ShrinkEventDiagnostic
|
||||
{
|
||||
internal ShrinkEventDiagnostic(DateTime timestampUtc, Type eventType, ShrinkBusKey busKey,
|
||||
ShrinkBusSchedulerKind scheduler, ShrinkDispatchMode dispatchMode, int threadId,
|
||||
long elapsedTimestampTicks, ShrinkPostResult result, bool isAsync)
|
||||
{
|
||||
TimestampUtc = timestampUtc;
|
||||
EventType = eventType;
|
||||
BusKey = busKey;
|
||||
Scheduler = scheduler;
|
||||
DispatchMode = dispatchMode;
|
||||
ThreadId = threadId;
|
||||
ElapsedTimestampTicks = elapsedTimestampTicks;
|
||||
Result = result;
|
||||
IsAsync = isAsync;
|
||||
}
|
||||
|
||||
public DateTime TimestampUtc { get; }
|
||||
public Type EventType { get; }
|
||||
public ShrinkBusKey BusKey { get; }
|
||||
public ShrinkBusSchedulerKind Scheduler { get; }
|
||||
public ShrinkDispatchMode DispatchMode { get; }
|
||||
public int ThreadId { get; }
|
||||
public long ElapsedTimestampTicks { get; }
|
||||
public double ElapsedMilliseconds => ElapsedTimestampTicks * 1000d / Stopwatch.Frequency;
|
||||
public TimeSpan Elapsed => TimeSpan.FromSeconds(ElapsedTimestampTicks / (double)Stopwatch.Frequency);
|
||||
public ShrinkPostResult Result { get; }
|
||||
public bool IsAsync { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0dd120bc74194af29d7cbd1f8c80c141
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ShrinkSDK.EventBus" Version="2.3.2" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,40 @@
|
||||
using ShrinkEventBus;
|
||||
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var bus = host.CreateBus(ShrinkBusKey.Game, ShrinkBusOptions.Inline());
|
||||
var subscriber = new OrderSubscriber();
|
||||
using var binding = host.Attach(subscriber);
|
||||
var diagnostics = 0;
|
||||
using var observation = EventBus.ObserveDiagnostics(_ => diagnostics++);
|
||||
|
||||
bus.Post(new OrderPlaced(2));
|
||||
await bus.PostAsync(new OrderPlaced(3));
|
||||
if (subscriber.Total != 5 || diagnostics != 2)
|
||||
throw new InvalidOperationException("Generated subscription or diagnostics failed.");
|
||||
|
||||
var workerKey = new ShrinkBusKey("worker", "orders");
|
||||
var worker = host.CreateBus(workerKey, ShrinkBusOptions.DedicatedThread());
|
||||
var workerSubscriber = new OrderSubscriber();
|
||||
using var workerBinding = host.Attach(workerSubscriber, workerKey);
|
||||
await worker.PostAsync(new OrderPlaced(7));
|
||||
if (workerSubscriber.Total != 7)
|
||||
throw new InvalidOperationException("Dedicated-thread delivery failed.");
|
||||
|
||||
binding.Dispose();
|
||||
bus.Post(new OrderPlaced(10));
|
||||
if (subscriber.Total != 5)
|
||||
throw new InvalidOperationException("Unsubscribe failed.");
|
||||
|
||||
await host.ShutdownAsync();
|
||||
Console.WriteLine("EVENTBUS_CONSOLE_PASS: sync, async, diagnostics, worker, unsubscribe");
|
||||
|
||||
public readonly record struct OrderPlaced(int Amount) : IShrinkEvent;
|
||||
|
||||
[ShrinkEventSubscriber]
|
||||
public sealed partial class OrderSubscriber
|
||||
{
|
||||
public int Total { get; private set; }
|
||||
|
||||
[ShrinkSubscribe]
|
||||
private void OnOrder(OrderPlaced order) => Total += order.Amount;
|
||||
}
|
||||
@@ -14,6 +14,41 @@ namespace ShrinkEventBus.PlayMode.Tests
|
||||
public int Value { get; }
|
||||
}
|
||||
|
||||
internal readonly struct AwakeToDestroyEvent : IShrinkEvent
|
||||
{
|
||||
public AwakeToDestroyEvent(int value) => Value = value;
|
||||
public int Value { get; }
|
||||
}
|
||||
|
||||
[ShrinkEventSubscriber(
|
||||
DefaultBus = "game",
|
||||
Lifetime = ShrinkSubscriberLifetime.AwakeToDestroy)]
|
||||
internal sealed class AwakeToDestroyTarget : MonoBehaviour
|
||||
{
|
||||
public static int Sum { get; set; }
|
||||
public static int AwakeCalls { get; set; }
|
||||
public static int DestroyCalls { get; set; }
|
||||
|
||||
private void Awake() => AwakeCalls++;
|
||||
private void OnDestroy() => DestroyCalls++;
|
||||
|
||||
[ShrinkSubscribe]
|
||||
private void OnEvent(AwakeToDestroyEvent value) => Sum += value.Value;
|
||||
}
|
||||
|
||||
[ShrinkEventSubscriber(Lifetime = ShrinkSubscriberLifetime.AwakeToDestroy)]
|
||||
internal abstract class AbstractAwakeToDestroyTarget : MonoBehaviour
|
||||
{
|
||||
public static int Sum { get; set; }
|
||||
|
||||
[ShrinkSubscribe]
|
||||
private void OnEvent(AwakeToDestroyEvent value) => Sum += value.Value;
|
||||
}
|
||||
|
||||
internal sealed class ConcreteAwakeToDestroyTarget : AbstractAwakeToDestroyTarget
|
||||
{
|
||||
}
|
||||
|
||||
[ShrinkEventSubscriber(DefaultBus = "game")]
|
||||
internal sealed class MonoLifecycleTarget : MonoBehaviour
|
||||
{
|
||||
@@ -25,6 +60,53 @@ namespace ShrinkEventBus.PlayMode.Tests
|
||||
|
||||
public sealed class ShrinkMonoEventScopePlayModeTests
|
||||
{
|
||||
[UnityTest]
|
||||
public IEnumerator AwakeToDestroyLifetimeIsInjectedWithoutManualBinding()
|
||||
{
|
||||
AwakeToDestroyTarget.Sum = 0;
|
||||
AwakeToDestroyTarget.AwakeCalls = 0;
|
||||
AwakeToDestroyTarget.DestroyCalls = 0;
|
||||
var gameObject = new GameObject("ShrinkEventBus-AwakeToDestroy");
|
||||
var target = gameObject.AddComponent<AwakeToDestroyTarget>();
|
||||
|
||||
yield return null;
|
||||
Assert.IsInstanceOf<IShrinkGeneratedSubscriber>(target);
|
||||
Assert.AreEqual(1, AwakeToDestroyTarget.AwakeCalls);
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(3)).ToCoroutine();
|
||||
Assert.AreEqual(3, AwakeToDestroyTarget.Sum);
|
||||
|
||||
gameObject.SetActive(false);
|
||||
yield return null;
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(5)).ToCoroutine();
|
||||
Assert.AreEqual(8, AwakeToDestroyTarget.Sum,
|
||||
"AwakeToDestroy subscriptions must survive OnDisable.");
|
||||
|
||||
Object.Destroy(gameObject);
|
||||
yield return null;
|
||||
Assert.AreEqual(1, AwakeToDestroyTarget.DestroyCalls);
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(7)).ToCoroutine();
|
||||
Assert.AreEqual(8, AwakeToDestroyTarget.Sum,
|
||||
"The generated OnDestroy release must remove the subscription.");
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator AwakeToDestroyLifetimeSupportsAbstractSubscriberBasesWithoutLifecycleMethods()
|
||||
{
|
||||
AbstractAwakeToDestroyTarget.Sum = 0;
|
||||
var gameObject = new GameObject("ShrinkEventBus-AbstractAwakeToDestroy");
|
||||
var target = gameObject.AddComponent<ConcreteAwakeToDestroyTarget>();
|
||||
|
||||
yield return null;
|
||||
Assert.IsInstanceOf<IShrinkGeneratedSubscriber>(target);
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(11)).ToCoroutine();
|
||||
Assert.AreEqual(11, AbstractAwakeToDestroyTarget.Sum);
|
||||
|
||||
Object.Destroy(gameObject);
|
||||
yield return null;
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(13)).ToCoroutine();
|
||||
Assert.AreEqual(11, AbstractAwakeToDestroyTarget.Sum);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator OnEnableAttachesAndOnDisableReleases()
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"rootNamespace": "ShrinkEventBus.Tests",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"ShrinkRuntime.Abstractions",
|
||||
"UniTask",
|
||||
"UnityEngine.TestRunner",
|
||||
"UnityEditor.TestRunner"
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
namespace ShrinkEventBus.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class ShrinkEventBusDeferredDiagnosticsTests
|
||||
{
|
||||
private IShrinkEventBusMainThreadDispatcher _originalDispatcher;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_originalDispatcher = ShrinkEventBusRuntime.MainThreadDispatcher;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(_originalDispatcher);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ObserveDiagnostics_ReportsMetadataAndUnsubscribes()
|
||||
{
|
||||
var diagnostics = new List<ShrinkEventDiagnostic>();
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("diagnostics", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, ShrinkBusOptions.Inline());
|
||||
|
||||
var subscription = EventBus.ObserveDiagnostics(diagnostics.Add);
|
||||
bus.Post(new DeferredEvent(1));
|
||||
subscription.Dispose();
|
||||
bus.Post(new DeferredEvent(2));
|
||||
|
||||
Assert.AreEqual(1, diagnostics.Count);
|
||||
Assert.AreEqual(typeof(DeferredEvent), diagnostics[0].EventType);
|
||||
Assert.AreEqual(key, diagnostics[0].BusKey);
|
||||
Assert.IsTrue(diagnostics[0].Result.Accepted);
|
||||
Assert.IsFalse(diagnostics[0].IsAsync);
|
||||
Assert.GreaterOrEqual(diagnostics[0].ElapsedTimestampTicks, 0L);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ObserveDiagnostics_ThrowingObserverDoesNotBlockBusinessOrOtherObservers()
|
||||
{
|
||||
var calls = 0;
|
||||
var secondObserverCalls = 0;
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("diagnostics", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, ShrinkBusOptions.Inline());
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ => calls++, ShrinkEventPriority.Normal, 0, false);
|
||||
using var first = EventBus.ObserveDiagnostics(_ =>
|
||||
throw new InvalidOperationException("observer failure"));
|
||||
using var second = EventBus.ObserveDiagnostics(_ => secondObserverCalls++);
|
||||
|
||||
var previous = LogAssert.ignoreFailingMessages;
|
||||
LogAssert.ignoreFailingMessages = true;
|
||||
try
|
||||
{
|
||||
Assert.DoesNotThrow(() => bus.Post(new DeferredEvent(3)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
LogAssert.ignoreFailingMessages = previous;
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, calls);
|
||||
Assert.AreEqual(1, secondObserverCalls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ObserveDiagnostics_MutationsApplyToNextDispatch()
|
||||
{
|
||||
var calls = new List<string>();
|
||||
IDisposable second = null;
|
||||
IDisposable added = null;
|
||||
using var first = EventBus.ObserveDiagnostics(_ =>
|
||||
{
|
||||
calls.Add("first");
|
||||
second.Dispose();
|
||||
if (added == null)
|
||||
added = EventBus.ObserveDiagnostics(__ => calls.Add("added"));
|
||||
});
|
||||
second = EventBus.ObserveDiagnostics(_ => calls.Add("second"));
|
||||
try
|
||||
{
|
||||
EventBus.NotifyDetailedPosted(default);
|
||||
CollectionAssert.AreEqual(new[] { "first", "second" }, calls);
|
||||
calls.Clear();
|
||||
EventBus.NotifyDetailedPosted(default);
|
||||
CollectionAssert.AreEqual(new[] { "first", "added" }, calls);
|
||||
}
|
||||
finally
|
||||
{
|
||||
second.Dispose();
|
||||
added?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_DoesNotDispatchBeforePump()
|
||||
{
|
||||
var dispatcher = new ManualDispatcher();
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(dispatcher);
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread,
|
||||
QueueCapacity = 8
|
||||
});
|
||||
var calls = 0;
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ => calls++, ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
var result = EventBus.PostDeferred(bus, new DeferredEvent(4));
|
||||
|
||||
Assert.IsTrue(result.Accepted);
|
||||
Assert.IsFalse(result.Handled);
|
||||
Assert.AreEqual(0, calls);
|
||||
Assert.AreEqual(1, dispatcher.Count);
|
||||
|
||||
dispatcher.PumpAll();
|
||||
Assert.AreEqual(1, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_ReentrantPostWaitsForNextPump()
|
||||
{
|
||||
var dispatcher = new ManualDispatcher();
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(dispatcher);
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread,
|
||||
QueueCapacity = 8
|
||||
});
|
||||
var calls = 0;
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ =>
|
||||
{
|
||||
calls++;
|
||||
if (calls == 1)
|
||||
EventBus.PostDeferred(bus, new DeferredEvent(5));
|
||||
}, ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
EventBus.PostDeferred(bus, new DeferredEvent(4));
|
||||
dispatcher.PumpAll();
|
||||
Assert.AreEqual(1, calls);
|
||||
Assert.AreEqual(1, dispatcher.Count);
|
||||
|
||||
dispatcher.PumpAll();
|
||||
Assert.AreEqual(2, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_DropOldestKeepsNewest()
|
||||
{
|
||||
var dispatcher = new ManualDispatcher();
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(dispatcher);
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread,
|
||||
QueueCapacity = 1,
|
||||
OverflowPolicy = ShrinkQueueOverflowPolicy.DropOldest
|
||||
});
|
||||
var values = new List<int>();
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, evt => values.Add(evt.Value), ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
EventBus.PostDeferred(bus, new DeferredEvent(1));
|
||||
EventBus.PostDeferred(bus, new DeferredEvent(2));
|
||||
dispatcher.PumpAll();
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 2 }, values);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_InlineBusFailsWithoutDispatch()
|
||||
{
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, ShrinkBusOptions.Inline());
|
||||
var calls = 0;
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ => calls++, ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
var result = EventBus.PostDeferred(bus, new DeferredEvent(6));
|
||||
|
||||
Assert.AreEqual(ShrinkPostFailure.DeferredUnsupported, result.Failure);
|
||||
Assert.AreEqual(0, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_WithoutDeferredDispatcherFailsWithoutDispatch()
|
||||
{
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(new NonDeferredDispatcher());
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread
|
||||
});
|
||||
var calls = 0;
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ => calls++, ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
var result = EventBus.PostDeferred(bus, new DeferredEvent(7));
|
||||
|
||||
Assert.AreEqual(ShrinkPostFailure.DeferredUnsupported, result.Failure);
|
||||
Assert.AreEqual(0, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_DisposedBusRejects()
|
||||
{
|
||||
var dispatcher = new ManualDispatcher();
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(dispatcher);
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread
|
||||
});
|
||||
bus.Dispose();
|
||||
|
||||
var result = EventBus.PostDeferred(bus, new DeferredEvent(8));
|
||||
|
||||
Assert.AreEqual(ShrinkPostFailure.BusStopped, result.Failure);
|
||||
}
|
||||
|
||||
private readonly struct DeferredEvent : IShrinkEvent
|
||||
{
|
||||
public DeferredEvent(int value) => Value = value;
|
||||
public int Value { get; }
|
||||
}
|
||||
|
||||
private sealed class ManualDispatcher : IShrinkEventBusMainThreadDispatcher,
|
||||
ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher
|
||||
{
|
||||
private readonly Queue<Action> _queue = new();
|
||||
|
||||
public bool IsMainThread => true;
|
||||
public int Count => _queue.Count;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
_queue.Enqueue(action);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryPostDeferred(Action action)
|
||||
{
|
||||
_queue.Enqueue(action);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void PumpAll()
|
||||
{
|
||||
var count = _queue.Count;
|
||||
for (var i = 0; i < count; i++)
|
||||
_queue.Dequeue()();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NonDeferredDispatcher : IShrinkEventBusMainThreadDispatcher
|
||||
{
|
||||
public bool IsMainThread => true;
|
||||
public bool TryPost(Action action) => true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 070c5e5975c64a39badcb0ebb04c2902
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
<AssemblyName>ShrinkEventBus.Core</AssemblyName>
|
||||
<RootNamespace>ShrinkEventBus</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="ShrinkEventBus.cs" />
|
||||
<Compile Include="Schedulers.cs" />
|
||||
<Compile Include="../../../Runtime/ShrinkEventContracts.cs" Link="Runtime/ShrinkEventContracts.cs" />
|
||||
<Compile Include="../../../Runtime/ShrinkEventAttributes.cs" Link="Runtime/ShrinkEventAttributes.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
<IncludeBuildOutput>false</IncludeBuildOutput>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../ShrinkEventBus.Core/ShrinkEventBus.Core.csproj" />
|
||||
<ProjectReference Include="../ShrinkEventBus.Generator/ShrinkEventBus.Generator.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+7
-6
@@ -1,15 +1,16 @@
|
||||
{
|
||||
"name": "com.cneicy.shrink-eventbus",
|
||||
"version": "2.0.0",
|
||||
"version": "2.3.2",
|
||||
"displayName": "ShrinkEventBus",
|
||||
"description": "多 Bus、特性强类型注册、UniTask 调度与低分配发布的 Unity 事件总线。",
|
||||
"unity": "2022.3",
|
||||
"documentationUrl": "https://git.crash.work/ShrinkSDK/ShrinkEventBus",
|
||||
"changelogUrl": "https://git.crash.work/ShrinkSDK/ShrinkEventBus/src/branch/main/CHANGELOG.md",
|
||||
"licensesUrl": "https://git.crash.work/ShrinkSDK/ShrinkEventBus/src/branch/main/LICENSE",
|
||||
"documentationUrl": "https://github.com/cneicy/ShrinkEventBus",
|
||||
"changelogUrl": "https://github.com/cneicy/ShrinkEventBus/blob/main/CHANGELOG.md",
|
||||
"licensesUrl": "https://github.com/cneicy/ShrinkEventBus/blob/main/LICENSE",
|
||||
"dependencies": {
|
||||
"com.cysharp.unitask": "2.5.10",
|
||||
"com.unity.nuget.mono-cecil": "1.11.4"
|
||||
"com.unity.nuget.mono-cecil": "1.11.4",
|
||||
"com.cneicy.shrink-runtime-abstractions": "0.2.0"
|
||||
},
|
||||
"keywords": [
|
||||
"eventbus",
|
||||
@@ -19,6 +20,6 @@
|
||||
],
|
||||
"author": {
|
||||
"name": "cneicy",
|
||||
"url": "https://git.crash.work/ShrinkSDK"
|
||||
"url": "https://github.com/cneicy"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user