diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index df9af6399..dc906534f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,7 +8,70 @@ on: workflow_dispatch: jobs: + # 数据库契约双绿门禁:PG + Mongo 双主线全验证档的发布前提 + # (A1 裁决:DatabaseConditionalWritePrimitivesTests + 可翻译子集契约在两家 Provider 上必须全部通过; + # Sqlite 档随套件常开,作为零依赖上手+测试档的回归网)。 + database-contract-gate: + name: Database Contract Gate (PostgreSQL + MongoDB) + runs-on: ubuntu-latest + permissions: + contents: read + services: + postgres: + image: postgres:17 + env: + POSTGRES_PASSWORD: postgres + POSTGRES_DB: gameframex + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + env: + GAMEFRAMEX_TEST_MONGODB_CONNECTION_STRING: mongodb://localhost:27017 + GAMEFRAMEX_TEST_POSTGRESQL_CONNECTION_STRING: 'Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=postgres' + steps: + # Mongo 以单节点副本集运行(独立 service 容器无法传 mongod 参数): + # 发布门禁必须实际执行事务回滚/嵌套断言(hello.setName 探测),不能停在独立服务跳过路径。 + # 独立服务的跳过路径由 topology-equivalence 工作流的常开 mongo service 覆盖。 + - name: Start MongoDB Single-Node Replica Set + run: | + docker run -d --name mongo-replica-set -p 27017:27017 mongo:7 --replSet rs0 --bind_ip_all + for attempt in $(seq 1 30); do + if docker exec mongo-replica-set mongosh --quiet --eval "db.adminCommand('ping').ok" | grep -q 1; then break; fi + sleep 2 + done + docker exec mongo-replica-set mongosh --quiet --eval "try { rs.initiate({ _id: 'rs0', members: [ { _id: 0, host: 'localhost:27017' } ] }) } catch (error) { }" + for attempt in $(seq 1 30); do + if docker exec mongo-replica-set mongosh --quiet --eval "db.hello().isWritablePrimary" | grep -q true; then exit 0; fi + sleep 2 + done + echo "mongodb replica set did not become primary in time" >&2 + exit 1 + - name: Checkout Repository + uses: actions/checkout@v7 + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: 10.0.x + + - name: Restore + run: dotnet restore Server.slnx + + - name: Build + run: dotnet build Server.slnx --no-restore + + - name: Run Database Contract Suite (SQLite always + PostgreSQL + MongoDB) + run: > + dotnet test Tests/GameFrameX.Tests/GameFrameX.Tests.csproj --no-build + --filter "FullyQualifiedName~GameFrameX.Tests.DataBase.DatabaseConditionalWritePrimitivesTests|FullyQualifiedName~GameFrameX.Tests.DataBase.DatabaseExecuteInTransactionAtomicityTests|FullyQualifiedName~GameFrameX.Tests.DataBase.SqlitePredicatePushdownTests|FullyQualifiedName~GameFrameX.Tests.DataBase.PostgreSqlDbServiceQueryTests|FullyQualifiedName~GameFrameX.Tests.DataBase.MongoDbServiceQueryTests" + --logger GitHubActions + release: + needs: database-contract-gate # GITHUB_TOKEN 权限由复用工作流内部统一声明(contents: write / packages: write),调用方无需重复声明。 uses: GameFrameX/public-github-actions/.github/workflows/publish-dotnet-release.yml@main with: diff --git a/.github/workflows/topology-equivalence.yml b/.github/workflows/topology-equivalence.yml index f5d989b00..1b19ad503 100644 --- a/.github/workflows/topology-equivalence.yml +++ b/.github/workflows/topology-equivalence.yml @@ -62,5 +62,5 @@ jobs: - name: Run Topology Equivalence Suite run: > dotnet test Tests/GameFrameX.Tests/GameFrameX.Tests.csproj --no-build - --filter "FullyQualifiedName~GameFrameX.Tests.Topology.Equivalence|FullyQualifiedName~GameFrameX.Tests.Discovery|FullyQualifiedName~GameFrameX.Tests.DataBase.PostgreSqlDbServiceQueryTests" + --filter "FullyQualifiedName~GameFrameX.Tests.Topology.Equivalence|FullyQualifiedName~GameFrameX.Tests.Discovery|FullyQualifiedName~GameFrameX.Tests.DataBase.PostgreSqlDbServiceQueryTests|FullyQualifiedName~GameFrameX.Tests.DataBase.DatabaseConditionalWritePrimitivesTests|FullyQualifiedName~GameFrameX.Tests.DataBase.DatabaseExecuteInTransactionAtomicityTests|FullyQualifiedName~GameFrameX.Tests.DataBase.SqlitePredicatePushdownTests|FullyQualifiedName~GameFrameX.Tests.DataBase.MongoDbServiceQueryTests" --logger GitHubActions diff --git a/.sonarcloud.properties b/.sonarcloud.properties index e819d47d9..c20bb017f 100644 --- a/.sonarcloud.properties +++ b/.sonarcloud.properties @@ -1,4 +1,4 @@ # SonarCloud Automatic Analysis 配置(CI analysis 请用 sonar-project.properties) # 忽略 CI/GitHub workflow 目录,避免 githubactions 规则对 .github 产生 issue -# docs/toc.yml:QQ 群公开入群链接的 authKey 查询参数被 yaml:S6418 误报为硬编码密钥(GFX-1120 裁定误报),该文件为纯导航配置,排除扫描 -sonar.exclusions=**/.github/**,docs/toc.yml +# Configs/:quickstart/compose 演示样例(本地默认凭据连接串,非生产机密),S2068 排除 +sonar.exclusions=**/.github/**,docs/toc.yml,Configs/** diff --git a/CHANGELOG.md b/CHANGELOG.md index 31894a798..79c8544ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,12 @@ * 版本线归一 2.0.0(C459,GFX-1194,GitHub #958):`Version.props` 由 1.7.3 切至 2.0.0.0,全部 27 个可打包项目(运行时基座 15 包 + `GameFrameX.Capability.*` 12 包)统一随 2.0.0 版本线发布。按 D1 裁决为断代升级:**不保留 1.x 兼容层**,1.x 消费方升级须整体切换 * `GameFrameX.Capability.*`(Hosting×3 + Online×9)随 2.0.0 首发,此前从未发布过任何版本;`GameFrameX.NetWork.Message` / `GameFrameX.Core.Config` 等已并入包以 2.0.0 续线 -* Server 运行仓(`GameFrameX.Server`)的 `GameFrameX.*` 包引用钉住 1.13.0 不随本次升级,待框架 2.0 发布后按收敛计划 P5 阶段统一切换 +* 基础设施收敛 P4b(C464,GFX-1200):①新增 `GameFrameX.ServerLink` 薄门面封装包(直连拨号 + 固定重试上限默认 2 + `RoleRouteEnvelopeMessage` 信封转发门面 + 玩家路由解析内置默认),作为服间链路推荐入口;②`GameFrameX.Network.RemoteMessaging` 原位收缩——**移除**多版本协商灰度面(`IProtocolVersionNegotiator`/`DefaultProtocolVersionNegotiator`/`ProtocolVersionAttribute`,保留握手帧最小版本号校验与 HMAC 节点互信),**移除** `RemoteMessagingOptions.EnableUnifiedClient` 与环境键 `RemoteMessaging__EnableUnifiedClient`,`EnableRetry` 默认由 true 改为 false、熔断器与端点健康评估默认降级 PassThrough(`WithRetry`/`WithCircuitBreaker`/`EnableCircuitBreaker` 显式开启,接口保留),最小观测计数(Metrics/Trace 拦截器常开不再绑定韧性开关),Unified 治理面(`MessageGovernancePolicy` 与一致性哈希实例选择器)冻结标注不再演进;③`GameFrameX.StartUp` 移除 `MongoDB.Driver` 直接包引用(Mongo 健康检查经 `GameFrameX.DataBase.Mongo` Provider 程序集反射解析,`MongoDbHealthCheck` 新增连接串构造重载);④数据库三档定档文档化(5 份 README 的三段说明:三档定位 / 无迁移工具 / 双主线维护代价)+ docker-compose 提供 PostgreSQL 档(`--profile postgres`)与默认 Mongo 档并列示例;⑤契约套件双绿设为发布门禁(release.yml 新增 `database-contract-gate` 前置 job,PG+Mongo service container 真跑条件写/事务原子性/可翻译子集契约;PR 侧 topology-equivalence filter 同步扩入) + +### Added + +* `GameFrameX.ServerLink` 薄门面封装包(2.0.0 首发):`ServerLinkBuilder`(内置默认直连 TCP + 固定重试上限 + PassThrough 韧性)、`ServerLinkEnvelopeForwarder`(跨 Role 信封转发门面)、`ServerLinkPlayerRouting`(统一消息发送器组合 + 本地投递槽补装 + 发现层玩家路由解析适配);服务间链路用户文档见 `docs/remote-messaging.md`(含跨服调用准入规则收编) +* Sqlite quickstart 黄金路径四项存量缺陷修复(随 C464 落地,GFX-1200):①示例配置 `Configs/app_config.json` 按三档定档切为零依赖 Sqlite 档(quickstart/demo 默认载体;生产选型改文件两行,另附 `app_config.mongo.json` / `app_config.postgres.json` 双主线样例与 compose 挂载),解除 README 五分钟命令与启动期校验器的 CliFileValueConflict 死锁;②`OnlineCapabilityOptions.Settings`(`JsonElement` 缺省 `Undefined`)新增 `UndefinedSafeJsonElementConverter`(写侧 Undefined→空对象,读侧不变)——文件配置启动时 `AppSetting.ToFormatString` 序列化未配置能力参数节恒抛 `InvalidOperationException` 的问题修复;③`GameEventDispatcher.DispatchGlobal` 无监听告警路径不再因合法的全局分发 ActorId(0,低于最小服务器 Id)在类型反查中抛 `ArgumentOutOfRangeException` 中断启动;④`HttpIsDevelopment` 开关现在真正驱动 Web 宿主环境(此前 `/health`、`/alive` 仅在 ASP.NET Core 环境为 Development 时映射,开关开启仍 404)——示例配置默认开启开发端点,README 注明生产关闭 ## [Unreleased] - PostgreSQL-Only 验证分支(verify/pg-only-no-mongo) diff --git a/Configs/app_config.json b/Configs/app_config.json index 2b5fad123..921ccf61c 100644 --- a/Configs/app_config.json +++ b/Configs/app_config.json @@ -16,13 +16,17 @@ "Online": { "EnableRuntime": true, "EnableAdminApi": true, - "EnableRoles": ["Game"], + "EnableRoles": [ + "Game" + ], "UseGameDbStores": true }, "MinModuleId": 10, "MaxModuleId": 9999, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", - "DataBaseName": "gameframex" + "DataBaseUrl": "Data Source=data/gameframex.db", + "DataBaseName": "gameframex", + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Social", @@ -40,142 +44,174 @@ "MetricsPort": 29490, "MinModuleId": 10000, "MaxModuleId": 19999, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", - "DataBaseName": "gameframex" + "DataBaseUrl": "Data Source=data/gameframex.db", + "DataBaseName": "gameframex", + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Account", "ServerId": 5050, "InnerHost": "0.0.0.0", "InnerPort": 25050, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Login", "ServerId": 5030, "InnerHost": "0.0.0.0", "InnerPort": 25030, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Auth", "ServerId": 5040, "InnerHost": "0.0.0.0", "InnerPort": 25040, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Gateway", "ServerId": 5000, "InnerHost": "0.0.0.0", "InnerPort": 25000, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Chat", "ServerId": 5510, "InnerHost": "0.0.0.0", "InnerPort": 25510, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Mail", "ServerId": 5590, "InnerHost": "0.0.0.0", "InnerPort": 25590, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Team", "ServerId": 5550, "InnerHost": "0.0.0.0", "InnerPort": 25550, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Guild", "ServerId": 5570, "InnerHost": "0.0.0.0", "InnerPort": 25570, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Room", "ServerId": 7010, "InnerHost": "0.0.0.0", "InnerPort": 27010, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Scene", "ServerId": 7020, "InnerHost": "0.0.0.0", "InnerPort": 27020, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "World", "ServerId": 7030, "InnerHost": "0.0.0.0", "InnerPort": 27030, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Battle", "ServerId": 7040, "InnerHost": "0.0.0.0", "InnerPort": 27040, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Trade", "ServerId": 7610, "InnerHost": "0.0.0.0", "InnerPort": 27610, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Auction", "ServerId": 7620, "InnerHost": "0.0.0.0", "InnerPort": 27620, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true }, { "ServerType": "Gm", "ServerId": 8000, "InnerHost": "0.0.0.0", "InnerPort": 28000, - "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseUrl": "Data Source=data/gameframex.db", "DataBaseName": "gameframex", - "HttpPort": 0 + "HttpPort": 0, + "DatabaseProvider": "Sqlite", + "HttpIsDevelopment": true } -] +] \ No newline at end of file diff --git a/Configs/app_config.mongo.json b/Configs/app_config.mongo.json new file mode 100644 index 000000000..e94a96be4 --- /dev/null +++ b/Configs/app_config.mongo.json @@ -0,0 +1,217 @@ +[ + { + "ServerType": "Game", + "ServerId": 1001, + "ServerInstanceId": 1001, + "InnerHost": "0.0.0.0", + "InnerPort": 29100, + "OuterHost": "0.0.0.0", + "OuterPort": 29100, + "HttpPort": 28080, + "WsPort": 29110, + "KcpPort": 29120, + "IsEnableKcp": false, + "OnlineAdminPort": 28090, + "MetricsPort": 29090, + "Online": { + "EnableRuntime": true, + "EnableAdminApi": true, + "EnableRoles": [ + "Game" + ], + "UseGameDbStores": true + }, + "MinModuleId": 10, + "MaxModuleId": 9999, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Social", + "ServerId": 5531, + "ServerInstanceId": 2001, + "InnerHost": "0.0.0.0", + "InnerPort": 29400, + "OuterHost": "0.0.0.0", + "OuterPort": 29400, + "HttpPort": 28081, + "WsPort": 29410, + "KcpPort": 29420, + "IsEnableKcp": false, + "OnlineAdminPort": 28190, + "MetricsPort": 29490, + "MinModuleId": 10000, + "MaxModuleId": 19999, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Account", + "ServerId": 5050, + "InnerHost": "0.0.0.0", + "InnerPort": 25050, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Login", + "ServerId": 5030, + "InnerHost": "0.0.0.0", + "InnerPort": 25030, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Auth", + "ServerId": 5040, + "InnerHost": "0.0.0.0", + "InnerPort": 25040, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Gateway", + "ServerId": 5000, + "InnerHost": "0.0.0.0", + "InnerPort": 25000, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Chat", + "ServerId": 5510, + "InnerHost": "0.0.0.0", + "InnerPort": 25510, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Mail", + "ServerId": 5590, + "InnerHost": "0.0.0.0", + "InnerPort": 25590, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Team", + "ServerId": 5550, + "InnerHost": "0.0.0.0", + "InnerPort": 25550, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Guild", + "ServerId": 5570, + "InnerHost": "0.0.0.0", + "InnerPort": 25570, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Room", + "ServerId": 7010, + "InnerHost": "0.0.0.0", + "InnerPort": 27010, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Scene", + "ServerId": 7020, + "InnerHost": "0.0.0.0", + "InnerPort": 27020, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "World", + "ServerId": 7030, + "InnerHost": "0.0.0.0", + "InnerPort": 27030, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Battle", + "ServerId": 7040, + "InnerHost": "0.0.0.0", + "InnerPort": 27040, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Trade", + "ServerId": 7610, + "InnerHost": "0.0.0.0", + "InnerPort": 27610, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Auction", + "ServerId": 7620, + "InnerHost": "0.0.0.0", + "InnerPort": 27620, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Gm", + "ServerId": 8000, + "InnerHost": "0.0.0.0", + "InnerPort": 28000, + "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + } +] \ No newline at end of file diff --git a/Configs/app_config.postgres.json b/Configs/app_config.postgres.json new file mode 100644 index 000000000..18522c5b0 --- /dev/null +++ b/Configs/app_config.postgres.json @@ -0,0 +1,217 @@ +[ + { + "ServerType": "Game", + "ServerId": 1001, + "ServerInstanceId": 1001, + "InnerHost": "0.0.0.0", + "InnerPort": 29100, + "OuterHost": "0.0.0.0", + "OuterPort": 29100, + "HttpPort": 28080, + "WsPort": 29110, + "KcpPort": 29120, + "IsEnableKcp": false, + "OnlineAdminPort": 28090, + "MetricsPort": 29090, + "Online": { + "EnableRuntime": true, + "EnableAdminApi": true, + "EnableRoles": [ + "Game" + ], + "UseGameDbStores": true + }, + "MinModuleId": 10, + "MaxModuleId": 9999, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Social", + "ServerId": 5531, + "ServerInstanceId": 2001, + "InnerHost": "0.0.0.0", + "InnerPort": 29400, + "OuterHost": "0.0.0.0", + "OuterPort": 29400, + "HttpPort": 28081, + "WsPort": 29410, + "KcpPort": 29420, + "IsEnableKcp": false, + "OnlineAdminPort": 28190, + "MetricsPort": 29490, + "MinModuleId": 10000, + "MaxModuleId": 19999, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Account", + "ServerId": 5050, + "InnerHost": "0.0.0.0", + "InnerPort": 25050, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Login", + "ServerId": 5030, + "InnerHost": "0.0.0.0", + "InnerPort": 25030, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Auth", + "ServerId": 5040, + "InnerHost": "0.0.0.0", + "InnerPort": 25040, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Gateway", + "ServerId": 5000, + "InnerHost": "0.0.0.0", + "InnerPort": 25000, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Chat", + "ServerId": 5510, + "InnerHost": "0.0.0.0", + "InnerPort": 25510, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Mail", + "ServerId": 5590, + "InnerHost": "0.0.0.0", + "InnerPort": 25590, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Team", + "ServerId": 5550, + "InnerHost": "0.0.0.0", + "InnerPort": 25550, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Guild", + "ServerId": 5570, + "InnerHost": "0.0.0.0", + "InnerPort": 25570, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Room", + "ServerId": 7010, + "InnerHost": "0.0.0.0", + "InnerPort": 27010, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Scene", + "ServerId": 7020, + "InnerHost": "0.0.0.0", + "InnerPort": 27020, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "World", + "ServerId": 7030, + "InnerHost": "0.0.0.0", + "InnerPort": 27030, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Battle", + "ServerId": 7040, + "InnerHost": "0.0.0.0", + "InnerPort": 27040, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Trade", + "ServerId": 7610, + "InnerHost": "0.0.0.0", + "InnerPort": 27610, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Auction", + "ServerId": 7620, + "InnerHost": "0.0.0.0", + "InnerPort": 27620, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Gm", + "ServerId": 8000, + "InnerHost": "0.0.0.0", + "InnerPort": 28000, + "DataBaseUrl": "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + } +] \ No newline at end of file diff --git a/Configs/compose/app_config.mongo.json b/Configs/compose/app_config.mongo.json new file mode 100644 index 000000000..30a075f0f --- /dev/null +++ b/Configs/compose/app_config.mongo.json @@ -0,0 +1,217 @@ +[ + { + "ServerType": "Game", + "ServerId": 1001, + "ServerInstanceId": 1001, + "InnerHost": "0.0.0.0", + "InnerPort": 29100, + "OuterHost": "0.0.0.0", + "OuterPort": 29100, + "HttpPort": 28080, + "WsPort": 29110, + "KcpPort": 29120, + "IsEnableKcp": false, + "OnlineAdminPort": 28090, + "MetricsPort": 29090, + "Online": { + "EnableRuntime": true, + "EnableAdminApi": true, + "EnableRoles": [ + "Game" + ], + "UseGameDbStores": true + }, + "MinModuleId": 10, + "MaxModuleId": 9999, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Social", + "ServerId": 5531, + "ServerInstanceId": 2001, + "InnerHost": "0.0.0.0", + "InnerPort": 29400, + "OuterHost": "0.0.0.0", + "OuterPort": 29400, + "HttpPort": 28081, + "WsPort": 29410, + "KcpPort": 29420, + "IsEnableKcp": false, + "OnlineAdminPort": 28190, + "MetricsPort": 29490, + "MinModuleId": 10000, + "MaxModuleId": 19999, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Account", + "ServerId": 5050, + "InnerHost": "0.0.0.0", + "InnerPort": 25050, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Login", + "ServerId": 5030, + "InnerHost": "0.0.0.0", + "InnerPort": 25030, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Auth", + "ServerId": 5040, + "InnerHost": "0.0.0.0", + "InnerPort": 25040, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Gateway", + "ServerId": 5000, + "InnerHost": "0.0.0.0", + "InnerPort": 25000, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Chat", + "ServerId": 5510, + "InnerHost": "0.0.0.0", + "InnerPort": 25510, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Mail", + "ServerId": 5590, + "InnerHost": "0.0.0.0", + "InnerPort": 25590, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Team", + "ServerId": 5550, + "InnerHost": "0.0.0.0", + "InnerPort": 25550, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Guild", + "ServerId": 5570, + "InnerHost": "0.0.0.0", + "InnerPort": 25570, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Room", + "ServerId": 7010, + "InnerHost": "0.0.0.0", + "InnerPort": 27010, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Scene", + "ServerId": 7020, + "InnerHost": "0.0.0.0", + "InnerPort": 27020, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "World", + "ServerId": 7030, + "InnerHost": "0.0.0.0", + "InnerPort": 27030, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Battle", + "ServerId": 7040, + "InnerHost": "0.0.0.0", + "InnerPort": 27040, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Trade", + "ServerId": 7610, + "InnerHost": "0.0.0.0", + "InnerPort": 27610, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Auction", + "ServerId": 7620, + "InnerHost": "0.0.0.0", + "InnerPort": 27620, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + }, + { + "ServerType": "Gm", + "ServerId": 8000, + "InnerHost": "0.0.0.0", + "InnerPort": 28000, + "DataBaseUrl": "mongodb://mongo:27017/?authSource=admin", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "Mongo", + "HttpIsDevelopment": true + } +] \ No newline at end of file diff --git a/Configs/compose/app_config.postgres.json b/Configs/compose/app_config.postgres.json new file mode 100644 index 000000000..c861fbb45 --- /dev/null +++ b/Configs/compose/app_config.postgres.json @@ -0,0 +1,217 @@ +[ + { + "ServerType": "Game", + "ServerId": 1001, + "ServerInstanceId": 1001, + "InnerHost": "0.0.0.0", + "InnerPort": 29100, + "OuterHost": "0.0.0.0", + "OuterPort": 29100, + "HttpPort": 28080, + "WsPort": 29110, + "KcpPort": 29120, + "IsEnableKcp": false, + "OnlineAdminPort": 28090, + "MetricsPort": 29090, + "Online": { + "EnableRuntime": true, + "EnableAdminApi": true, + "EnableRoles": [ + "Game" + ], + "UseGameDbStores": true + }, + "MinModuleId": 10, + "MaxModuleId": 9999, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Social", + "ServerId": 5531, + "ServerInstanceId": 2001, + "InnerHost": "0.0.0.0", + "InnerPort": 29400, + "OuterHost": "0.0.0.0", + "OuterPort": 29400, + "HttpPort": 28081, + "WsPort": 29410, + "KcpPort": 29420, + "IsEnableKcp": false, + "OnlineAdminPort": 28190, + "MetricsPort": 29490, + "MinModuleId": 10000, + "MaxModuleId": 19999, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Account", + "ServerId": 5050, + "InnerHost": "0.0.0.0", + "InnerPort": 25050, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Login", + "ServerId": 5030, + "InnerHost": "0.0.0.0", + "InnerPort": 25030, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Auth", + "ServerId": 5040, + "InnerHost": "0.0.0.0", + "InnerPort": 25040, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Gateway", + "ServerId": 5000, + "InnerHost": "0.0.0.0", + "InnerPort": 25000, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Chat", + "ServerId": 5510, + "InnerHost": "0.0.0.0", + "InnerPort": 25510, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Mail", + "ServerId": 5590, + "InnerHost": "0.0.0.0", + "InnerPort": 25590, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Team", + "ServerId": 5550, + "InnerHost": "0.0.0.0", + "InnerPort": 25550, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Guild", + "ServerId": 5570, + "InnerHost": "0.0.0.0", + "InnerPort": 25570, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Room", + "ServerId": 7010, + "InnerHost": "0.0.0.0", + "InnerPort": 27010, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Scene", + "ServerId": 7020, + "InnerHost": "0.0.0.0", + "InnerPort": 27020, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "World", + "ServerId": 7030, + "InnerHost": "0.0.0.0", + "InnerPort": 27030, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Battle", + "ServerId": 7040, + "InnerHost": "0.0.0.0", + "InnerPort": 27040, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Trade", + "ServerId": 7610, + "InnerHost": "0.0.0.0", + "InnerPort": 27610, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Auction", + "ServerId": 7620, + "InnerHost": "0.0.0.0", + "InnerPort": 27620, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + }, + { + "ServerType": "Gm", + "ServerId": 8000, + "InnerHost": "0.0.0.0", + "InnerPort": 28000, + "DataBaseUrl": "Host=postgres;Port=5432;Username=postgres;Password=postgres;Database=gameframex", + "DataBaseName": "gameframex", + "HttpPort": 0, + "DatabaseProvider": "PostgreSql", + "HttpIsDevelopment": true + } +] \ No newline at end of file diff --git a/GameFrameX.Core/Events/GameEventDispatcher.cs b/GameFrameX.Core/Events/GameEventDispatcher.cs index 790eb7996..bdd0c1eb4 100644 --- a/GameFrameX.Core/Events/GameEventDispatcher.cs +++ b/GameFrameX.Core/Events/GameEventDispatcher.cs @@ -199,7 +199,7 @@ private void DispatchGlobal(long actorId, GameEventArgs eventArgs) var listeners = HotfixManager.Resolver.FindListeners(eventArgs.GetType()); if (listeners.IsNullOrEmpty()) { - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchNoListeners, actorId, ActorIdGenerator.GetActorType(actorId), eventArgs.GetType().Name)); + LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchNoListeners, actorId, DescribeActorType(actorId), eventArgs.GetType().Name)); return; } @@ -241,6 +241,31 @@ private void DispatchGlobal(long actorId, GameEventArgs eventArgs) } } + /// + /// 描述目标 Actor 类型(无监听告警格式化用)。全局事件分发以 0 作为目标 ActorId + ///(低于最小服务器 Id,不参与 Actor 类型编码),类型反查失败时返回固定描述而不是抛出—— + /// 告警路径不得因合法的全局分发 Id 中断启动/分发链路。 + /// + /// + /// Describes the target actor type (formatting for the no-listener warning). Global event + /// dispatch uses 0 as the target actor id (below the minimum server id, outside the actor-type + /// encoding); when the type lookup fails a fixed description is returned instead of throwing — + /// the warning path must not break the startup/dispatch chain for a legal global dispatch id. + /// + /// 目标 ActorId / The target actor id + /// Actor 类型数值;无法编码时为 "global" / The actor type value, or "global" when not encodable + private static object DescribeActorType(long actorId) + { + try + { + return ActorIdGenerator.GetActorType(actorId); + } + catch (Exception) + { + return "global"; + } + } + /// /// 在 Actor 上下文内执行单个监听器:取出该监听器代理类型的组件代理并调用其事件处理方法,异常就地记录。 /// diff --git a/GameFrameX.DataBase.Mongo/HealthChecks/MongoDbHealthCheck.cs b/GameFrameX.DataBase.Mongo/HealthChecks/MongoDbHealthCheck.cs index d810a735b..5f8ae62b6 100644 --- a/GameFrameX.DataBase.Mongo/HealthChecks/MongoDbHealthCheck.cs +++ b/GameFrameX.DataBase.Mongo/HealthChecks/MongoDbHealthCheck.cs @@ -41,10 +41,56 @@ namespace GameFrameX.DataBase.Mongo.HealthChecks; /// public sealed class MongoDbHealthCheck : IHealthCheck { + /// + /// 共享健康检查客户端的创建锁。 + /// + /// + /// The creation lock for the shared health check client. + /// + private static readonly object SharedClientLock = new(); + + /// + /// 进程内共享的健康检查客户端(按连接串复用,避免每次探测重建连接池)。 + /// + /// + /// The process-wide shared health check client (reused per connection string so each probe does not rebuild a connection pool). + /// + private static IMongoClient _sharedHealthClient; + + /// + /// 共享客户端当前对应的连接串。 + /// + /// + /// The connection string the shared client currently belongs to. + /// + private static string _sharedHealthClientConnectionString; + private const int ConsecutiveFailureThreshold = 5; private readonly IMongoClient _mongoClient; private int _consecutiveFailures; + /// + /// 按连接串初始化 MongoDbHealthCheck(客户端在进程内按连接串共享缓存)。 + /// 供宿主在未直接引用 MongoDB.Driver 时经 Provider 程序集反射装配健康检查。 + /// + /// + /// Initializes a new instance of MongoDbHealthCheck from a connection string (the underlying + /// client is cached and shared per connection string within the process). Hosts that do not + /// reference MongoDB.Driver directly resolve this constructor through the provider assembly. + /// + /// MongoDB 连接串 / The MongoDB connection string + /// 当 connectionString 为空白时抛出 / Thrown when connectionString is blank + public MongoDbHealthCheck(string connectionString) + { + if (string.IsNullOrWhiteSpace(connectionString)) + { + throw new ArgumentException("The MongoDB connection string must not be blank.", nameof(connectionString)); + } + + _mongoClient = GetOrCreateSharedClient(connectionString); + } + + /// /// 初始化 MongoDbHealthCheck 的新实例。 /// @@ -57,6 +103,34 @@ public MongoDbHealthCheck(IMongoClient mongoClient) _mongoClient = mongoClient; } + /// + /// 获取或创建进程内共享的健康检查客户端(双检锁;连接串变化时重建)。 + /// + /// + /// Gets or creates the process-wide shared health check client (double-checked lock; rebuilt when the connection string changes). + /// + /// MongoDB 连接串 / The MongoDB connection string + /// 共享客户端实例 / The shared client instance + private static IMongoClient GetOrCreateSharedClient(string connectionString) + { + if (_sharedHealthClient != null && string.Equals(_sharedHealthClientConnectionString, connectionString, StringComparison.Ordinal)) + { + return _sharedHealthClient; + } + + lock (SharedClientLock) + { + if (_sharedHealthClient != null && string.Equals(_sharedHealthClientConnectionString, connectionString, StringComparison.Ordinal)) + { + return _sharedHealthClient; + } + + _sharedHealthClient = new MongoClient(connectionString); + _sharedHealthClientConnectionString = connectionString; + return _sharedHealthClient; + } + } + /// /// 执行健康检查。 /// diff --git a/GameFrameX.Localization/Keys.RemoteMessaging.cs b/GameFrameX.Localization/Keys.RemoteMessaging.cs index 80b94e560..f2ca52104 100644 --- a/GameFrameX.Localization/Keys.RemoteMessaging.cs +++ b/GameFrameX.Localization/Keys.RemoteMessaging.cs @@ -276,16 +276,6 @@ public static class ClientModule /// public const string SendOneWayHealthScoreLow = "RemoteMessaging.Client.SendOneWayHealthScoreLow"; - /// - /// SendOneWayAsync: 协议版本不兼容, MessageType: {0} - /// - /// - /// 键名: RemoteMessaging.Client.SendOneWayProtocolVersionIncompatible - /// 用途: 单向发送时协议版本不兼容而放弃发送的警告日志 - /// 参数: {0} - 请求消息类型名 - /// - public const string SendOneWayProtocolVersionIncompatible = "RemoteMessaging.Client.SendOneWayProtocolVersionIncompatible"; - /// /// 拦截器 OnExceptionAsync 失败 /// diff --git a/GameFrameX.Localization/Localization/Messages/Resources.resx b/GameFrameX.Localization/Localization/Messages/Resources.resx index b438ae925..32d0ec6d7 100644 --- a/GameFrameX.Localization/Localization/Messages/Resources.resx +++ b/GameFrameX.Localization/Localization/Messages/Resources.resx @@ -2152,9 +2152,6 @@ SendOneWayAsync: service health score too low, Service: {0}, Score: {1} - - SendOneWayAsync: protocol version incompatible, MessageType: {0} - FaultInjection: simulated connection drop, Service: {0} diff --git a/GameFrameX.Localization/Localization/Messages/Resources.zh-CN.resx b/GameFrameX.Localization/Localization/Messages/Resources.zh-CN.resx index a5d1e0333..72a371536 100644 --- a/GameFrameX.Localization/Localization/Messages/Resources.zh-CN.resx +++ b/GameFrameX.Localization/Localization/Messages/Resources.zh-CN.resx @@ -2154,9 +2154,6 @@ SendOneWayAsync: 服务健康评分过低, Service: {0}, Score: {1} - - SendOneWayAsync: 协议版本不兼容, MessageType: {0} - FaultInjection: 模拟连接断开, Service: {0} diff --git a/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessageClient.cs b/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessageClient.cs index 085c2dbc9..006498f88 100644 --- a/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessageClient.cs +++ b/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessageClient.cs @@ -46,7 +46,6 @@ internal sealed class RemoteMessageClient : IRemoteMessageClient, IDisposable private readonly IEndpointHealthEvaluator _healthEvaluator; private readonly IRemoteCallInterceptor[] _interceptors; private readonly IMessageCodec _messageCodec; - private readonly IProtocolVersionNegotiator _protocolVersionNegotiator; private readonly IRequestResponseMatcher _requestResponseMatcher; private readonly IRetryPolicy _retryPolicy; private readonly ITransportProtocolAdapter _transportProtocolAdapter; @@ -62,7 +61,7 @@ internal sealed class RemoteMessageClient : IRemoteMessageClient, IDisposable /// 传输协议适配器 / Transport protocol adapter /// 消息编解码器 / Message codec /// 请求-响应匹配器 / Request-response matcher - /// 协议版本协商器 / Protocol version negotiator + /// 远程调用拦截器数组 / Array of remote call interceptors /// 重试策略(可为 null) / Retry policy (can be null) /// 熔断器 / Circuit breaker @@ -72,7 +71,7 @@ public RemoteMessageClient( ITransportProtocolAdapter transportProtocolAdapter, IMessageCodec messageCodec, IRequestResponseMatcher requestResponseMatcher, - IProtocolVersionNegotiator protocolVersionNegotiator, + IRemoteCallInterceptor[] interceptors, IRetryPolicy retryPolicy, ICircuitBreaker circuitBreaker, @@ -82,7 +81,7 @@ public RemoteMessageClient( _transportProtocolAdapter = transportProtocolAdapter; _messageCodec = messageCodec; _requestResponseMatcher = requestResponseMatcher ?? throw new ArgumentNullException(nameof(requestResponseMatcher)); - _protocolVersionNegotiator = protocolVersionNegotiator; + _interceptors = interceptors ?? Array.Empty(); _retryPolicy = retryPolicy; _circuitBreaker = circuitBreaker; @@ -412,16 +411,6 @@ private RemoteCallResult CheckPreconditions(RemoteCallCont // 连接级协议版本握手(每连接单飞一次):拒绝抛 ProtocolVersionMismatchException,混布超时回落旧版本 await EnsureHandshakeAsync(connection, targetKey); - if (_protocolVersionNegotiator != null && !_protocolVersionNegotiator.IsMessageCompatible(requestMessage.GetType(), connection.NegotiatedRemoteVersion)) - { - return ( - RemoteCallResult.Fail( - RemoteStatusCode.ProtocolVersionIncompatible, - $"Protocol version incompatible for message type: {requestMessage.GetType().Name}", - stopwatch.ElapsedMilliseconds, - context.TraceId), - false); - } var requestUniqueId = _requestResponseMatcher.RegisterPendingRequest(context.TimeoutMs); PrepareRequestMessage(requestMessage, requestUniqueId); @@ -651,8 +640,7 @@ private async Task PerformHandshakeAsync(ConnectionContext connection, string se if (response is GameFrameX.Network.RemoteMessaging.Versioning.RespProtocolVersionNegotiation handshakeResponse) { var remote = new GameFrameX.Network.RemoteMessaging.Versioning.ProtocolVersion(handshakeResponse.Major, handshakeResponse.Minor); - if (!handshakeResponse.Accepted || - (_protocolVersionNegotiator != null && !_protocolVersionNegotiator.IsConnectionCompatible(local, remote))) + if (!handshakeResponse.Accepted || remote.Major != local.Major) { // Localization: RemoteMessaging.Versioning.HandshakeRejected - 协议版本握手被拒绝:本端 {0},远端 {1}。连接已关闭(跨 major 混布禁止)。 throw new GameFrameX.Network.RemoteMessaging.Versioning.ProtocolVersionMismatchException( @@ -661,7 +649,6 @@ private async Task PerformHandshakeAsync(ConnectionContext connection, string se remote); } - connection.SetNegotiatedRemoteVersion(remote); return; } @@ -697,7 +684,6 @@ private async Task PerformHandshakeAsync(ConnectionContext connection, string se serviceName, _handshakeTimeoutMs, GameFrameX.Network.RemoteMessaging.Versioning.RemoteMessagingProtocolVersion.Legacy)); - connection.SetNegotiatedRemoteVersion(GameFrameX.Network.RemoteMessaging.Versioning.RemoteMessagingProtocolVersion.Legacy); } finally { @@ -780,28 +766,6 @@ public ConnectionContext(Stream stream, IRequestResponseMatcher matcher) } public Stream Stream { get; } - /// - /// 获取握手协商出的远端协议版本(握手完成前为 占位; - /// 保证消息级检查发生在握手之后)。 - /// - /// - /// Gets the remote protocol version negotiated by the handshake (the - /// - /// placeholder before the handshake completes; guarantees the - /// message-level check runs after the handshake). - /// - public GameFrameX.Network.RemoteMessaging.Versioning.ProtocolVersion NegotiatedRemoteVersion { get; private set; } = GameFrameX.Network.RemoteMessaging.Versioning.RemoteMessagingProtocolVersion.Legacy; - - /// - /// 记录握手协商出的远端协议版本(仅握手流程调用)。 - /// - /// - /// Records the remote protocol version negotiated by the handshake (called by the handshake flow only). - /// - public void SetNegotiatedRemoteVersion(GameFrameX.Network.RemoteMessaging.Versioning.ProtocolVersion version) - { - NegotiatedRemoteVersion = version; - } /// /// 获取或启动本连接的单飞握手任务:首个调用者执行握手,并发调用者等待同一任务结果。 @@ -1005,12 +969,6 @@ public async Task SendOneWayAsync(RemoteCallContext context, MessageObject reque return; } - if (_protocolVersionNegotiator != null && !_protocolVersionNegotiator.IsMessageCompatible(requestMessage.GetType(), connection.NegotiatedRemoteVersion)) - { - // Localization: RemoteMessaging.Client.SendOneWayProtocolVersionIncompatible - SendOneWayAsync: 协议版本不兼容, MessageType: {0} - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.RemoteMessaging.ClientModule.SendOneWayProtocolVersionIncompatible, requestMessage.GetType().Name)); - return; - } var requestUniqueId = _requestResponseMatcher.RegisterPendingRequest(context.TimeoutMs); PrepareRequestMessage(requestMessage, requestUniqueId); diff --git a/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessagingBuilder.cs b/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessagingBuilder.cs index dd2b82b11..7e0ee13ca 100644 --- a/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessagingBuilder.cs +++ b/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessagingBuilder.cs @@ -78,13 +78,14 @@ public RemoteMessagingBuilder WithTimeoutMs(int timeoutMs) } /// - /// 设置重试策略。 + /// 设置重试策略(固定重试上限)。默认不重试(PassThrough 口径);调用本方法显式开启。 /// /// - /// Configures the retry policy. + /// Configures the retry policy (a fixed retry limit). Retries are disabled by default (the + /// pass-through posture); calling this method opts in explicitly. /// /// 最大重试次数 / The maximum number of retry attempts - /// 基础延迟毫秒 / The base delay in milliseconds between retries + /// 基础延迟毫秒数 / The base delay in milliseconds between retries /// 构建器实例 / The builder instance public RemoteMessagingBuilder WithRetry(int maxRetryCount, int baseDelayMs = 200) { @@ -95,16 +96,18 @@ public RemoteMessagingBuilder WithRetry(int maxRetryCount, int baseDelayMs = 200 } /// - /// 设置熔断器参数。 + /// 设置熔断器参数并显式启用真实现(默认 PassThrough 直通,不熔断、不做端点健康评估)。 /// /// - /// Configures the circuit breaker parameters. + /// Configures the circuit breaker parameters and opts in to the real implementation (the default + /// is the pass-through posture: no circuit breaking and no endpoint health evaluation). /// /// 连续失败阈值 / The consecutive failure threshold that triggers the circuit breaker /// 熔断开启持续时间毫秒 / The duration in milliseconds the circuit breaker stays open /// 构建器实例 / The builder instance public RemoteMessagingBuilder WithCircuitBreaker(int failureThreshold = 5, int openDurationMs = 30000) { + _options.EnableCircuitBreaker = true; _options.CircuitBreakerFailureThreshold = failureThreshold; _options.CircuitBreakerOpenDurationMs = openDurationMs; return this; @@ -320,27 +323,28 @@ public IRemoteMessageClient Build() _options.MaxPacketSize, _options.MaxDecompressedSize); var requestResponseMatcher = new RequestResponseMatcher(); - var protocolVersionNegotiator = new DefaultProtocolVersionNegotiator(); + // 最小观测常开:调用计数/时延/错误计数(Metrics)+ 标准 OTel span(Trace,无监听器时零成本)。 + // 详细观测面板归运营台,本包只保留最小计数。 + var metrics = new DiagnosticsRemoteCallMetrics(); var interceptors = new List { new LoggingRemoteCallInterceptor(), + new MetricsRemoteCallInterceptor(metrics), + new TraceRemoteCallInterceptor(), }; + if (_options.EnableFaultInjection) + { + interceptors.Add(new FaultInjectionRemoteCallInterceptor()); + } + + // 韧性默认 PassThrough(不熔断、不做端点健康评估);显式 WithCircuitBreaker 才装配真实现(自托管进阶场景) ICircuitBreaker circuitBreaker; IEndpointHealthEvaluator healthEvaluator; - if (_options.EnableUnifiedClient) + if (_options.EnableCircuitBreaker) { - var metrics = new DiagnosticsRemoteCallMetrics(); - interceptors.Add(new MetricsRemoteCallInterceptor(metrics)); - interceptors.Add(new TraceRemoteCallInterceptor()); - - if (_options.EnableFaultInjection) - { - interceptors.Add(new FaultInjectionRemoteCallInterceptor()); - } - circuitBreaker = new DefaultCircuitBreaker( _options.CircuitBreakerFailureThreshold, _options.CircuitBreakerOpenDurationMs); @@ -352,7 +356,8 @@ public IRemoteMessageClient Build() healthEvaluator = new PassThroughEndpointHealthEvaluator(); } - var retryPolicy = _options.EnableUnifiedClient && _options.EnableRetry + // 重试默认关闭(PassThrough 口径);WithRetry 显式开启并携带固定重试上限 + var retryPolicy = _options.EnableRetry ? new DefaultRetryPolicy(_options.MaxRetryCount, _options.RetryBaseDelayMs) : null; @@ -360,7 +365,6 @@ public IRemoteMessageClient Build() transportProtocolAdapter, messageCodec, requestResponseMatcher, - protocolVersionNegotiator, interceptors.ToArray(), retryPolicy, circuitBreaker, diff --git a/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessagingOptions.cs b/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessagingOptions.cs index f42c5bca3..a05f679fa 100644 --- a/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessagingOptions.cs +++ b/GameFrameX.Network.RemoteMessaging/Composition/RemoteMessagingOptions.cs @@ -50,22 +50,29 @@ public sealed class RemoteMessagingOptions private const string EnvPrefix = "RemoteMessaging__"; /// - /// 是否启用统一客户端(默认 true)。设为 false 可回退到旧实现。 + /// 是否启用熔断器(默认 false,PassThrough 直通:不熔断、不做端点健康评估)。 + /// 显式开启后装配真实现(DefaultCircuitBreaker + DefaultEndpointHealthEvaluator),属自托管进阶配置。 /// /// - /// Whether the unified client is enabled (default true). Set to false to fall back to the legacy implementation. + /// Whether the circuit breaker is enabled (default false, the pass-through posture: no circuit + /// breaking and no endpoint health evaluation). Opting in assembles the real implementations + /// (DefaultCircuitBreaker + DefaultEndpointHealthEvaluator) for advanced self-hosted setups. /// - /// 是否启用统一客户端 / Whether the unified client is enabled - public bool EnableUnifiedClient { get; set; } = true; + /// 是否启用熔断器 / Whether the circuit breaker is enabled + public bool EnableCircuitBreaker { get; set; } /// - /// 是否启用重试(默认 true)。 + /// 是否启用重试(默认 false,PassThrough 口径)。重试经 WithRetry 或环境变量显式开启, + /// 携带固定重试上限()。 /// /// - /// Whether retry is enabled (default true). + /// Whether retry is enabled (default false, the pass-through posture). Retries are enabled + /// explicitly via WithRetry or the environment variable, carrying a fixed retry limit + /// (). /// /// 是否启用重试 / Whether retry is enabled - public bool EnableRetry { get; set; } = true; + public bool EnableRetry { get; set; } + /// /// 默认超时毫秒数(默认 5000)。 @@ -209,8 +216,8 @@ public static RemoteMessagingOptions LoadFromEnvironment() { var options = new RemoteMessagingOptions { - EnableUnifiedClient = GetEnvBool("EnableUnifiedClient", true), - EnableRetry = GetEnvBool("EnableRetry", true), + EnableCircuitBreaker = GetEnvBool("EnableCircuitBreaker", false), + EnableRetry = GetEnvBool("EnableRetry", false), DefaultTimeoutMs = GetEnvInt("DefaultTimeoutMs", 5000), MaxRetryCount = GetEnvInt("MaxRetryCount", 2), RetryBaseDelayMs = GetEnvInt("RetryBaseDelayMs", 200), diff --git a/GameFrameX.Network.RemoteMessaging/Guides/CrossServiceCallRules.cs b/GameFrameX.Network.RemoteMessaging/Guides/CrossServiceCallRules.cs deleted file mode 100644 index cef59f4a3..000000000 --- a/GameFrameX.Network.RemoteMessaging/Guides/CrossServiceCallRules.cs +++ /dev/null @@ -1,168 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the People's Republic of China and relevant international regulations. -// 使用本项目须严格遵守相应法律法规及开源许可证之规定。 -// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. -// 本项目采用 Apache License 2.0 单协议分发, -// This project is licensed solely under the Apache License 2.0, -// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 -// please refer to the LICENSE file in the root directory of the source code for the full license text. -// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 -// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, -// 侵犯他人合法权益等法律法规所禁止的行为! -// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! -// 因基于本项目二次开发所产生的一切法律纠纷与责任, -// Any legal disputes and liabilities arising from secondary development based on this project -// 本项目组织与贡献者概不承担。 -// shall be borne solely by the developer; the project organization and contributors assume no responsibility. -// GitHub 仓库:https://github.com/GameFrameX -// GitHub Repository: https://github.com/GameFrameX -// Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX -// CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX -// 官方文档:https://gameframex.doc.alianblank.com/ -// Official Documentation: https://gameframex.doc.alianblank.com/ -// ========================================================================================== - -// ========================================================================================== -// 跨服务调用开发指南 -// ========================================================================================== -// -// 本文档定义了新增跨服务调用的标准模板和代码准入规则。 -// 所有新增跨服务调用必须遵循以下规范。 -// -// ## 准入规则 -// -// 1. 【强制】所有跨服务调用必须通过 IRemoteMessageClient 发起,禁止在 ComponentAgent 中直接使用 TcpClient/NetworkStream。 -// 2. 【强制】非幂等操作(写操作)必须设置 AllowRetry = false。 -// 3. 【强制】幂等操作(读操作/查询)可设置 AllowRetry = true,但最大重试不超过 2 次。 -// 4. 【推荐】使用 CallWithResultAsync 替代 CallAsync,获取结构化结果和状态码。 -// 5. 【推荐】使用 RemoteMessagingBuilder 构建客户端,而非直接实例化。 -// 6. 【推荐】通过 MessageObjectPoolHelper.Get/Return 管理请求对象生命周期。 -// -// ## 标准模板 -// -// ### 1. 幂等查询调用(允许重试) -// -// ```csharp -// public async Task OnQueryData(INetworkChannel networkChannel, ReqQuery request, RespQuery response) -// { -// var req = MessageObjectPoolHelper.Get(); -// req.Param = request.Param; -// try -// { -// var context = new RemoteCallContext -// { -// ServiceName = GlobalConst.TargetServiceName, -// TimeoutMs = RpcTimeoutMilliseconds, -// AllowRetry = true, // 幂等查询允许重试 -// }; -// -// var remoteClient = new RemoteMessagingBuilder() -// .LoadFromEnvironment() -// .WithRouteTable(GameFrameX.Discovery.ActiveDiscoveryRuntime.RouteTableProvider) -// .Build(); -// var result = await remoteClient.CallWithResultAsync(context, req); -// -// if (result.IsSuccess && result.Response != null) -// { -// response.Data = result.Response.Data; -// return; -// } -// -// response.Data = null; -// response.ErrorCode = MapToBusinessErrorCode(result.StatusCode); -// LogHelper.Error("调用失败, StatusCode: {statusCode}, TraceId: {traceId}", -// result.StatusCode, result.TraceId); -// } -// catch (Exception exception) -// { -// response.ErrorCode = -99; -// LogHelper.Error(exception, "调用异常"); -// } -// finally -// { -// MessageObjectPoolHelper.Return(req); -// } -// } -// ``` -// -// ### 2. 非幂等写操作(禁止重试) -// -// ```csharp -// public async Task OnWriteData(INetworkChannel networkChannel, ReqWrite request, RespWrite response) -// { -// var req = MessageObjectPoolHelper.Get(); -// req.Param = request.Param; -// try -// { -// var context = new RemoteCallContext -// { -// ServiceName = GlobalConst.TargetServiceName, -// TimeoutMs = RpcTimeoutMilliseconds, -// AllowRetry = false, // 非幂等操作禁止重试 -// }; -// -// var remoteClient = new RemoteMessagingBuilder() -// .LoadFromEnvironment() -// .WithRouteTable(GameFrameX.Discovery.ActiveDiscoveryRuntime.RouteTableProvider) -// .Build(); -// var result = await remoteClient.CallWithResultAsync(context, req); -// -// if (result.IsSuccess && result.Response != null) -// { -// response.Success = result.Response.Success; -// return; -// } -// -// response.Success = false; -// LogHelper.Error("调用失败, StatusCode: {statusCode}, TraceId: {traceId}", -// result.StatusCode, result.TraceId); -// } -// catch (Exception exception) -// { -// response.Success = false; -// LogHelper.Error(exception, "调用异常"); -// } -// finally -// { -// MessageObjectPoolHelper.Return(req); -// } -// } -// ``` -// -// ## 错误码映射参考 -// -// | RemoteStatusCode | 业务错误码 | 说明 | -// |---|---|---| -// | Success | 0 | 成功 | -// | Timeout | -1 | 超时 | -// | ConnectionFailed | -2 | 连接失败 | -// | EndpointNotFound | -3 | 服务发现失败 | -// | Cancelled | -4 | 取消 | -// | RetryExhausted | -5 | 重试耗尽 | -// | ConnectionClosed | -6 | 连接关闭 | -// | UnexpectedResponse | -7 | 响应异常 | -// | CircuitOpen | -10 | 熔断开启 | -// | ServiceUnavailable | -11 | 服务不可用 | -// | UnknownError | -99 | 未知错误 | - -namespace GameFrameX.Network.RemoteMessaging.Guides; - -/// -/// 跨服务调用代码准入规则标记。在 Code Review 时检查此规则的遵守情况。 -/// -/// -/// Cross-service call code admission rule marker. Checked during code review for compliance. -/// -internal static class CrossServiceCallRules -{ - // 本文件作为代码规范的声明点,实际规则见上方注释。 - // Code Review 检查清单: - // 1. 搜索 TcpClient/NetworkStream 的使用 → 应为 0 处(除 RemoteMessaging 内部) - // 2. 搜索 CallAsync 的调用 → 应全部通过 IRemoteMessageClient 接口 - // 3. 搜索 AllowRetry → 写操作必须为 false -} \ No newline at end of file diff --git a/GameFrameX.Network.RemoteMessaging/Routing/DiscoveryRoutingWire.cs b/GameFrameX.Network.RemoteMessaging/Routing/DiscoveryRoutingWire.cs index ac19e9189..ab39462e5 100644 --- a/GameFrameX.Network.RemoteMessaging/Routing/DiscoveryRoutingWire.cs +++ b/GameFrameX.Network.RemoteMessaging/Routing/DiscoveryRoutingWire.cs @@ -49,7 +49,22 @@ public static class DiscoveryRoutingWire private static IReadOnlyCollection _hostedRoles; private static IRemoteRoleRouter _remoteRouter; private static int _initialized; - private static int _localDispatcherAttached; + private static readonly object AttachLocalDispatcherLock = new(); + + /// + /// 路由缝是否已完成初始化( 成功执行后为 true)。 + /// 组合门面(如 ServerLink)用它判断能否补装本地投递槽。 + /// + /// + /// Whether the routing seam has been initialized (true after completes + /// successfully). Composition facades (such as ServerLink) use it to decide whether the local + /// delivery slot can be attached. + /// + /// 是否已初始化 / Whether the seam is initialized + public static bool IsInitialized + { + get { return Volatile.Read(ref _initialized) == 1 && Volatile.Read(ref _hostedRoles) != null && Volatile.Read(ref _remoteRouter) != null; } + } /// /// 初始化路由缝:以发现层路由表装配跨 Role 路由器(case 2/3 真实转发器,替换占位)。 @@ -101,8 +116,9 @@ public static void Initialize(IReadOnlyCollection hostedRoleNames, IRole /// strictly after (the hotfix module loads later in the same startup /// sequence, when the Hotfix-side sender components finally exist); a call before /// therefore throws instead of quietly degrading case 1 back to - /// route-time . Idempotent per process: the first call wins, - /// later calls (multi-role re-entry) return immediately without rebuilding the router. + /// route-time . Repeat calls rebuild the router with the + /// newest dispatcher in the case 1 slot (the remote chain is reused as-is), mirroring the + /// "repeated calls overwrite with the newest instance" semantics of UnifiedMessageSenderHolder. /// /// 本地 envelope 复投器(Hotfix 装配点传入,与 UnifiedMessageSenderHolder 共用同一 IPlayerLocalSender)/ The local envelope dispatcher (sharing the same IPlayerLocalSender as UnifiedMessageSenderHolder) /// 当 为 null 时抛出 / Thrown when dispatcher is null @@ -117,12 +133,13 @@ public static void AttachLocalDispatcher(ILocalRoleMessageDispatcher dispatcher) throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.RemoteMessaging.Routing.AttachLocalDispatcherOrderInvalid)); } - if (Interlocked.CompareExchange(ref _localDispatcherAttached, 1, 0) != 0) + lock (AttachLocalDispatcherLock) { - return; - } + // 重复调用以最新 dispatcher 重建本地槽(远程链原样保留):与 UnifiedMessageSenderHolder + // 「重复调用覆盖为最新实例」同口径,保证本地信封复投与玩家级投递共用同一发送器。 + RoleRouterHolder.Initialize(new InProcessRoleRouter(_hostedRoles, dispatcher, _remoteRouter)); - RoleRouterHolder.Initialize(new InProcessRoleRouter(_hostedRoles, dispatcher, _remoteRouter)); + } } /// @@ -134,7 +151,7 @@ public static void AttachLocalDispatcher(ILocalRoleMessageDispatcher dispatcher) internal static void ResetForTest() { _initialized = 0; - _localDispatcherAttached = 0; + _hostedRoles = null; _remoteRouter = null; } diff --git a/GameFrameX.Network.RemoteMessaging/Routing/RoleRouteEnvelopeMessage.cs b/GameFrameX.Network.RemoteMessaging/Routing/RoleRouteEnvelopeMessage.cs index ddeaf95fc..444f7e3b6 100644 --- a/GameFrameX.Network.RemoteMessaging/Routing/RoleRouteEnvelopeMessage.cs +++ b/GameFrameX.Network.RemoteMessaging/Routing/RoleRouteEnvelopeMessage.cs @@ -29,7 +29,7 @@ using GameFrameX.Network.RemoteMessaging.Unified; -using GameFrameX.Network.RemoteMessaging.Versioning; + using ProtoBuf; namespace GameFrameX.Network.RemoteMessaging.Routing; @@ -48,7 +48,6 @@ namespace GameFrameX.Network.RemoteMessaging.Routing; /// [ProtoContract] [MessageTypeHandler(ReservedMessageId)] -[ProtocolVersion(1, 0)] public sealed class RoleRouteEnvelopeMessage : MessageObject { /// diff --git a/GameFrameX.Network.RemoteMessaging/Unified/ConsistentHashServerInstanceSelector.cs b/GameFrameX.Network.RemoteMessaging/Unified/ConsistentHashServerInstanceSelector.cs index 87d3fb381..5dfbfae4f 100644 --- a/GameFrameX.Network.RemoteMessaging/Unified/ConsistentHashServerInstanceSelector.cs +++ b/GameFrameX.Network.RemoteMessaging/Unified/ConsistentHashServerInstanceSelector.cs @@ -34,10 +34,13 @@ namespace GameFrameX.Network.RemoteMessaging.Unified; /// /// 基于一致性哈希的服务实例选择器。支持虚拟节点,提供稳定的路由落点。 /// 当实例下线时,仅影响部分 key 的重映射。 +/// 【冻结】随实例选择治理面一并冻结:保留现状供既有消费方使用,不再演进。 /// /// /// Consistent hash-based service instance selector. Supports virtual nodes for stable routing. /// When an instance goes offline, only a portion of keys are remapped. +/// [Frozen] Frozen together with the instance-selection governance surface: kept as-is for existing +/// consumers, no further evolution. /// public sealed class ConsistentHashServerInstanceSelector : IServerInstanceSelector { diff --git a/GameFrameX.Network.RemoteMessaging/Unified/IServerInstanceSelector.cs b/GameFrameX.Network.RemoteMessaging/Unified/IServerInstanceSelector.cs index 5901e320d..0caa7587d 100644 --- a/GameFrameX.Network.RemoteMessaging/Unified/IServerInstanceSelector.cs +++ b/GameFrameX.Network.RemoteMessaging/Unified/IServerInstanceSelector.cs @@ -31,9 +31,12 @@ namespace GameFrameX.Network.RemoteMessaging.Unified; /// /// 服务实例选择器接口。负责在同名多实例下进行一致性选路。 +/// 【冻结】实例选择治理面已冻结:保留现状供既有消费方使用,不再演进;新场景优先经玩家路由表寻址。 /// /// /// Server instance selector interface. Responsible for consistent routing among multiple instances with the same name. +/// [Frozen] The instance-selection governance surface is frozen: it stays as-is for existing consumers +/// and no longer evolves; new scenarios address through the player route table first. /// public interface IServerInstanceSelector { diff --git a/GameFrameX.Network.RemoteMessaging/Unified/MessageGovernancePolicy.cs b/GameFrameX.Network.RemoteMessaging/Unified/MessageGovernancePolicy.cs index 4896c6dd6..dee19155e 100644 --- a/GameFrameX.Network.RemoteMessaging/Unified/MessageGovernancePolicy.cs +++ b/GameFrameX.Network.RemoteMessaging/Unified/MessageGovernancePolicy.cs @@ -31,9 +31,13 @@ namespace GameFrameX.Network.RemoteMessaging.Unified; /// /// 消息治理策略配置。每类消息都应有对应的策略。 +/// 【冻结】治理策略面已冻结:保留现状供既有消费方使用,不再演进;新诉求经 IUnifiedMessageSender 的玩家级投递选项表达。 /// /// /// Message governance policy configuration. Each message type should have a corresponding policy. +/// [Frozen] The governance policy surface is frozen: it stays as-is for existing consumers and no +/// longer evolves; new needs are expressed through the player-level delivery options of +/// IUnifiedMessageSender. /// public sealed class MessageGovernancePolicy { diff --git a/GameFrameX.Network.RemoteMessaging/Versioning/DefaultProtocolVersionNegotiator.cs b/GameFrameX.Network.RemoteMessaging/Versioning/DefaultProtocolVersionNegotiator.cs deleted file mode 100644 index cda1931f7..000000000 --- a/GameFrameX.Network.RemoteMessaging/Versioning/DefaultProtocolVersionNegotiator.cs +++ /dev/null @@ -1,110 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the People's Republic of China and related international regulations. -// 使用本项目须严格遵守相应法律法规及开源许可证之规定。 -// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. -// 本项目采用 Apache License 2.0 单协议分发, -// This project is licensed solely under the Apache License 2.0, -// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 -// please refer to the LICENSE file in the root directory of the source code for the full license text. -// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 -// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, -// 侵犯他人合法权益等法律法规所禁止的行为! -// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! -// 因基于本项目二次开发所产生的一切法律纠纷与责任, -// Any legal disputes or liabilities arising from secondary development based on this project -// 本组织与贡献者概不承担。 -// shall be borne solely by the developer; the project organization and contributors assume no responsibility. -// GitHub 仓库:https://github.com/GameFrameX -// GitHub Repository: https://github.com/GameFrameX -// Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX -// CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX -// 官方文档:https://gameframex.doc.alianblank.com/ -// Official Documentation: https://gameframex.doc.alianblank.com/ -// ========================================================================================== - -namespace GameFrameX.Network.RemoteMessaging.Versioning; - -/// -/// 默认协议版本协商器。连接级按 major 相等判定兼容;消息级消费 : -/// 未标注恒兼容,标注则要求消息 major 不超过远端协商 major(minor 不阻断)。 -/// -/// -/// Default protocol version negotiator. Connection-level compatibility requires equal majors; -/// message-level checks consume : unannotated messages are -/// always compatible, annotated messages require their major not to exceed the negotiated remote -/// major (minor never blocks). -/// -internal sealed class DefaultProtocolVersionNegotiator : IProtocolVersionNegotiator -{ - /// - /// 检查连接级协议版本兼容性:major 一致即兼容,与 minor 无关。 - /// - /// - /// Checks connection-level protocol version compatibility: matching majors are compatible, - /// regardless of minor versions. - /// - /// 本端协议版本 / The local protocol version - /// 远端协议版本 / The remote protocol version - /// true 兼容;false 不兼容(应拒绝连接)/ true if compatible; false if incompatible (the connection should be rejected) - public bool IsConnectionCompatible(ProtocolVersion local, ProtocolVersion remote) - { - // 连接级拒绝语义:major 一致即兼容(minor 差异属向后兼容演进,不阻断) - return local.Major == remote.Major; - } - - /// - /// 检查指定消息类型对远端协商版本是否兼容:未标注的消息(基础契约)恒兼容; - /// 标注 的消息要求其 major 不超过远端协商 major。 - /// - /// - /// Checks whether the specified message type is compatible with the negotiated remote version: - /// unannotated messages (the base contract) are always compatible; messages annotated with - /// require their major not to exceed the negotiated remote major. - /// - /// 消息类型 / The message type to check - /// 远端协商版本 / The negotiated remote version - /// true 兼容;false 不兼容(该消息不应发往此对端)/ true if compatible; false if incompatible (the message must not be sent to this peer) - public bool IsMessageCompatible(Type messageType, ProtocolVersion remoteVersion) - { - var attribute = GetVersionAttribute(messageType); - if (attribute == null) - { - // 未标注消息 = 基础契约,对任意远端版本放行(既有消息路径行为不变) - return true; - } - - // 消息比远端协商 major 更新 → 对端无法按该版本解读,拒绝发送 - return attribute.Major <= remoteVersion.Major; - } - - /// - /// 获取指定消息类型的协议版本信息。 - /// - /// - /// Gets the protocol version information for the specified message type. - /// - /// 消息类型 / The message type to query - /// 版本字符串;未标注特性时返回 "0.0" / The version string; returns "0.0" when no attribute is present - public string GetVersion(Type messageType) - { - return GetVersionAttribute(messageType)?.VersionString ?? "0.0"; - } - - /// - /// 读取消息类型上的协议版本特性(不存在时返回 null)。 - /// - /// - /// Reads the protocol version attribute on the message type (null when absent). - /// - /// 消息类型 / The message type - /// 协议版本特性 / The protocol version attribute - private static ProtocolVersionAttribute GetVersionAttribute(Type messageType) - { - return (ProtocolVersionAttribute)messageType.GetCustomAttributes(typeof(ProtocolVersionAttribute), false).FirstOrDefault(); - } -} diff --git a/GameFrameX.Network.RemoteMessaging/Versioning/IProtocolVersionNegotiator.cs b/GameFrameX.Network.RemoteMessaging/Versioning/IProtocolVersionNegotiator.cs deleted file mode 100644 index 7f5c2354c..000000000 --- a/GameFrameX.Network.RemoteMessaging/Versioning/IProtocolVersionNegotiator.cs +++ /dev/null @@ -1,83 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the People's Republic of China and related international regulations. -// 使用本项目须严格遵守相应法律法规及开源许可证之规定。 -// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. -// 本项目采用 Apache License 2.0 单协议分发, -// This project is licensed solely under the Apache License 2.0, -// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 -// please refer to the LICENSE file in the root directory of the source code for the full license text. -// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 -// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, -// 侵犯他人合法权益等法律法规所禁止的行为! -// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! -// 因基于本项目二次开发所产生的一切法律纠纷与责任, -// Any legal disputes or liabilities arising from secondary development based on this project -// 本组织与贡献者概不承担。 -// shall be borne solely by the developer; the project organization and contributors assume no responsibility. -// GitHub 仓库:https://github.com/GameFrameX -// GitHub Repository: https://github.com/GameFrameX -// Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX -// CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX -// 官方文档:https://gameframex.doc.alianblank.com/ -// Official Documentation: https://gameframex.doc.alianblank.com/ -// ========================================================================================== - -namespace GameFrameX.Network.RemoteMessaging.Versioning; - -/// -/// 协议版本协商器。提供连接级 major 比较与消息级 消费语义: -/// 连接握手交换 ,major 不一致显式拒绝; -/// 消息级检查按「未标注恒兼容;标注则消息 major 不超过远端协商 major」判定。 -/// -/// -/// Protocol version negotiator. Provides the connection-level major comparison and the -/// message-level consumption semantics: the connection -/// handshake exchanges and rejects on differing -/// majors; the message-level check follows "unannotated is always compatible; an annotated -/// message's major must not exceed the negotiated remote major". -/// -public interface IProtocolVersionNegotiator -{ - /// - /// 检查连接级协议版本兼容性:major 一致即兼容,与 minor 无关。 - /// - /// - /// Checks connection-level protocol version compatibility: matching majors are compatible, - /// regardless of minor versions. - /// - /// 本端协议版本 / The local protocol version - /// 远端协议版本 / The remote protocol version - /// true 兼容;false 不兼容(应拒绝连接)/ true if compatible; false if incompatible (the connection should be rejected) - bool IsConnectionCompatible(ProtocolVersion local, ProtocolVersion remote); - - /// - /// 检查指定消息类型对远端协商版本是否兼容:未标注的消息(基础契约)恒兼容; - /// 标注 的消息要求其 major 不超过远端协商 major - /// (minor 不阻断——protobuf 向后兼容演进规则)。 - /// - /// - /// Checks whether the specified message type is compatible with the negotiated remote version: - /// unannotated messages (the base contract) are always compatible; messages annotated with - /// require their major not to exceed the negotiated - /// remote major (minor never blocks — the protobuf backward-compatible evolution rules). - /// - /// 消息类型 / The message type to check - /// 远端协商版本 / The negotiated remote version - /// true 兼容;false 不兼容(该消息不应发往此对端)/ true if compatible; false if incompatible (the message must not be sent to this peer) - bool IsMessageCompatible(Type messageType, ProtocolVersion remoteVersion); - - /// - /// 获取指定消息类型的协议版本信息。 - /// - /// - /// Gets the protocol version information for the specified message type. - /// - /// 消息类型 / The message type to query - /// 版本字符串;未标注特性时返回 "0.0" / The version string; returns "0.0" when no attribute is present - string GetVersion(Type messageType); -} diff --git a/GameFrameX.Network.RemoteMessaging/Versioning/ProtocolVersionAttribute.cs b/GameFrameX.Network.RemoteMessaging/Versioning/ProtocolVersionAttribute.cs deleted file mode 100644 index 7f785948a..000000000 --- a/GameFrameX.Network.RemoteMessaging/Versioning/ProtocolVersionAttribute.cs +++ /dev/null @@ -1,101 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the People's Republic of China and relevant international regulations. -// 使用本项目须严格遵守相应法律法规及开源许可证之规定。 -// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. -// 本项目采用 Apache License 2.0 单协议分发, -// This project is licensed solely under the Apache License 2.0, -// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 -// please refer to the LICENSE file in the root directory of the source code for the full license text. -// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 -// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, -// 侵犯他人合法权益等法律法规所禁止的行为! -// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! -// 因基于本项目二次开发所产生的一切法律纠纷与责任, -// Any legal disputes and liabilities arising from secondary development based on this project -// 本项目组织与贡献者概不承担。 -// shall be borne solely by the developer; the project organization and contributors assume no responsibility. -// GitHub 仓库:https://github.com/GameFrameX -// GitHub Repository: https://github.com/GameFrameX -// Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX -// CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX -// 官方文档:https://gameframex.doc.alianblank.com/ -// Official Documentation: https://gameframex.doc.alianblank.com/ -// ========================================================================================== - -namespace GameFrameX.Network.RemoteMessaging.Versioning; - -/// -/// 协议版本特性。标注在消息类型上,用于协议演进时的版本协商和兼容性检查。 -/// 演进规则: -/// 1. 新增字段:使用新的 ProtoMember 编号,不修改已有编号。 -/// 2. 废弃字段:保留编号但不使用,不得删除或复用编号。 -/// 3. 版本升级:Minor 版本递增表示向后兼容,Major 版本递增表示不兼容变更。 -/// -/// -/// Protocol version attribute. Annotate on message types for version negotiation and compatibility checking during protocol evolution. -/// Evolution rules: -/// 1. Adding fields: Use new ProtoMember numbers; do not modify existing numbers. -/// 2. Deprecating fields: Keep the number but stop using it; never delete or reuse numbers. -/// 3. Version upgrades: Increment Minor for backward-compatible changes; increment Major for breaking changes. -/// -[AttributeUsage(AttributeTargets.Class, Inherited = false)] -public sealed class ProtocolVersionAttribute : Attribute -{ - /// - /// 初始化协议版本特性。 - /// - /// - /// Initializes a new instance of the protocol version attribute. - /// - /// 主版本号 / The major version number - /// 次版本号 / The minor version number - public ProtocolVersionAttribute(int major, int minor) - { - Major = major; - Minor = minor; - } - - /// - /// 主版本号。不兼容变更时递增。 - /// - /// - /// The major version number. Incremented on breaking changes. - /// - /// 主版本号 / The major version number - public int Major { get; } - - /// - /// 次版本号。向后兼容新增时递增。 - /// - /// - /// The minor version number. Incremented for backward-compatible additions. - /// - /// 次版本号 / The minor version number - public int Minor { get; } - - /// - /// 协议描述。 - /// - /// - /// The protocol description. - /// - /// 协议描述 / The protocol description - public string Description { get; set; } - - /// - /// 版本字符串。 - /// - /// - /// The version string. - /// - /// 版本字符串(格式 "Major.Minor") / The version string (format "Major.Minor") - public string VersionString - { - get { return $"{Major}.{Minor}"; } - } -} \ No newline at end of file diff --git a/GameFrameX.Network.RemoteMessaging/Versioning/RemoteMessagingProtocolVersion.cs b/GameFrameX.Network.RemoteMessaging/Versioning/RemoteMessagingProtocolVersion.cs index e4ff4f7c4..525f6fbba 100644 --- a/GameFrameX.Network.RemoteMessaging/Versioning/RemoteMessagingProtocolVersion.cs +++ b/GameFrameX.Network.RemoteMessaging/Versioning/RemoteMessagingProtocolVersion.cs @@ -32,14 +32,14 @@ namespace GameFrameX.Network.RemoteMessaging.Versioning; /// /// RemoteMessaging 连接级协议版本的单一事实源。握手阶段交换此版本;Major 不一致显式拒绝。 /// 演进规则: 的 Major 递增表示 wire 契约不兼容变更(禁止跨 Major 混布), -/// Minor 递增表示向后兼容演进(protobuf 字段规则,见 )。 +/// Minor 递增表示向后兼容演进(protobuf 字段规则)。 /// /// /// The single source of truth for the connection-level RemoteMessaging protocol version. This version is /// exchanged during the connection handshake; differing majors are explicitly rejected. Evolution rules: /// incrementing 's major marks a breaking wire-contract change (cross-major mixed /// deployments are forbidden); incrementing the minor marks backward-compatible evolution (the protobuf -/// field rules, see ). +/// field rules). /// public static class RemoteMessagingProtocolVersion { diff --git a/GameFrameX.Network.RemoteMessaging/Versioning/ReqProtocolVersionNegotiation.cs b/GameFrameX.Network.RemoteMessaging/Versioning/ReqProtocolVersionNegotiation.cs index 0b5b584c5..e3164eb12 100644 --- a/GameFrameX.Network.RemoteMessaging/Versioning/ReqProtocolVersionNegotiation.cs +++ b/GameFrameX.Network.RemoteMessaging/Versioning/ReqProtocolVersionNegotiation.cs @@ -44,7 +44,6 @@ namespace GameFrameX.Network.RemoteMessaging.Versioning; /// [ProtoContract] [MessageTypeHandler(ReservedMessageId)] -[ProtocolVersion(1, 0)] public sealed class ReqProtocolVersionNegotiation : MessageObject, IRequestMessage { /// diff --git a/GameFrameX.Network.RemoteMessaging/Versioning/RespProtocolVersionNegotiation.cs b/GameFrameX.Network.RemoteMessaging/Versioning/RespProtocolVersionNegotiation.cs index fff0e17a2..d9e4fa716 100644 --- a/GameFrameX.Network.RemoteMessaging/Versioning/RespProtocolVersionNegotiation.cs +++ b/GameFrameX.Network.RemoteMessaging/Versioning/RespProtocolVersionNegotiation.cs @@ -44,7 +44,6 @@ namespace GameFrameX.Network.RemoteMessaging.Versioning; /// [ProtoContract] [MessageTypeHandler(ReservedMessageId)] -[ProtocolVersion(1, 0)] public sealed class RespProtocolVersionNegotiation : MessageObject, IResponseMessage { /// diff --git a/GameFrameX.ServerLink/GameFrameX.ServerLink.csproj b/GameFrameX.ServerLink/GameFrameX.ServerLink.csproj new file mode 100644 index 000000000..967f3281d --- /dev/null +++ b/GameFrameX.ServerLink/GameFrameX.ServerLink.csproj @@ -0,0 +1,14 @@ + + + + + GameFrameX.ServerLink,GameFrameX 框架的服务器间链路薄门面:直连拨号(固定重试上限)+ RoleRouteEnvelopeMessage 信封转发 + 玩家路由解析内置默认. Thin inter-server link facade for the GameFrameX framework: direct dialing with a fixed retry limit, RoleRouteEnvelopeMessage envelope forwarding, and player-route resolution as the built-in default. Documentation: https://gameframex.doc.alianblank.com + GameFrameX,ServerLink,RemoteMessaging,Routing,PlayerRoute,Server,GameServer + + + + + + + + diff --git a/GameFrameX.ServerLink/ServerLinkBuilder.cs b/GameFrameX.ServerLink/ServerLinkBuilder.cs new file mode 100644 index 000000000..91e9f24de --- /dev/null +++ b/GameFrameX.ServerLink/ServerLinkBuilder.cs @@ -0,0 +1,199 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please see the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes and liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== +using GameFrameX.Discovery; +using GameFrameX.Network.RemoteMessaging; +using GameFrameX.Network.RemoteMessaging.Contracts; +using GameFrameX.Network.RemoteMessaging.Transport; + +namespace GameFrameX.ServerLink; + +/// +/// 服务器间链路薄门面构建器:在 组合面之上 +/// 固化内置默认——直连 TCP 拨号 + 固定重试上限 + PassThrough 韧性(不熔断、不做端点健康评估)。 +/// 路由表为必填(心跳注册表双视图读侧),未绑定时构建即失败。 +/// +/// +/// The thin builder facade for the inter-server link. It pins the built-in defaults on top of the +/// composition surface: direct TCP dialing, +/// a fixed retry limit, and the pass-through resilience posture (no circuit breaking and no endpoint +/// health evaluation). The route table is required (the heartbeat registry's dual-view read side); +/// building without one fails fast. +/// +/// +/// +/// var client = new ServerLinkBuilder() +/// .WithRouteTable(ActiveDiscoveryRuntime.RouteTableProvider) +/// .Build(); +/// +/// // 需要 UDP 传输时显式叠加 KCP +/// var kcpClient = new ServerLinkBuilder() +/// .WithRouteTable(ActiveDiscoveryRuntime.RouteTableProvider) +/// .WithKcpTransport() +/// .Build(); +/// +/// +public sealed class ServerLinkBuilder +{ + /// + /// 固定重试上限的缺省值(2 次重试;与 RemoteMessagingOptions.MaxRetryCount 缺省及 + /// 「幂等操作最大重试不超过 2 次」的准入规范一致)。 + /// + /// + /// The default fixed retry limit (2 retries; aligned with the RemoteMessagingOptions.MaxRetryCount + /// default and the guideline that idempotent operations retry at most twice). + /// + public const int DefaultFixedRetryLimit = 2; + + /// + /// 缺省调用超时毫秒数(5000ms,与 RemoteMessaging 缺省一致)。 + /// + /// + /// The default call timeout in milliseconds (5000 ms, same as the RemoteMessaging default). + /// + public const int DefaultTimeoutMilliseconds = 5000; + + private IRoleRouteTableProvider _routeTableProvider; + private Func _connectionProviderFactory; + private int _timeoutMilliseconds = DefaultTimeoutMilliseconds; + private int _fixedRetryLimit = DefaultFixedRetryLimit; + private int _retryBaseDelayMilliseconds = 200; + private bool _enableKcpTransport; + + /// + /// 绑定发现层路由表(服务器间端点的唯一事实源:心跳注册表双视图读侧)。必填。 + /// + /// + /// Binds the discovery-layer route table (the single source of truth for inter-server + /// endpoints: the heartbeat registry's dual-view read side). Required. + /// + /// 双视图路由表提供者 / The dual-view route table provider + /// 构建器实例 / The builder instance + /// 当 routeTableProvider 为 null 时抛出 / Thrown when routeTableProvider is null + public ServerLinkBuilder WithRouteTable(IRoleRouteTableProvider routeTableProvider) + { + _routeTableProvider = routeTableProvider ?? throw new ArgumentNullException(nameof(routeTableProvider)); + return this; + } + + /// + /// 设置调用超时毫秒数。 + /// + /// + /// Sets the call timeout in milliseconds. + /// + /// 超时毫秒数 / The timeout duration in milliseconds + /// 构建器实例 / The builder instance + public ServerLinkBuilder WithTimeoutMilliseconds(int timeoutMilliseconds) + { + _timeoutMilliseconds = timeoutMilliseconds; + return this; + } + + /// + /// 设置固定重试上限(直连拨号的内置重试策略;0 表示不重试)。 + /// + /// + /// Sets the fixed retry limit (the built-in retry policy of the direct dial; 0 disables retries). + /// + /// 最大重试次数 / The maximum number of retry attempts + /// 重试基础延迟毫秒数 / The base delay in milliseconds between retries + /// 构建器实例 / The builder instance + public ServerLinkBuilder WithFixedRetryLimit(int maxRetryCount, int baseDelayMilliseconds = 200) + { + _fixedRetryLimit = maxRetryCount; + _retryBaseDelayMilliseconds = baseDelayMilliseconds; + return this; + } + + /// + /// 叠加注册 KCP 拨号适配器(UDP 传输;TCP 仍为回落传输,与 RemoteMessaging 组合面一致)。 + /// + /// + /// Registers the KCP dialing adapter on top (the UDP transport; tcp stays the fallback + /// transport, identical to the RemoteMessaging composition surface). + /// + /// 构建器实例 / The builder instance + public ServerLinkBuilder WithKcpTransport() + { + _enableKcpTransport = true; + return this; + } + + /// + /// 配置连接提供器工厂(测试注入点):替代缺省的进程级共享 TCP 连接池。 + /// + /// + /// Configures the connection provider factory (a test injection point) that replaces the + /// default process-wide shared TCP connection pool. + /// + /// 连接提供器工厂 / The connection provider factory + /// 构建器实例 / The builder instance + /// 当 connectionProviderFactory 为 null 时抛出 / Thrown when connectionProviderFactory is null + public ServerLinkBuilder WithConnectionProvider(Func connectionProviderFactory) + { + _connectionProviderFactory = connectionProviderFactory ?? throw new ArgumentNullException(nameof(connectionProviderFactory)); + return this; + } + + /// + /// 构建远程消息客户端。内置默认:直连 TCP 拨号、固定重试上限、PassThrough 韧性、压缩与包上限取 RemoteMessaging 缺省。 + /// 未绑定路由表时抛 (fail-fast、无回落)。 + /// + /// + /// Builds the remote message client with the built-in defaults: direct TCP dialing, the fixed + /// retry limit, the pass-through resilience posture, and RemoteMessaging's default compression + /// and packet limits. Throws when no route table was + /// bound (fail fast; there is no fallback). + /// + /// 远程消息客户端实例 / The remote message client instance + public IRemoteMessageClient Build() + { + if (_routeTableProvider == null) + { + throw new InvalidOperationException("ServerLinkBuilder requires a route table: call WithRouteTable(IRoleRouteTableProvider) before Build()."); + } + + var builder = new RemoteMessagingBuilder() + .WithTimeoutMs(_timeoutMilliseconds) + .WithRetry(_fixedRetryLimit, _retryBaseDelayMilliseconds) + .WithRouteTable(_routeTableProvider); + + if (_enableKcpTransport) + { + builder.UseKcpTransportAdapter(); + } + + if (_connectionProviderFactory != null) + { + builder.WithConnectionProvider(_connectionProviderFactory); + } + + return builder.Build(); + } +} diff --git a/GameFrameX.ServerLink/ServerLinkEnvelopeForwarder.cs b/GameFrameX.ServerLink/ServerLinkEnvelopeForwarder.cs new file mode 100644 index 000000000..ed21aa0cb --- /dev/null +++ b/GameFrameX.ServerLink/ServerLinkEnvelopeForwarder.cs @@ -0,0 +1,82 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please see the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes and liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Network.RemoteMessaging.Routing; + +namespace GameFrameX.ServerLink; + +/// +/// 服务器间信封转发薄门面:把一条跨 Role 消息交给进程级路由缝 +/// (本进程 Role 走本地投递,跨进程跳由路由器打包 经共享传输池转发)。 +/// +/// +/// The thin envelope-forwarding facade for inter-server messaging: it hands one cross-role message +/// to the process-wide routing seam (roles hosted by this process go to local in-process delivery; +/// remote hops are packed as a by the router and forwarded +/// over the shared transport pool). +/// +public static class ServerLinkEnvelopeForwarder +{ + /// + /// 路由缝是否已完成装配(启动流程初始化 RoleRouterHolder 后为 true)。 + /// + /// + /// Whether the routing seam has been assembled (true after the launch flow initializes + /// RoleRouterHolder). + /// + /// 是否已装配 / Whether the seam is initialized + public static bool IsRoutingInitialized + { + get { return RoleRouterHolder.IsInitialized; } + } + + /// + /// 转发一封跨 Role 消息信封:目标 Role 由本进程承载时走本地投递,否则经远程转发(打包 RoleRouteEnvelopeMessage)。 + /// + /// + /// Forwards one cross-role message envelope: when the target role is hosted by this process the + /// message goes to local in-process delivery; otherwise it is forwarded remotely (packed as a + /// RoleRouteEnvelopeMessage). + /// + /// 目标 Role 的服务器类型名 / The target role server type name + /// 要转发的消息 / The message to forward + /// 本地投递目标 ActorId(跨进程跳时忽略)/ The local delivery target actor id (ignored on remote hops) + /// 可选的目标实例 Id(非空定向已知实例,空取任意活跃实例)/ Optional target instance id (non-null selects a known instance, null selects any active instance) + /// 取消操作的令牌 / The cancellation token + /// 实际命中的投递分支 / The delivery branch that was actually hit + /// 当 message 为 null 时抛出 / Thrown when message is null + /// 当路由缝尚未装配时抛出 / Thrown when the routing seam is not initialized + public static Task ForwardAsync(string targetRole, GameFrameX.Network.Messages.MessageObject message, long targetActorId = 0, string targetInstanceId = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(message); + + var envelope = new MessageEnvelope(targetRole, message, targetActorId, targetInstanceId); + return RoleRouterHolder.Current.RouteAsync(envelope, cancellationToken); + } +} diff --git a/GameFrameX.ServerLink/ServerLinkPlayerRouting.cs b/GameFrameX.ServerLink/ServerLinkPlayerRouting.cs new file mode 100644 index 000000000..11d1598ee --- /dev/null +++ b/GameFrameX.ServerLink/ServerLinkPlayerRouting.cs @@ -0,0 +1,118 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please see the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes and liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Discovery; +using GameFrameX.Network.RemoteMessaging; +using GameFrameX.Network.RemoteMessaging.Contracts; +using GameFrameX.Network.RemoteMessaging.Routing; +using GameFrameX.Network.RemoteMessaging.Unified; + +namespace GameFrameX.ServerLink; + +/// +/// 玩家路由投递组合薄门面:以发现层玩家路由解析为内置默认,装配统一消息发送器与本地信封投递槽。 +/// 跨服找人是合服后的刚需——玩家级投递(本服直发 / 跨服转发 / 离线策略)经 +/// 的发送器完成,宿主无需自行拼接各组件。 +/// +/// +/// The thin composition facade for player-route delivery: it assembles the unified message sender +/// and the local envelope delivery slot with the discovery-layer player-route resolver as the +/// built-in default. Finding players across servers is essential after server merges — the +/// player-level delivery (local direct send / cross-server forward / offline strategy) is done by +/// the sender held in , so hosts do not wire the +/// components themselves. +/// +public static class ServerLinkPlayerRouting +{ + /// + /// 以发现层玩家路由解析器为内置默认,装配统一消息发送器与本地信封投递槽。 + /// 幂等装配由各 Holder/组合侧自行保证(重复调用覆盖为最新实例)。 + /// + /// + /// Assembles the unified message sender and the local envelope delivery slot with the + /// discovery-layer player-route resolver as the built-in default. Idempotence is delegated to + /// the holders/composition side (repeated calls overwrite with the newest instances). + /// + /// 远程消息客户端(建议经 构建)/ The remote message client (preferably built via ) + /// 双视图路由表提供者(实例列表唯一来源)/ The dual-view route table provider (the single source of the instance list) + /// 发现层玩家路由解析器(控制库读侧)/ The discovery-layer player-route resolver (the control-database read side) + /// 本服玩家发送器(本地投递出口)/ The local player sender (the local delivery exit) + /// 本服服务器类型(本服判定基准)/ The local server type (the local-server identity baseline) + /// 本进程发现层实例 Id(本服判定基准)/ This process's discovery instance id (the local-server identity baseline) + /// 装配完成的统一消息发送器(同 当前实例)/ The assembled unified message sender (the current instance of ) + /// 当 remoteMessageClient、routeTableProvider、playerRouteResolver 或 localPlayerSender 为 null 时抛出 / Thrown when remoteMessageClient, routeTableProvider, playerRouteResolver, or localPlayerSender is null + public static IUnifiedMessageSender ComposeUnifiedSender( + IRemoteMessageClient remoteMessageClient, + IRoleRouteTableProvider routeTableProvider, + GameFrameX.Discovery.Routing.IPlayerRouteResolver playerRouteResolver, + IPlayerLocalSender localPlayerSender, + string localServerType, + string localInstanceId) + { + ArgumentNullException.ThrowIfNull(remoteMessageClient); + ArgumentNullException.ThrowIfNull(routeTableProvider); + ArgumentNullException.ThrowIfNull(playerRouteResolver); + ArgumentNullException.ThrowIfNull(localPlayerSender); + + var routeResolver = CreateRouteResolver(playerRouteResolver); + UnifiedMessageSenderHolder.InitializeWithDefaults( + routeResolver, + localPlayerSender, + remoteMessageClient, + routeTableProvider, + localServerType, + localInstanceId); + + // 本地信封投递槽与发送器共用同一 localSender,保证一条本地复投语义; + // 仅在路由缝已由启动流程初始化后补装(未初始化时跳过,由启动流程装配各自的投递槽) + if (DiscoveryRoutingWire.IsInitialized) + { + DiscoveryRoutingWire.AttachLocalDispatcher(new LocalEnvelopeDispatcher(localPlayerSender)); + } + + return UnifiedMessageSenderHolder.Sender; + } + + /// + /// 把发现层玩家路由解析器适配为 Unified 投递契约(在线路由 → Online,离线路由 → Offline,路由缺失 → null)。 + /// + /// + /// Adapts a discovery-layer player-route resolver into the Unified delivery contract (online + /// routes become Online, offline routes become Offline, a missing route becomes null). + /// + /// 发现层玩家路由解析器 / The discovery-layer player-route resolver + /// Unified 契约的玩家路由解析器 / The Unified-contract player-route resolver + /// 当 playerRouteResolver 为 null 时抛出 / Thrown when playerRouteResolver is null + public static IPlayerRouteResolver CreateRouteResolver(GameFrameX.Discovery.Routing.IPlayerRouteResolver playerRouteResolver) + { + ArgumentNullException.ThrowIfNull(playerRouteResolver); + + return new RoutingPlayerRouteResolverAdapter(playerRouteResolver); + } +} diff --git a/GameFrameX.StartUp/AppStartUpBase.ByHTTPServer.cs b/GameFrameX.StartUp/AppStartUpBase.ByHTTPServer.cs index 4342a74b8..24749efbb 100644 --- a/GameFrameX.StartUp/AppStartUpBase.ByHTTPServer.cs +++ b/GameFrameX.StartUp/AppStartUpBase.ByHTTPServer.cs @@ -184,10 +184,18 @@ private void LogHttpPortOccupied() /// 当启用 HTTPS 但未实现时抛出 / Thrown when HTTPS is enabled but not implemented private async Task RunHttpServerAsync(List baseHandler, Func httpFactory, List aopHandlerTypes, LogLevel minimumLevelLogLevel) { - var builder = WebApplication.CreateBuilder(); - - // 确定是否为开发环境 + // 确定是否为开发环境;开发环境名必须在构建前经 WebApplicationOptions 传入—— + // CreateBuilder 按当时环境名加载 appsettings.{Environment}.json,构建后改写 + // EnvironmentName 只改判定不改已加载配置,会造成环境状态与配置源不一致。 var development = Setting.HttpIsDevelopment || EnvironmentHelper.IsDevelopment(); + var builder = development + ? WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = Environments.Development }) + : WebApplication.CreateBuilder(); + + // 显式开发开关(HttpIsDevelopment / 本机开发环境判定)驱动 Web 宿主环境: + // /health、/alive 等默认端点仅在 Development 环境映射(ServiceDefaults 的安全默认—— + // 非开发环境暴露健康端点有安全影响),开关开启而环境未标注时健康端点将 404, + // 与开关语义及 README 健康检查指引相悖,这里在构建期对齐环境名。 var openApiInfo = GetOpenApiInfo(); diff --git a/GameFrameX.StartUp/GameFrameX.StartUp.csproj b/GameFrameX.StartUp/GameFrameX.StartUp.csproj index 2a96aea80..f14fef8a4 100644 --- a/GameFrameX.StartUp/GameFrameX.StartUp.csproj +++ b/GameFrameX.StartUp/GameFrameX.StartUp.csproj @@ -36,7 +36,7 @@ - + diff --git a/GameFrameX.StartUp/ServiceDefaults/ServiceDefaultsExtensions.cs b/GameFrameX.StartUp/ServiceDefaults/ServiceDefaultsExtensions.cs index 9b91d147e..7aa24e250 100644 --- a/GameFrameX.StartUp/ServiceDefaults/ServiceDefaultsExtensions.cs +++ b/GameFrameX.StartUp/ServiceDefaults/ServiceDefaultsExtensions.cs @@ -36,7 +36,7 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using MongoDB.Driver; + using OpenTelemetry; using OpenTelemetry.Exporter; using OpenTelemetry.Metrics; @@ -61,10 +61,18 @@ public static class ServiceDefaultsExtensions /// private const string AlivenessEndpointPath = "/alive"; - private static readonly object MongoHealthClientLock = new(); + /// + /// MongoDB 健康检查类型的程序集限定名。StartUp 不直接引用 MongoDB.Driver, + /// 健康检查实例经 Provider 程序集反射解析(与 DbProviderResolver 的装配机制一致)。 + /// + /// + /// The assembly-qualified name of the MongoDB health check type. StartUp does not reference + /// MongoDB.Driver directly; the health check instance is resolved through the provider + /// assembly by reflection (the same assembly-resolution mechanism as DbProviderResolver). + /// + private const string MongoHealthCheckTypeName = "GameFrameX.DataBase.Mongo.HealthChecks.MongoDbHealthCheck, GameFrameX.DataBase.Mongo"; + private static readonly TimeSpan MongoHealthCheckTimeout = TimeSpan.FromSeconds(3); - private static MongoClient _mongoHealthClient; - private static string _mongoHealthConnectionString; /// /// 为应用程序构建器添加默认服务,包括弹性、健康检查和OpenTelemetry @@ -301,10 +309,14 @@ public static TBuilder AddDefaultHealthChecks(this TBuilder builder) w } /// - /// 在配置了 MongoDB 连接串时添加数据库健康检查。 + /// 在配置了 MongoDB 连接串时添加数据库健康检查。检查实例经 Provider 程序集反射解析 + /// (StartUp 不引用 MongoDB.Driver);Provider 程序集未加载时注册显式 Degraded 探针暴露配置错配。 /// /// - /// Adds MongoDB health check when the MongoDB connection string is configured. + /// Adds the MongoDB health check when the MongoDB connection string is configured. The check + /// instance is resolved through the provider assembly by reflection (StartUp does not reference + /// MongoDB.Driver); when the provider assembly is not loaded, an explicit degraded check is + /// registered so the misconfiguration surfaces instead of being silently skipped. /// /// 健康检查构建器 / Health checks builder private static void AddMongoDbHealthCheckIfConfigured(IHealthChecksBuilder healthChecksBuilder) @@ -316,6 +328,29 @@ private static void AddMongoDbHealthCheckIfConfigured(IHealthChecksBuilder healt return; } + IHealthCheck mongoHealthCheck; + try + { + mongoHealthCheck = CreateMongoDbHealthCheck(connectionString); + } + catch (Exception exception) + { + // 探针构造失败(如连接串非法被驱动拒绝)按 Degraded 暴露,不打断宿主启动: + // 与「Provider 程序集未加载 → Degraded」同一降级口径。 + healthChecksBuilder.AddCheck("mongodb", () => HealthCheckResult.Degraded( + "MongoDB health check could not be created from the configured connection string", exception), + tags: new[] { "db", "ready", }); + return; + } + + if (mongoHealthCheck == null) + { + healthChecksBuilder.AddCheck("mongodb", () => HealthCheckResult.Degraded( + "MongoDB connection string is configured but the GameFrameX.DataBase.Mongo provider assembly is not loaded"), + tags: new[] { "db", "ready", }); + return; + } + healthChecksBuilder.AddCheck("mongodb", cancellationToken => { using (var timeoutCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) @@ -323,51 +358,34 @@ private static void AddMongoDbHealthCheckIfConfigured(IHealthChecksBuilder healt timeoutCancellationSource.CancelAfter(MongoHealthCheckTimeout); try { - var mongoClient = GetOrCreateMongoHealthClient(connectionString); - using (var databases = mongoClient.ListDatabaseNamesAsync(timeoutCancellationSource.Token).GetAwaiter().GetResult()) - { - if (databases.AnyAsync(timeoutCancellationSource.Token).GetAwaiter().GetResult()) - { - return HealthCheckResult.Healthy("MongoDB connection is healthy"); - } - - return HealthCheckResult.Degraded("MongoDB connection is degraded: no databases found"); - } + return mongoHealthCheck.CheckHealthAsync(new HealthCheckContext(), timeoutCancellationSource.Token).GetAwaiter().GetResult(); } - catch (Exception ex) + catch (Exception exception) { - return HealthCheckResult.Degraded("MongoDB connection is temporarily unavailable", ex); + return HealthCheckResult.Degraded("MongoDB connection is temporarily unavailable", exception); } } }, tags: new[] { "db", "ready", }); } /// - /// 获取或创建用于健康检查的 MongoClient 实例。 + /// 经 Provider 程序集解析 MongoDB 健康检查实例(连接串构造重载)。 /// /// - /// Gets or creates the MongoClient instance used by health checks. + /// Resolves the MongoDB health check instance (the connection-string constructor overload) + /// through the provider assembly. /// - /// MongoDB 连接字符串 / MongoDB connection string - /// MongoDB 客户端实例 / MongoDB client instance - private static MongoClient GetOrCreateMongoHealthClient(string connectionString) + /// MongoDB 连接串 / The MongoDB connection string + /// 健康检查实例;Provider 程序集不可用时为 null / The health check instance, or null when the provider assembly is unavailable + private static IHealthCheck CreateMongoDbHealthCheck(string connectionString) { - if (_mongoHealthClient != null && string.Equals(_mongoHealthConnectionString, connectionString, StringComparison.Ordinal)) + var healthCheckType = Type.GetType(MongoHealthCheckTypeName, throwOnError: false); + if (healthCheckType == null) { - return _mongoHealthClient; + return null; } - lock (MongoHealthClientLock) - { - if (_mongoHealthClient != null && string.Equals(_mongoHealthConnectionString, connectionString, StringComparison.Ordinal)) - { - return _mongoHealthClient; - } - - _mongoHealthClient = new MongoClient(connectionString); - _mongoHealthConnectionString = connectionString; - return _mongoHealthClient; - } + return Activator.CreateInstance(healthCheckType, connectionString) as IHealthCheck; } /// diff --git a/GameFrameX.Utility/Setting/OnlineCapabilityOptions.cs b/GameFrameX.Utility/Setting/OnlineCapabilityOptions.cs index 5b0cdc9e2..0b188aa8d 100644 --- a/GameFrameX.Utility/Setting/OnlineCapabilityOptions.cs +++ b/GameFrameX.Utility/Setting/OnlineCapabilityOptions.cs @@ -25,6 +25,7 @@ // ========================================================================================== +using System.Text.Json.Serialization; using System.Text.Json; namespace GameFrameX.Utility.Setting; @@ -137,6 +138,7 @@ public sealed class OnlineCapabilityOptions /// fields / type mismatches fail fast at composition time). Unconfigured leaves the /// default (, equivalent to an empty object). /// + [JsonConverter(typeof(UndefinedSafeJsonElementConverter))] public JsonElement Settings { get; set; } /// diff --git a/GameFrameX.Utility/Setting/UndefinedSafeJsonElementConverter.cs b/GameFrameX.Utility/Setting/UndefinedSafeJsonElementConverter.cs new file mode 100644 index 000000000..e8e5272ca --- /dev/null +++ b/GameFrameX.Utility/Setting/UndefinedSafeJsonElementConverter.cs @@ -0,0 +1,84 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please see the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace GameFrameX.Utility.Setting; + +/// +/// 的未定义安全序列化转换器:写侧把缺省值 +/// 输出为空对象(与「未配置等效空对象」的既有文档口径一致), +/// 读侧保持默认行为。未配置的能力参数节随启动配置日志序列化时不再抛 +/// (System.Text.Json 对 Undefined 元素的写操作恒抛该异常)。 +/// +/// +/// An undefined-safe serialization converter for : the write side emits the +/// default value as an empty object (matching the documented +/// "unconfigured is equivalent to an empty object" semantics); the read side keeps the default +/// behavior. Serializing an unconfigured capability-parameter section together with the startup +/// configuration log no longer throws (System.Text.Json +/// always throws that exception when writing an Undefined element). +/// +public sealed class UndefinedSafeJsonElementConverter : JsonConverter +{ + /// + /// 读取保持默认行为(由框架默认实现完成 JsonElement 的读取)。 + /// + /// + /// Reading keeps the default behavior: the element is parsed via + /// —不走 JsonSerializer.Deserialize<JsonElement>(那会绕开调用方选项且可能递归进入本转换器)。 + /// + public override JsonElement Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + using (var document = JsonDocument.ParseValue(ref reader)) + { + return document.RootElement.Clone(); + } + } + + /// + /// 写入 JsonElement;缺省 Undefined 值输出空对象,其余值按原样写。 + /// + /// + /// Writes the JsonElement; the default Undefined value is written as an empty object and every + /// other value is written as-is. + /// + public override void Write(Utf8JsonWriter writer, JsonElement value, JsonSerializerOptions options) + { + if (value.ValueKind == JsonValueKind.Undefined) + { + writer.WriteStartObject(); + writer.WriteEndObject(); + return; + } + + value.WriteTo(writer); + } +} diff --git a/README.ja.md b/README.ja.md index 24be2467c..4d86a8f2b 100644 --- a/README.ja.md +++ b/README.ja.md @@ -90,7 +90,7 @@ GameFrameX Server は、C# .NET 10.0 で開発された高性能・クロスプ #### データベースと永続化 -- **デュアルデータベース Provider**: `DatabaseProvider` で `Mongo`(デフォルト)または `PostgreSql` を選択。両 Provider は同じ `GameFrameX.DataBase` 抽象レイヤーを共有 +- **データベース Provider の 3 分類**: PostgreSQL と MongoDB を完全検証のデュアルメインラインとして提供(条件付き書き込み、翻訳可能サブセットクエリ、トランザクション原子性が両 Provider でグリーンになることをリリースゲートとする)。加えて `DatabaseProvider` のデフォルトである SQLite がゼロ依存の導入 + テスト分類。いずれも同じ `GameFrameX.DataBase` 抽象レイヤーを共有 - **MongoDB Provider**: 完全な MongoDB 統合。ヘルスステートマシン対応(Healthy → Degraded → Unhealthy → Recovering) - **PostgreSQL Provider**: Npgsql ベース。MongoDB Provider と同等のリトライ / リカバリ / 可用性 / ヘルスチェック能力を備える - **透過的永続化**: StateComponent の自動シリアライズ/デシリアライズ。定期的バッチ upsert 操作で永続化 @@ -109,7 +109,7 @@ GameFrameX Server は、C# .NET 10.0 で開発された高性能・クロスプ ### 前提条件 - [.NET 10.0 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) のみをサポートします。.NET 8/9 はサポート対象外です。 -- [MongoDB 4.x+](https://www.mongodb.com/try/download/community)(デフォルト Provider。`--DatabaseProvider=PostgreSql` で PostgreSQL も利用可能) +- ゼロ依存起動に追加インストールは不要(SQLite は組込み、サンプル `Configs/app_config.json` のデフォルトも SQLite)。本番向け完全 Provider は MongoDB と PostgreSQL で、設定ファイルの選択 2 行を書き換えて選びます([データベース Provider の 3 分類と境界](#データベース-provider-の-3-分類と境界) を参照。MongoDB / PostgreSQL Provider を選択した場合のみ、それぞれのデータベースのインストールが必要です) - Visual Studio 2022 または JetBrains Rider(推奨) ### インストール @@ -120,40 +120,51 @@ GameFrameX Server は、C# .NET 10.0 で開発された高性能・クロスプ cd GameFrameX.Server.Source ``` -2. **依存関係を復元** - ```bash - dotnet restore - ``` +2. **ビルドして出力ディレクトリに移動** -3. **プロジェクトをビルド** + ランチャーは `Configs/` と `hotfix/` を作業ディレクトリ基準で解決するため、ビルド出力先から実行します(`quick_start-game.bat` もここにあります): ```bash dotnet build + cp -r Configs bin/app_debug/Configs + cd bin/app_debug ``` -4. **MongoDB を起動** - ```bash - # ローカルインストール - mongod --dbpath /path/to/data +3. **5 分でゼロ依存起動(SQLite)** - # または Docker を使用 - docker run -d -p 27017:27017 --name mongo mongo:8.2 + データベースのインストールも Docker も不要——コマンド 1 つで全ロールを単一プロセスで起動します(サンプル設定は既に SQLite デフォルトなので、CLI 値と設定ファイルは一致します): + ```bash + dotnet GameFrameX.Launcher.dll -- \ + --AllInOne \ + --DatabaseProvider=Sqlite \ + --DataBaseUrl="Data Source=data/gameframex.db" ``` - -5. **サーバーを起動** + - 起動ログに HTTP エントリと、解決された**データファイルの絶対パス**およびその読み書きチェックが出力されます。 + - ヘルスチェック: `http://localhost:28080/health`(ライブネスプローブ: `/alive`)——サンプル設定は開発モードが有効なためこれらのエンドポイントがマッピングされます(本番では `HttpIsDevelopment` をオフにしてください。`ServiceDefaultsExtensions` のセキュリティ注記を参照)。 + - データは作業ディレクトリ配下の `data/gameframex.db` に保存されます(Docker の `/app/data` ボリュームルートと一致)。プロセスを停止して再起動しても、アカウントと状態はそのまま残ります。 + - 一時的なスクラッチデータベースを使いたい場合は `--DataBaseUrl="Data Source=:memory:"` を指定——起動ログは**何も永続化されない**(プロセス終了で全データ消失)旨を警告します。 + - 単一プロセスを超えるスケールの前に [SQLite Provider の境界](#データベース-provider-の-3-分類と境界) を確認してください。 + +4. **MongoDB / PostgreSQL で起動(完全 Provider)** + サンプル `Configs/app_config.json` のデフォルトはゼロ依存の SQLite 分類です。Provider の選択は設定ファイルの 2 行書き換えで行います(起動バリデーターは CLI 引数と設定ファイルの一致を要求するため、選択は設定ファイルが担います): ```bash - dotnet run --project GameFrameX.Launcher -- \ - --ServerType=Game \ - --ServerId=1000 \ - --OuterPort=29100 \ - --HttpPort=28080 \ - --DataBaseUrl=mongodb://127.0.0.1:27017 \ - --DataBaseName=gameframex + # 1. データベースを起動(MongoDB の例。PostgreSQL も同様) + docker run -d -p 27017:27017 --name mongo mongo:8.2 + + # 2. 起動する全ロール分の Configs/app_config.json の選択を切り替え: + # "DatabaseProvider": "Mongo", + # "DataBaseUrl": "mongodb://127.0.0.1:27017" + # (完成済みサンプル: Configs/app_config.mongo.json / app_config.postgres.json) + + # 3. 実行 + dotnet GameFrameX.Launcher.dll -- --ServerType=Game ``` -6. **起動確認** +5. **起動確認** - ヘルスチェック: `http://localhost:28080/health`(ライブネスプローブ: `/alive`) - コンソールログで起動成功を確認 + **ゼロ JSON ゴールデンパス**: `Online.Settings` を一切書かずに起動しても、サンプルの RPS チェーン(マッチメイキング → 試合 → 決済 → 報酬付与 → ランキング)がそのまま動作します——`MatchSettledBoardId` はデフォルトボード `match-settled`(アセンブリ読み込み時に事前作成)へ投影されます。投影をオフにするには `online-competition.LeaderboardProjection.MatchSettledBoardId` を明示的に空にしてください。 + --- ## 使用例 @@ -212,11 +223,17 @@ GameFrameX はコマンドライン引数(`--Key=Value`)で設定を行い | 設定項目 | 説明 | デフォルト | 例 | |:--------|:-----|:----------|:---| -| `DatabaseProvider` | データベース Provider | `Mongo` | `PostgreSql` | +| `DatabaseProvider` | データベース Provider | `Sqlite` | `PostgreSql`、`Mongo` | | `DataBaseUrl` | データベース接続文字列 | なし | `mongodb://localhost:27017` | | `DataBaseName` | データベース名 | なし | `gameframex` | | `DataBasePassword` | データベースパスワード | なし | `your_password` | +#### データベース Provider の 3 分類と境界 + +- **3 分類の位置づけ**: `PostgreSql` と `Mongo` は完全検証のデュアルメインライン——条件付き書き込みプリミティブ、翻訳可能サブセットクエリ、トランザクション原子性などの全機能を両 Provider で二重実装・二重検証し、契約スイートのダブルグリーンがリリースゲートになります。`Sqlite` はゼロ依存の導入 + テスト分類(quickstart / demo ゴールデンパスのデフォルトの選択肢。組込みなのでデータベースの設置は不要)であり、本番トポロジは保証しません。 +- **データ移行ツールなし**: リポジトリは Mongo ↔ PostgreSQL のデータ移行実装を提供しません。Provider の切り替えは新規インストール / 新規サーバーの選定アクション(設定 2 行の変更)であり、既存の本番データベースの移行は各自で行ってください。 +- **デュアルメインラインの保守コスト**: 今後のデータベース機能は両 Provider で二重実装・二重検証が必要です(保守面は単一メインラインの約 ×1.5–2)。契約テストスイートは CI で PostgreSQL + MongoDB の両方で実行され、回帰はダブルグリーンゲートで担保されます。 + #### Actor 設定 | 設定項目 | 説明 | デフォルト | 例 | diff --git a/README.ko.md b/README.ko.md index 609a3ca48..5414ebc99 100644 --- a/README.ko.md +++ b/README.ko.md @@ -91,7 +91,7 @@ GameFrameX Server는 C# .NET 10.0으로 개발된 고성능, 크로스 플랫폼 #### 데이터베이스 및 영속화 -- **듀얼 데이터베이스 Provider**: `DatabaseProvider`로 `Mongo`(기본) 또는 `PostgreSql` 선택. 두 Provider 모두 동일한 `GameFrameX.DataBase` 추상 레이어를 공유 +- **데이터베이스 Provider 3등급**: PostgreSQL과 MongoDB를 이중 메인라인으로 제공(조건부 쓰기, 번역 가능 하위 집합 쿼리, 트랜잭션 원자성이 두 Provider에서 모두 그린이어야 릴리스 게이트를 통과)하고, SQLite는 제로 의존성 온보딩 + 테스트 등급으로 제공 - **MongoDB Provider**: 완전한 MongoDB 통합. 헬스 상태 머신 지원(Healthy → Degraded → Unhealthy → Recovering) - **PostgreSQL Provider**: Npgsql 기반. MongoDB Provider와 동일한 재시도 / 복구 / 가용성 / 헬스 체크 능력 제공 - **투명한 영속화**: StateComponent 자동 직렬화/역직렬화. 정기적 배치 업서트 작업으로 영속화 @@ -112,7 +112,7 @@ GameFrameX Server는 C# .NET 10.0으로 개발된 고성능, 크로스 플랫폼 ### 요구 사항 - [.NET 10.0 SDK](https://dotnet.microsoft.com/download/dotnet/10.0)만 지원합니다. .NET 8/9는 지원하지 않습니다. -- [MongoDB 4.x+](https://www.mongodb.com/try/download/community)(기본 Provider; `--DatabaseProvider=PostgreSql`로 PostgreSQL 사용 가능) +- 제로 의존성 시작: 그 외에는 아무것도 필요 없음(SQLite는 임베디드이며 예제 `Configs/app_config.json`도 기본으로 사용). 완전한 프로덕션 Provider는 MongoDB와 PostgreSQL이며, 설정 파일에서 선택 라인 2줄만 수정해 원하는 쪽을 고르면 됩니다([데이터베이스 Provider 3등급 정의와 경계](#데이터베이스-provider-3등급-정의와-경계) 참고). Mongo/PostgreSql Provider를 선택할 때만 해당 데이터베이스 설치가 필요합니다. - Visual Studio 2022 또는 JetBrains Rider(권장) ### 설치 @@ -123,37 +123,46 @@ GameFrameX Server는 C# .NET 10.0으로 개발된 고성능, 크로스 플랫폼 cd GameFrameX.Server.Source ``` -2. **종속성 복원** - ```bash - dotnet restore - ``` +2. **빌드 후 출력 디렉터리로 이동** -3. **프로젝트 빌드** + 런처는 작업 디렉터리를 기준으로 `Configs/`와 `hotfix/`를 해석하므로 빌드 출력 위치에서 실행합니다(`quick_start-game.bat`도 이곳에 있습니다): ```bash dotnet build + cp -r Configs bin/app_debug/Configs + cd bin/app_debug ``` -4. **MongoDB 시작** - ```bash - # 로컬 설치 - mongod --dbpath /path/to/data +3. **5분 제로 의존성 시작(Sqlite)** - # 또는 Docker 사용 - docker run -d -p 27017:27017 --name mongo mongo:8.2 + 데이터베이스 설치도 Docker도 없이, 명령 한 줄로 모든 역할을 단일 프로세스로 부팅합니다(예제 설정이 이미 SQLite 기본이므로 CLI 값과 파일이 일치): + ```bash + dotnet GameFrameX.Launcher.dll -- \ + --AllInOne \ + --DatabaseProvider=Sqlite \ + --DataBaseUrl="Data Source=data/gameframex.db" ``` - -5. **서버 실행** + - 시작 로그에 HTTP 진입점과 데이터 파일의 **절대 경로** 및 읽기/쓰기 검사 결과가 출력됩니다. + - 헬스 체크: `http://localhost:28080/health`(라이브니스 프로브: `/alive`) — 예제 설정은 개발 모드가 켜져 있어 이 엔드포인트가 매핑됩니다(프로덕션에서는 `HttpIsDevelopment`를 끄세요. `ServiceDefaultsExtensions`의 보안 참고 사항 확인). + - 데이터는 작업 디렉터리의 `data/gameframex.db`에 저장됩니다(Docker의 `/app/data` 볼륨 루트와 정렬). 프로세스를 중지하고 재시작해도 계정과 상태가 그대로 유지됩니다. + - 휘발성 스크래치 데이터베이스를 원한다면 `--DataBaseUrl="Data Source=:memory:"`를 사용하세요 — 시작 로그가 **아무것도 영속화되지 않는다**고 경고합니다(프로세스 종료 시 모두 손실). + - 단일 프로세스를 넘어 확장하기 전에 [데이터베이스 Provider 3등급 정의와 경계](#데이터베이스-provider-3등급-정의와-경계)를 먼저 확인하세요. + +4. **MongoDB / PostgreSQL로 시작(완전한 Provider)** + 예제 `Configs/app_config.json`은 기본적으로 제로 의존성 SQLite 등급입니다. Provider 선택은 설정 파일 2줄 수정으로 변경합니다(시작 검증기가 CLI 인수와 설정 파일의 일치를 요구하므로 파일이 선택 기준입니다): ```bash - dotnet run --project GameFrameX.Launcher -- \ - --ServerType=Game \ - --ServerId=1000 \ - --OuterPort=29100 \ - --HttpPort=28080 \ - --DataBaseUrl=mongodb://127.0.0.1:27017 \ - --DataBaseName=gameframex + # 1. 데이터베이스 시작(MongoDB 예시; PostgreSQL도 동일한 방식) + docker run -d -p 27017:27017 --name mongo mongo:8.2 + + # 2. 실행하는 모든 역할의 Configs/app_config.json에서 선택 변경: + # "DatabaseProvider": "Mongo", + # "DataBaseUrl": "mongodb://127.0.0.1:27017" + # (즉시 사용 가능한 샘플: Configs/app_config.mongo.json / app_config.postgres.json) + + # 3. 실행 + dotnet GameFrameX.Launcher.dll -- --ServerType=Game ``` -6. **시작 확인** +5. **시작 확인** - 헬스 체크: `http://localhost:28080/health`(라이브니스 프로브: `/alive`) - 콘솔 로그에서 시작 성공 확인 @@ -210,11 +219,17 @@ GameFrameX는 명령줄 인수(`--Key=Value`)로 설정합니다. 모든 설정 | 설정 항목 | 설명 | 기본값 | 예시 | |:---------|:-----|:------|:-----| -| `DatabaseProvider` | 데이터베이스 Provider | `Mongo` | `PostgreSql` | +| `DatabaseProvider` | 데이터베이스 Provider | `Sqlite` | `PostgreSql` | | `DataBaseUrl` | 데이터베이스 연결 문자열 | 없음 | `mongodb://localhost:27017` | | `DataBaseName` | 데이터베이스 이름 | 없음 | `gameframex` | | `DataBasePassword` | 데이터베이스 비밀번호 | 없음 | `your_password` | +#### 데이터베이스 Provider 3등급 정의와 경계 + +- **3등급 정의**: `PostgreSql`와 `Mongo`는 완전 검증 이중 메인라인입니다——조건부 쓰기 프리미티브, 번역 가능 하위 집합 쿼리, 트랜잭션 원자성 등 모든 기능을 두 Provider에서 이중 구현·이중 검증하며, 계약 스위트의 더블 그린이 릴리스 게이트입니다. `Sqlite`는 제로 의존성 온보딩 + 테스트 등급(quickstart / demo 골든 패스의 기본 수단, 임베디드로 데이터베이스 설치 불필요)이며 프로덕션 토폴로지는 보장하지 않습니다. +- **데이터 마이그레이션 도구 없음**: 저장소는 Mongo ↔ PostgreSQL 데이터 마이그레이션 구현을 제공하지 않습니다. Provider 전환은 신규 설치 / 신규 서버의 선택 작업(설정 2줄 변경)이며, 기존 프로덕션 데이터베이스의 전환은 직접 수행해야 합니다. +- **이중 메인라인 유지 비용**: 이후 모든 데이터베이스 기능은 두 Provider에서 이중 구현·이중 검증이 필요합니다(유지 규모는 단일 메인라인의 약 ×1.5–2). 계약 테스트 스위트는 CI에서 PostgreSQL + MongoDB 양쪽으로 실행되며, 회귀는 더블 그린 게이트로 방어됩니다. + #### Actor 설정 | 설정 항목 | 설명 | 기본값 | 예시 | diff --git a/README.md b/README.md index 0fc784aec..ec53522ef 100644 --- a/README.md +++ b/README.md @@ -87,11 +87,10 @@ GameFrameX Server is a high-performance, cross-platform game server framework bu - **WebSocket**: Bidirectional communication based on SuperSocket WebSocket - **HTTP/HTTPS**: HTTP service based on Kestrel, supporting Swagger documentation, CORS, health checks - **KCP**: Reliable UDP transport promoted to officially supported (opt-in); when `KcpPort` is `0` it shares the TCP port -- **Cross-Process Messaging**: Built-in RemoteMessaging module with circuit breaker, retry strategy, and consistent hashing sharding +- **Cross-Process Messaging**: Point-to-point inter-server RPC over the `GameFrameX.ServerLink` thin facade (direct dialing with a fixed retry limit, envelope forwarding, and player-route resolution built in); handshake version check and inter-node HMAC authentication included #### Database & Persistence - -- **Dual Database Providers**: `DatabaseProvider` selects `Mongo` (default) or `PostgreSql`; both providers share the same `GameFrameX.DataBase` abstraction layer +- **Database Provider Tiers**: PostgreSQL and MongoDB as dual mainlines (both fully verified — conditional writes, translatable-subset queries, and transaction atomicity run green on both as a release gate) plus SQLite as the zero-dependency onboarding + testing tier - **MongoDB Provider**: Complete MongoDB integration with health state machine (Healthy → Degraded → Unhealthy → Recovering) - **PostgreSQL Provider**: Based on Npgsql, with the same retry / recovery / availability / health-check capabilities as the MongoDB provider - **Transparent Persistence**: StateComponent automatic serialization/deserialization, persisted through timed batch upsert operations @@ -112,7 +111,7 @@ GameFrameX Server is a high-performance, cross-platform game server framework bu ### Requirements - [.NET 10.0 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) only. .NET 8/9 are not supported. -- Zero-dependency start: nothing else (SQLite is embedded). Full production providers remain MongoDB (default) or PostgreSQL via `--DatabaseProvider`. +- Zero-dependency start: nothing else (SQLite is embedded, and the sample `Configs/app_config.json` defaults to it). Full production providers are MongoDB and PostgreSQL — pick one by editing the two selection lines in the config file (see [Database Provider Tiers and Boundaries](#database-provider-tiers-and-boundaries)). - Visual Studio 2022 or JetBrains Rider (recommended) ### Installation @@ -123,39 +122,48 @@ GameFrameX Server is a high-performance, cross-platform game server framework bu cd GameFrameX.Server.Source ``` -2. **Five-Minute Zero-Dependency Start (SQLite)** +2. **Build and Enter the Output Directory** - No database install, no Docker — one command boots all roles in a single process: + The launcher resolves `Configs/` and `hotfix/` relative to its working directory, so run it from + the build output (this is also where `quick_start-game.bat` lives): ```bash - dotnet run --project GameFrameX.Launcher -- \ + dotnet build + cp -r Configs bin/app_debug/Configs + cd bin/app_debug + ``` + +3. **Five-Minute Zero-Dependency Start (SQLite)** + + No database install, no Docker — one command boots all roles in a single process (the sample + config already defaults to SQLite, so the CLI values and the file agree): + ```bash + dotnet GameFrameX.Launcher.dll -- \ --AllInOne \ --DatabaseProvider=Sqlite \ --DataBaseUrl="Data Source=data/gameframex.db" ``` - - The startup log prints the HTTP entry (`http://localhost:28080/health` for the health check) and the resolved **absolute path of the data file** with its read/write checks. + - The startup log prints the HTTP entry and the resolved **absolute path of the data file** with its read/write checks. + - Health check: `http://localhost:28080/health` (liveness probe: `/alive`) — the sample config enables development mode, which maps these endpoints (turn `HttpIsDevelopment` off for production; see the security note in `ServiceDefaultsExtensions`). - Data lands in `data/gameframex.db` under the working directory (aligned with the Docker `/app/data` volume root). Stop and restart the process — accounts and state are still there. - Want an ephemeral scratch database instead? Use `--DataBaseUrl="Data Source=:memory:"` — the startup log then warns that **nothing is persisted** (everything is lost when the process exits). - See [SQLite Provider Boundaries](#sqlite-provider-boundaries) before scaling this beyond a single process. -3. **Build the Project** - ```bash - dotnet build - ``` - 4. **Start with MongoDB / PostgreSQL (full providers)** + The sample `Configs/app_config.json` defaults to the zero-dependency SQLite tier; provider + selection is a two-line file edit (the startup validator requires CLI arguments and the config + file to agree, so the file is the selection carrier): ```bash - # MongoDB (default provider) + # 1. Start the database (MongoDB shown; PostgreSQL works the same way) docker run -d -p 27017:27017 --name mongo mongo:8.2 - dotnet run --project GameFrameX.Launcher -- \ - --ServerType=Game \ - --ServerId=1000 \ - --OuterPort=29100 \ - --HttpPort=28080 \ - --DataBaseUrl=mongodb://127.0.0.1:27017 \ - --DataBaseName=gameframex + # 2. Switch the selection in Configs/app_config.json for every role you launch: + # "DatabaseProvider": "Mongo", + # "DataBaseUrl": "mongodb://127.0.0.1:27017" + # (ready-made samples: Configs/app_config.mongo.json / Configs/app_config.postgres.json) + + # 3. Run + dotnet GameFrameX.Launcher.dll -- --ServerType=Game ``` - PostgreSQL: add `--DatabaseProvider=PostgreSql` and point `--DataBaseUrl` at your instance. 5. **Verify Startup** - Health check: `http://localhost:28080/health` (liveness probe: `/alive`) @@ -185,6 +193,13 @@ network/SMB shares risks corruption), and prefer forward slashes in custom absol (`Data Source=/abs/path/game.db`) — one syntax that works on every platform; drive-letter backslash paths are Windows-only and a wrong one surfaces immediately in the startup full-path log. + +### Database Provider Tiers and Boundaries + +- **Three tiers**: `PostgreSql` and `Mongo` are the dual mainlines — both fully verified (conditional-write primitives, translatable-subset queries, and transaction atomicity are implemented and verified on both providers, and the contract suites must pass on both as a release gate). `Sqlite` is the zero-dependency onboarding + testing tier (the default vehicle for the quickstart/demo golden path; embedded, nothing to install) and carries no production-topology commitment (see [SQLite Provider Boundaries](#sqlite-provider-boundaries) above). +- **No data-migration tooling**: the repository ships no Mongo ↔ PostgreSQL data migration. Switching providers means choosing one for a fresh install or a new server (two lines of configuration); migrating an existing production database to another provider is your responsibility. +- **Dual-mainline maintenance cost**: every future database feature is implemented and verified on both mainlines (roughly ×1.5–2 the maintenance surface of a single mainline). The contract suites run on PostgreSQL + MongoDB in CI, so regressions are caught by the dual-green gate. + --- ## Usage Examples @@ -245,8 +260,8 @@ GameFrameX uses command-line arguments (`--Key=Value`) for configuration. All co | Option | Description | Default | Example | |:-------------------|:--------------------------|:--------|:----------------------------| -| `DatabaseProvider` | Database provider | `Mongo` | `PostgreSql` | -| `DataBaseUrl` | Database connection string | None | `mongodb://localhost:27017` | +| `DatabaseProvider` | Database provider | `Sqlite` | `Mongo`, `PostgreSql` | +| `DataBaseUrl` | Database connection string | None | `Data Source=data/gameframex.db` | | `DataBaseName` | Database name | None | `gameframex` | | `DataBasePassword` | Database password | None | `your_password` | diff --git a/README.zh-CN.md b/README.zh-CN.md index d98892af1..ed80270e9 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -91,7 +91,7 @@ GameFrameX Server 是基于 C# .NET 10.0 开发的高性能、跨平台游戏服 #### 数据库与持久化 -- **双数据库 Provider**:通过 `DatabaseProvider` 选择 `Mongo`(默认)或 `PostgreSql`,两个 Provider 共享同一套 `GameFrameX.DataBase` 抽象层 +- **数据库 Provider 三档**:`PostgreSql` 与 `Mongo` 为双主线(两家均全验证——条件写原语、可翻译子集查询、事务原子性在两家双绿,作为发布门禁),外加 `Sqlite` 零依赖上手 + 测试档 - **MongoDB Provider**:完整的 MongoDB 集成,支持健康状态机(Healthy → Degraded → Unhealthy → Recovering) - **PostgreSQL Provider**:基于 Npgsql,具备与 MongoDB Provider 相同的重试 / 恢复 / 可用性 / 健康检查能力 - **透明持久化**:StateComponent 自动序列化/反序列化,通过定时批量 upsert 操作持久化 @@ -112,7 +112,7 @@ GameFrameX Server 是基于 C# .NET 10.0 开发的高性能、跨平台游戏服 ### 环境要求 - 仅支持 [.NET 10.0 SDK](https://dotnet.microsoft.com/download/dotnet/10.0),不支持 .NET 8/9。 -- [MongoDB 4.x+](https://www.mongodb.com/try/download/community)(默认 Provider;也可通过 `--DatabaseProvider=PostgreSql` 使用 PostgreSQL) +- 零依赖启动无需安装任何数据库(SQLite 内嵌,示例配置 `Configs/app_config.json` 默认即 Sqlite);完整生产 Provider 为 MongoDB 与 PostgreSQL,仅在选用对应 Provider 时才需要安装——通过修改配置文件中的两行选择项切换(见[数据库 Provider 三档定位与边界](#数据库-provider-三档定位与边界)) - Visual Studio 2022 或 JetBrains Rider(推荐) ### 安装 @@ -123,37 +123,47 @@ GameFrameX Server 是基于 C# .NET 10.0 开发的高性能、跨平台游戏服 cd GameFrameX.Server.Source ``` -2. **还原依赖** - ```bash - dotnet restore - ``` +2. **构建并进入输出目录** -3. **构建项目** + 启动器以工作目录为基准解析 `Configs/` 与 `hotfix/`,因此请从构建输出目录运行(`quick_start-game.bat` 也在该目录): ```bash dotnet build + cp -r Configs bin/app_debug/Configs + cd bin/app_debug ``` -4. **启动 MongoDB** - ```bash - # 本地安装方式 - mongod --dbpath /path/to/data +3. **五分钟零依赖启动(SQLite)** - # 或使用 Docker - docker run -d -p 27017:27017 --name mongo mongo:8.2 + 无需安装数据库、无需 Docker——一条命令在单进程中拉起全部角色(示例配置默认即 SQLite,命令行取值与配置文件一致): + ```bash + dotnet GameFrameX.Launcher.dll -- \ + --AllInOne \ + --DatabaseProvider=Sqlite \ + --DataBaseUrl="Data Source=data/gameframex.db" ``` + - 启动日志会打印 HTTP 入口以及解析出的**数据文件绝对路径**和它的读写检查结果。 + - 健康检查:`http://localhost:28080/health`(存活探针:`/alive`)——示例配置开启了开发模式才会映射这些端点(生产环境请关闭 `HttpIsDevelopment`;安全说明见 `ServiceDefaultsExtensions`)。 + - 数据落在工作目录下的 `data/gameframex.db`(与 Docker 的 `/app/data` 卷根对齐)。停止并重启进程,账号与状态依然存在。 + - 想要一个用完即弃的临时数据库?改用 `--DataBaseUrl="Data Source=:memory:"`——启动日志会警告**不做任何持久化**(进程退出后全部丢失)。 + - 在把部署规模扩展到单进程之外前,请先阅读[数据库 Provider 三档定位与边界](#数据库-provider-三档定位与边界)。 + +4. **使用 MongoDB / PostgreSQL 启动(完整 Provider)** -5. **运行服务器** + 示例 `Configs/app_config.json` 默认为零依赖的 SQLite 档;切换 Provider 只需改配置文件中的两行选择项(启动校验器要求命令行参数与配置文件一致,因此配置文件才是选择载体): ```bash - dotnet run --project GameFrameX.Launcher -- \ - --ServerType=Game \ - --ServerId=1000 \ - --OuterPort=29100 \ - --HttpPort=28080 \ - --DataBaseUrl=mongodb://127.0.0.1:27017 \ - --DataBaseName=gameframex + # 1. 启动数据库(以 MongoDB 为例;PostgreSQL 同理) + docker run -d -p 27017:27017 --name mongo mongo:8.2 + + # 2. 修改 Configs/app_config.json 中的选择项(对每个要启动的角色都要生效): + # "DatabaseProvider": "Mongo", + # "DataBaseUrl": "mongodb://127.0.0.1:27017" + # (现成样例:Configs/app_config.mongo.json / Configs/app_config.postgres.json) + + # 3. 运行 + dotnet GameFrameX.Launcher.dll -- --ServerType=Game ``` -6. **验证启动** +5. **验证启动** - 健康检查:`http://localhost:28080/health`(存活探针:`/alive`) - 查看控制台日志确认启动成功 @@ -217,11 +227,17 @@ GameFrameX 使用命令行参数 (`--Key=Value`) 进行配置,所有配置项 | 配置项 | 说明 | 默认值 | 示例 | |:------|:-----|:------|:----| -| `DatabaseProvider` | 数据库 Provider | `Mongo` | `PostgreSql` | +| `DatabaseProvider` | 数据库 Provider | `Sqlite` | `PostgreSql` | | `DataBaseUrl` | 数据库连接字符串 | 无 | `mongodb://localhost:27017` | | `DataBaseName` | 数据库名称 | 无 | `gameframex` | | `DataBasePassword` | 数据库密码 | 无 | `your_password` | +#### 数据库 Provider 三档定位与边界 + +- **三档定位**:`PostgreSql` 与 `Mongo` 为双主线全验证档——条件写原语、可翻译子集查询、事务原子性等全部特性在两家 Provider 双实现双验证,契约套件双绿是发布门禁;`Sqlite` 为零依赖上手 + 测试档(quickstart / demo 黄金路径的默认载体,嵌入式、无需安装任何数据库),不承诺生产拓扑。 +- **无数据迁移工具**:仓库不提供 Mongo ↔ PostgreSQL 的数据搬迁实现。切换 Provider 是新装/新服的选型动作(改两行配置);存量生产库换型需自行完成数据搬迁。 +- **双主线维护代价**:后续每个数据库特性都要在两家 Provider 双实现、双验证(维护面约为单主线的 ×1.5–2);契约测试套件在 CI 中于 PostgreSQL + MongoDB 双跑,回归由双绿门禁兜底。 + #### Actor 配置 | 配置项 | 说明 | 默认值 | 示例 | diff --git a/README.zh-TW.md b/README.zh-TW.md index 1e6175106..cec7756e7 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -91,7 +91,7 @@ GameFrameX Server 是基於 C# .NET 10.0 開發的高效能、跨平臺遊戲伺 #### 資料庫與持久化 -- **雙資料庫 Provider**:`DatabaseProvider` 可選 `Mongo`(預設)或 `PostgreSql`,兩者共用同一 `GameFrameX.DataBase` 抽象層 +- **資料庫 Provider 三檔**:`PostgreSql` 與 `Mongo` 為雙主線全驗證 Provider(條件寫、可翻譯子集查詢、事務原子性在兩家皆實作並驗證,作為發布門檻),`Sqlite` 為零依賴上手 + 測試檔(quickstart 預設),三者共用同一 `GameFrameX.DataBase` 抽象層 - **MongoDB Provider**:完整的 MongoDB 整合,支援健康狀態機(Healthy → Degraded → Unhealthy → Recovering) - **PostgreSQL Provider**:基於 Npgsql,具備與 MongoDB Provider 同等的重試 / 復原 / 可用性 / 健康檢查能力 - **透明持久化**:StateComponent 自動序列化/反序列化,透過定時批次 upsert 操作持久化 @@ -112,7 +112,7 @@ GameFrameX Server 是基於 C# .NET 10.0 開發的高效能、跨平臺遊戲伺 ### 環境要求 - 僅支援 [.NET 10.0 SDK](https://dotnet.microsoft.com/download/dotnet/10.0),不支援 .NET 8/9。 -- [MongoDB 4.x+](https://www.mongodb.com/try/download/community)(預設 Provider;亦可透過 `--DatabaseProvider=PostgreSql` 使用 PostgreSQL) +- 零依賴啟動:無需安裝任何其他軟體(SQLite 為嵌入式,範例 `Configs/app_config.json` 即預設使用)。完整生產級 Provider 為 MongoDB 與 PostgreSQL——透過修改設定檔中的兩行選型即可選用(見[資料庫 Provider 三檔定位與邊界](#資料庫-provider-三檔定位與邊界)) - Visual Studio 2022 或 JetBrains Rider(推薦) ### 安裝 @@ -123,40 +123,51 @@ GameFrameX Server 是基於 C# .NET 10.0 開發的高效能、跨平臺遊戲伺 cd GameFrameX.Server.Source ``` -2. **還原相依套件** - ```bash - dotnet restore - ``` +2. **建置並進入輸出目錄** -3. **建置專案** + 啟動器以工作目錄為基準解析 `Configs/` 與 `hotfix/`,因此請在建置輸出目錄中執行(`quick_start-game.bat` 也位於此): ```bash dotnet build + cp -r Configs bin/app_debug/Configs + cd bin/app_debug ``` -4. **啟動 MongoDB** - ```bash - # 本地安裝方式 - mongod --dbpath /path/to/data +3. **五分鐘零依賴啟動(SQLite)** - # 或使用 Docker - docker run -d -p 27017:27017 --name mongo mongo:8.2 + 無需安裝資料庫、無需 Docker——單一命令以單一程序啟動全部角色(範例設定檔已預設 SQLite,因此 CLI 參數與檔案內容一致): + ```bash + dotnet GameFrameX.Launcher.dll -- \ + --AllInOne \ + --DatabaseProvider=Sqlite \ + --DataBaseUrl="Data Source=data/gameframex.db" ``` - -5. **執行伺服器** + - 啟動日誌會印出 HTTP 入口與資料檔的**絕對路徑**及其讀寫檢查結果。 + - 健康檢查:`http://localhost:28080/health`(存活探針:`/alive`)——範例設定檔開啟了開發模式才映射這些端點(生產環境請關閉 `HttpIsDevelopment`;詳見 `ServiceDefaultsExtensions` 中的安全說明)。 + - 資料落地於工作目錄下的 `data/gameframex.db`(與 Docker `/app/data` 卷冊根目錄對齊)。停止並重啟程序——帳號與狀態仍然存在。 + - 想要拋棄式的暫存資料庫?改用 `--DataBaseUrl="Data Source=:memory:"`——啟動日誌會警告**不會持久化任何資料**(程序結束即全部丟失)。 + - 要將其擴展到單一程序之外之前,請先閱讀 [SQLite Provider 邊界](#資料庫-provider-三檔定位與邊界)。 + +4. **改用 MongoDB / PostgreSQL 啟動(完整 Provider)** + 範例 `Configs/app_config.json` 預設為零依賴的 SQLite 檔;Provider 選型是兩行的設定檔修改(啟動驗證器要求 CLI 參數與設定檔一致,因此設定檔是選型載體): ```bash - dotnet run --project GameFrameX.Launcher -- \ - --ServerType=Game \ - --ServerId=1000 \ - --OuterPort=29100 \ - --HttpPort=28080 \ - --DataBaseUrl=mongodb://127.0.0.1:27017 \ - --DataBaseName=gameframex + # 1. 啟動資料庫(此處以 MongoDB 為例;PostgreSQL 方式相同) + docker run -d -p 27017:27017 --name mongo mongo:8.2 + + # 2. 修改 Configs/app_config.json 中每個要啟動的角色的選型: + # "DatabaseProvider": "Mongo", + # "DataBaseUrl": "mongodb://127.0.0.1:27017" + # (現成範例:Configs/app_config.mongo.json / app_config.postgres.json) + + # 3. 執行 + dotnet GameFrameX.Launcher.dll -- --ServerType=Game ``` -6. **驗證啟動** +5. **驗證啟動** - 健康檢查:`http://localhost:28080/health`(存活探針:`/alive`) - 檢視控制檯日誌確認啟動成功 + **零 JSON 黃金路徑**:不撰寫任何 `Online.Settings` 即可啟動伺服器,範例 RPS 鏈路(配對 → 對局 → 結算 → 發獎 → 排行榜)開箱即用——`MatchSettledBoardId` 會投影到預設排行榜 `match-settled`(組件裝配期間預先建立)。若要關閉投影,請在 `Online.Settings` 下將 `online-competition.LeaderboardProjection.MatchSettledBoardId` 明確留空。 + --- ## 使用範例 @@ -210,11 +221,17 @@ GameFrameX 使用命令列參數 (`--Key=Value`) 進行配置,所有配置項 | 配置項 | 說明 | 預設值 | 範例 | |:------|:-----|:------|:----| -| `DatabaseProvider` | 資料庫 Provider | `Mongo` | `PostgreSql` | +| `DatabaseProvider` | 資料庫 Provider | `Sqlite` | `Mongo`、`PostgreSql` | | `DataBaseUrl` | 資料庫連線字串 | 無 | `mongodb://localhost:27017` | | `DataBaseName` | 資料庫名稱 | 無 | `gameframex` | | `DataBasePassword` | 資料庫密碼 | 無 | `your_password` | +#### 資料庫 Provider 三檔定位與邊界 + +- **三檔定位**:`PostgreSql` 與 `Mongo` 為雙主線全驗證檔——條件寫原語、可翻譯子集查詢、事務原子性等全部特性在兩家 Provider 雙實作雙驗證,契約套件雙綠是發布門檻;`Sqlite` 為零依賴上手 + 測試檔(quickstart / demo 黃金路徑的預設載體,嵌入式、無需安裝任何資料庫),不承諾生產拓撲。 +- **無資料遷移工具**:倉庫不提供 Mongo ↔ PostgreSQL 的資料搬遷實作。切換 Provider 是新裝/新服的選型動作(改兩行設定);既有生產庫換型需自行完成資料搬遷。 +- **雙主線維護成本**:後續每個資料庫特性都要在兩家 Provider 雙實作、雙驗證(維護面約為單主線的 ×1.5–2);契約測試套件在 CI 中於 PostgreSQL + MongoDB 雙跑,回歸由雙綠門檻兜底。 + #### Actor 配置 | 配置項 | 說明 | 預設值 | 範例 | @@ -740,7 +757,7 @@ dotnet test --logger "console;verbosity=detailed" ├─────────────────────────────────────────────────────────────────┤ │ 資料庫層 │ │ ┌─────────────────────────────────────────────────────────┐ │ -│ │ MongoDB (default) / PostgreSQL │ │ +│ │ PostgreSQL / MongoDB (mainlines) + SQLite │ │ │ └─────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ``` diff --git a/Server.slnx b/Server.slnx index e080d1a38..8faf39d9e 100644 --- a/Server.slnx +++ b/Server.slnx @@ -52,6 +52,7 @@ + diff --git a/Tests/GameFrameX.Tests/Discovery/PlayerRouteWiringTests.cs b/Tests/GameFrameX.Tests/Discovery/PlayerRouteWiringTests.cs index 3a6783064..0f9879422 100644 --- a/Tests/GameFrameX.Tests/Discovery/PlayerRouteWiringTests.cs +++ b/Tests/GameFrameX.Tests/Discovery/PlayerRouteWiringTests.cs @@ -140,7 +140,7 @@ public async Task AttachLocalDispatcher_AfterInitialize_InstallsCase1DispatcherI } [Fact] - public async Task AttachLocalDispatcher_SecondCall_IsNoOpAndKeepsFirstDispatcher() + public async Task AttachLocalDispatcher_SecondCall_ReplacesWithNewestDispatcher() { var remoteRouter = new RecordingRemoteRouter(); DiscoveryRoutingWire.SimulateInitializedForTest(new[] { "Game" }, remoteRouter); @@ -153,8 +153,10 @@ public async Task AttachLocalDispatcher_SecondCall_IsNoOpAndKeepsFirstDispatcher var envelope = new MessageEnvelope("Game", new WiringTestMessage { PlayerId = 1001 }); await RoleRouterHolder.Current.RouteAsync(envelope); - Assert.Single(first.Received); - Assert.Empty(second.Received); + // 与 UnifiedMessageSenderHolder「重复调用覆盖为最新实例」同口径: + // 本地信封复投槽取最新 dispatcher,保证与玩家级投递共用同一发送器。 + Assert.Empty(first.Received); + Assert.Same(envelope, Assert.Single(second.Received)); } [Fact] diff --git a/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj b/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj index f7324b7fc..a81139a4d 100644 --- a/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj +++ b/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj @@ -52,6 +52,7 @@ + diff --git a/Tests/GameFrameX.Tests/RemoteMessaging/InterServerKcpTransportTests.cs b/Tests/GameFrameX.Tests/RemoteMessaging/InterServerKcpTransportTests.cs index 691c5783a..76a65cf4e 100644 --- a/Tests/GameFrameX.Tests/RemoteMessaging/InterServerKcpTransportTests.cs +++ b/Tests/GameFrameX.Tests/RemoteMessaging/InterServerKcpTransportTests.cs @@ -232,6 +232,7 @@ public async Task KcpEndpoint_TwoNodeRoundTrip_ResponsesMatchRequestIdentity() .WithRouteTable(_routeTable) .UseKcpTransportAdapter() .WithTimeoutMs(15000) + .WithRetry(2) .Build(); for (var attempt = 1; attempt <= 3; attempt++) @@ -263,7 +264,7 @@ public async Task TransportMatrix_TcpKcpAndMigration_ProduceEquivalentResponses( // 腿一:仅配 tcp 键(现状部署形态) SetEnvironmentEndpoint(serviceName, "tcp", $"tcp://127.0.0.1:{_tcpPort}"); - var tcpClient = new RemoteMessagingBuilder().WithRouteTable(_routeTable).WithTimeoutMs(15000).Build(); + var tcpClient = new RemoteMessagingBuilder().WithRouteTable(_routeTable).WithTimeoutMs(15000).WithRetry(2).Build(); foreach (var identity in identities) { var request = new ReqInnerFriendByAdd { PlayerId = IdentityBase + identity, SourcePlayerId = identity }; @@ -278,6 +279,7 @@ public async Task TransportMatrix_TcpKcpAndMigration_ProduceEquivalentResponses( .WithRouteTable(_routeTable) .UseKcpTransportAdapter() .WithTimeoutMs(15000) + .WithRetry(2) .Build(); foreach (var (identity, tcpSuccess, tcpErrorCode) in observed) { diff --git a/Tests/GameFrameX.Tests/RemoteMessaging/ProtocolVersionNegotiationMatrixTests.cs b/Tests/GameFrameX.Tests/RemoteMessaging/ProtocolVersionNegotiationMatrixTests.cs index 2584d7a24..a9b4cde64 100644 --- a/Tests/GameFrameX.Tests/RemoteMessaging/ProtocolVersionNegotiationMatrixTests.cs +++ b/Tests/GameFrameX.Tests/RemoteMessaging/ProtocolVersionNegotiationMatrixTests.cs @@ -88,6 +88,7 @@ public async Task SameMajor_HandshakeExchanged_CallSucceedsWithIdentity() var client = new RemoteMessagingBuilder() .WithRouteTable(_routeTable) .WithTimeoutMs(15000) + .WithRetry(2) .Build(); for (var attempt = 1; attempt <= 3; attempt++) @@ -119,6 +120,7 @@ public async Task CrossMajor_ClientVersion1_ServerVersion2_ConnectionRejected() var client = new RemoteMessagingBuilder() .WithRouteTable(_routeTable) .WithTimeoutMs(15000) + .WithRetry(2) .Build(); var request = new ReqInnerFriendByAdd { PlayerId = IdentityBase + 1, SourcePlayerId = 42 }; @@ -167,29 +169,6 @@ public async Task MixedWindow_LegacyServer_HandshakeTimeout_FallsBackAndCallSucc Assert.True(_businessMessages.TryGetValue("legacy", out var legacyCount) && legacyCount >= 1, "business message must reach the legacy server after fallback"); } - // ───────────────────────────────────────────────────────────── - // ④ 消息级标注消费:标注 major 2 的消息对 major 1 对端拒绝发送 - // ───────────────────────────────────────────────────────────── - - [Fact] - public async Task MessageAnnotation_MajorBeyondRemote_IsRejectedBeforeSending() - { - const string serviceName = "C252Annotation"; - SetEnvironmentEndpoint(serviceName, $"tcp://127.0.0.1:{_v1Port}"); - - var client = new RemoteMessagingBuilder() - .WithRouteTable(_routeTable) - .WithTimeoutMs(15000) - .Build(); - - var request = new AnnotatedMajor2Message { PlayerId = IdentityBase + 1 }; - var result = await client.CallWithResultAsync(serviceName, request); - - // 协商远端为 (1,0):标注 (2,0) 的消息必须在发送前被拒绝,且不进入服务端业务面 - Assert.Equal(RemoteStatusCode.ProtocolVersionIncompatible, result.StatusCode); - Assert.Null(result.Response); - Assert.False(_businessMessages.TryGetValue("v1", out var v1Count) && v1Count > 0, "annotated business message must not be sent to the major-1 peer"); - } /// /// 启动一条 TCP 接收面:握手短路行为可注入(null = 旧节点不回);业务消息按身份回写并计数。 @@ -288,24 +267,6 @@ private async ValueTask PackageHandler( } } - /// - /// 标注 (2,0) 的测试业务消息:对 major 1 对端必须拒绝发送。 - /// - /// - /// A test business message annotated (2,0): sending it to a major-1 peer must be rejected. - /// - [ProtoContract] - [ProtocolVersion(2, 0)] - private sealed class AnnotatedMajor2Message : GameFrameX.Network.Messages.MessageObject, GameFrameX.Network.Abstractions.IRequestMessage - { - [ProtoMember(1)] - public long PlayerId { get; set; } - - public override void Clear() - { - PlayerId = 0; - } - } /// /// 与生产 ProtocolVersionNegotiationServer 同宽限语义:拒绝包先送达,再关闭会话。 diff --git a/Tests/GameFrameX.Tests/RemoteMessaging/ProtocolVersionNegotiationTests.cs b/Tests/GameFrameX.Tests/RemoteMessaging/ProtocolVersionNegotiationTests.cs index 7225e716e..b9280506e 100644 --- a/Tests/GameFrameX.Tests/RemoteMessaging/ProtocolVersionNegotiationTests.cs +++ b/Tests/GameFrameX.Tests/RemoteMessaging/ProtocolVersionNegotiationTests.cs @@ -6,101 +6,40 @@ namespace GameFrameX.Tests.RemoteMessaging; /// -/// 协议版本协商契约测试:版本来源模型(连接级常量 + 消息级标注)、协商器 major 比较语义、 -/// 握手消息对形状(ID 段位 / Proto 往返 / 请求响应标记)与首批标注守护。 +/// 协议版本握手契约测试:版本来源模型(连接级常量)、握手消息对形状(ID 段位 / Proto 往返 / 请求响应标记)。 +/// 多版本协商灰度面(协商器抽象 + 消息级版本标注)已收缩移除,仅保留握手帧最小版本号校验。 /// /// -/// Contract tests for the protocol version negotiation: the version source model (the -/// connection-level constant plus message-level attributes), the negotiator's major-comparison -/// semantics, the handshake message pair shape (id segment, protobuf round trip, request/response -/// markers), and the first-batch annotation guard. +/// Contract tests for the protocol version handshake: the version source model (the +/// connection-level constant) and the handshake message pair shape (id segment, protobuf round +/// trip, request/response markers). The multi-version negotiation surface (the negotiator +/// abstraction plus message-level version attributes) has been removed by the in-place shrink; +/// only the handshake frame's minimal version check remains. /// public sealed class ProtocolVersionNegotiationTests { - [Fact] - public void ConnectionCompatibility_SameMajor_IsCompatible() - { - var negotiator = new DefaultProtocolVersionNegotiator(); - - Assert.True(negotiator.IsConnectionCompatible(new ProtocolVersion(1, 0), new ProtocolVersion(1, 0))); - Assert.True(negotiator.IsConnectionCompatible(new ProtocolVersion(1, 0), new ProtocolVersion(1, 9))); - Assert.True(negotiator.IsConnectionCompatible(new ProtocolVersion(2, 3), new ProtocolVersion(2, 0))); - } - - [Fact] - public void ConnectionCompatibility_CrossMajor_IsRejected() - { - var negotiator = new DefaultProtocolVersionNegotiator(); - - // 拒绝语义无方向豁免:任一侧更高 major 都判不兼容 - Assert.False(negotiator.IsConnectionCompatible(new ProtocolVersion(1, 0), new ProtocolVersion(2, 0))); - Assert.False(negotiator.IsConnectionCompatible(new ProtocolVersion(2, 0), new ProtocolVersion(1, 0))); - } - - [Fact] - public void MessageCompatibility_Unannotated_IsAlwaysCompatible() - { - var negotiator = new DefaultProtocolVersionNegotiator(); - - // 未标注消息 = 基础契约,对任意远端版本放行(既有消息路径行为不变红线) - Assert.True(negotiator.IsMessageCompatible(typeof(UnannotatedDummyMessage), new ProtocolVersion(1, 0))); - Assert.True(negotiator.IsMessageCompatible(typeof(UnannotatedDummyMessage), new ProtocolVersion(9, 9))); - } - - [Fact] - public void MessageCompatibility_Annotated_FollowsRemoteMajor() - { - var negotiator = new DefaultProtocolVersionNegotiator(); - - // 消息标注 major <= 远端协商 major 即兼容(minor 不阻断:protobuf 向后兼容演进) - Assert.True(negotiator.IsMessageCompatible(typeof(RoleRouteEnvelopeMessage), new ProtocolVersion(1, 0))); - Assert.True(negotiator.IsMessageCompatible(typeof(AnnotatedV1DummyMessage), new ProtocolVersion(2, 3))); - - // 消息比远端新(major 更高)→ 拒绝 - Assert.False(negotiator.IsMessageCompatible(typeof(AnnotatedV2DummyMessage), new ProtocolVersion(1, 9))); - } - - [Fact] - public void GetVersion_ReturnsAttributeVersion_OrZeroDotZero() - { - var negotiator = new DefaultProtocolVersionNegotiator(); - - Assert.Equal("1.0", negotiator.GetVersion(typeof(RoleRouteEnvelopeMessage))); - Assert.Equal("0.0", negotiator.GetVersion(typeof(UnannotatedDummyMessage))); - } - [Fact] public void ProtocolVersionConstants_SingleSourceOfTruth() { - // 连接级协议版本单一事实源:协商能力首版 = (1,0);协商能力落地前的部署等效版本同为 (1,0) - Assert.Equal(new ProtocolVersion(1, 0), RemoteMessagingProtocolVersion.Current); - Assert.Equal(new ProtocolVersion(1, 0), RemoteMessagingProtocolVersion.Legacy); - } - - [Fact] - public void FirstBatchContractMessages_CarryProtocolVersionAttribute() - { - // 首批标注:跨进程路由信封 + 握手消息对,全部 (1,0) - AssertVersionAttribute(RoleRouteEnvelopeMessage.ReservedMessageId, 1, 0, typeof(RoleRouteEnvelopeMessage)); - AssertVersionAttribute(ReqProtocolVersionNegotiation.ReservedMessageId, 1, 0, typeof(ReqProtocolVersionNegotiation)); - AssertVersionAttribute(RespProtocolVersionNegotiation.ReservedMessageId, 1, 0, typeof(RespProtocolVersionNegotiation)); + Assert.Equal(1, RemoteMessagingProtocolVersion.Current.Major); + Assert.Equal(0, RemoteMessagingProtocolVersion.Current.Minor); + Assert.Equal(RemoteMessagingProtocolVersion.Current, RemoteMessagingProtocolVersion.Legacy); } [Fact] public void HandshakeMessageIds_OccupyInnerSegmentMinus130_SubIds11And12() { - // -130 内部段:子号 10 = 路由信封(既有),11/12 = 握手 Req/Resp - Assert.Equal(unchecked((int)((-130 << 16) + 11)), ReqProtocolVersionNegotiation.ReservedMessageId); - Assert.Equal(unchecked((int)((-130 << 16) + 12)), RespProtocolVersionNegotiation.ReservedMessageId); - Assert.NotEqual(RoleRouteEnvelopeMessage.ReservedMessageId, ReqProtocolVersionNegotiation.ReservedMessageId); - Assert.NotEqual(RoleRouteEnvelopeMessage.ReservedMessageId, RespProtocolVersionNegotiation.ReservedMessageId); + Assert.Equal(-130, ReqProtocolVersionNegotiation.ReservedMessageId >> 16); + Assert.Equal(11, ReqProtocolVersionNegotiation.ReservedMessageId & 0xFFFF); + Assert.Equal(-130, RespProtocolVersionNegotiation.ReservedMessageId >> 16); + Assert.Equal(12, RespProtocolVersionNegotiation.ReservedMessageId & 0xFFFF); } [Fact] public void HandshakeMessages_ImplementRequestResponseMarkers() { - Assert.True(typeof(GameFrameX.Network.Abstractions.IRequestMessage).IsAssignableFrom(typeof(ReqProtocolVersionNegotiation))); - Assert.True(typeof(GameFrameX.Network.Abstractions.IResponseMessage).IsAssignableFrom(typeof(RespProtocolVersionNegotiation))); + Assert.IsAssignableFrom(new ReqProtocolVersionNegotiation()); + Assert.IsAssignableFrom(new RespProtocolVersionNegotiation()); } [Fact] @@ -121,60 +60,28 @@ public void HandshakeMessages_RoundTripPreservesVersionIdentity() } [Fact] - public void AnnotatedMessageMajor_NeverExceedsCurrentProtocolMajor() + public void HandshakeRejection_SameMajorOnly_MajorMismatchRejected() { - // 标注守护:本程序集内任何消息标注的 major 都不得超过协议当前 major(防标注跑在常量前面) - foreach (var type in typeof(RoleRouteEnvelopeMessage).Assembly.GetTypes()) - { - var attribute = (ProtocolVersionAttribute)Attribute.GetCustomAttribute(type, typeof(ProtocolVersionAttribute)); - if (attribute != null) - { - Assert.True(attribute.Major <= RemoteMessagingProtocolVersion.Current.Major, - $"{type.FullName} annotates major {attribute.Major} beyond current protocol major {RemoteMessagingProtocolVersion.Current.Major}"); - } - } - } + var local = RemoteMessagingProtocolVersion.Current; + var sameMajorPeer = new ProtocolVersion(local.Major, local.Minor + 1); + var crossMajorPeer = new ProtocolVersion(local.Major + 1, local.Minor); - [Fact] - public void RemoteStatusCode_ExposesProtocolVersionIncompatible() - { - // 拒绝语义的显式可观测状态码(区别于 UnexpectedResponse 等泛化错误) - Assert.Equal(12, (int)RemoteStatusCode.ProtocolVersionIncompatible); - } - - private static void AssertVersionAttribute(int messageId, int expectedMajor, int expectedMinor, Type type) - { - var attribute = (ProtocolVersionAttribute)Attribute.GetCustomAttribute(type, typeof(ProtocolVersionAttribute)); - Assert.NotNull(attribute); - Assert.Equal(expectedMajor, attribute.Major); - Assert.Equal(expectedMinor, attribute.Minor); + Assert.Equal(sameMajorPeer.Major, local.Major); + Assert.NotEqual(crossMajorPeer.Major, local.Major); - // 消息 ID 与标注同时存在([MessageTypeHandler] 负责注册表可解码性) - var handler = (GameFrameX.Network.Abstractions.MessageTypeHandlerAttribute)Attribute.GetCustomAttribute(type, typeof(GameFrameX.Network.Abstractions.MessageTypeHandlerAttribute)); - Assert.NotNull(handler); - Assert.Equal(messageId, handler.MessageId); - } + var replySameMajor = ProtocolVersionNegotiationServer.BuildReply( + new ReqProtocolVersionNegotiation { Major = sameMajorPeer.Major, Minor = sameMajorPeer.Minor }, local); + var replyCrossMajor = ProtocolVersionNegotiationServer.BuildReply( + new ReqProtocolVersionNegotiation { Major = crossMajorPeer.Major, Minor = crossMajorPeer.Minor }, local); - [ProtocolVersion(1, 2)] - private sealed class AnnotatedV1DummyMessage : GameFrameX.Network.Messages.MessageObject - { - public override void Clear() - { - } + Assert.True(replySameMajor.Accepted); + Assert.False(replyCrossMajor.Accepted); } - [ProtocolVersion(2, 0)] - private sealed class AnnotatedV2DummyMessage : GameFrameX.Network.Messages.MessageObject - { - public override void Clear() - { - } - } - - private sealed class UnannotatedDummyMessage : GameFrameX.Network.Messages.MessageObject + [Fact] + public void RemoteStatusCode_ExposesProtocolVersionIncompatible() { - public override void Clear() - { - } + // 握手被拒仍以该状态码回执调用方(跨 major 混布禁止) + Assert.Equal(12, (int)RemoteStatusCode.ProtocolVersionIncompatible); } } diff --git a/Tests/GameFrameX.Tests/RemoteMessaging/RemoteMessageClientFailureIsolationTests.cs b/Tests/GameFrameX.Tests/RemoteMessaging/RemoteMessageClientFailureIsolationTests.cs index 0397f51cb..cb191413c 100644 --- a/Tests/GameFrameX.Tests/RemoteMessaging/RemoteMessageClientFailureIsolationTests.cs +++ b/Tests/GameFrameX.Tests/RemoteMessaging/RemoteMessageClientFailureIsolationTests.cs @@ -145,7 +145,6 @@ private static (RemoteMessageClient Client, RecordingCircuitBreaker Circuit, Rec adapter, new DefaultMessageCodec(new DefaultMessageCompressionRegistry(), 0, 512, 1024 * 1024, 1024 * 1024), new RequestResponseMatcher(), - new DefaultProtocolVersionNegotiator(), Array.Empty(), enableRetry ? retry : null, circuit, diff --git a/Tests/GameFrameX.Tests/RemoteMessaging/RemoteMessageClientPumpTests.cs b/Tests/GameFrameX.Tests/RemoteMessaging/RemoteMessageClientPumpTests.cs index 4978d7bff..ec31387e1 100644 --- a/Tests/GameFrameX.Tests/RemoteMessaging/RemoteMessageClientPumpTests.cs +++ b/Tests/GameFrameX.Tests/RemoteMessaging/RemoteMessageClientPumpTests.cs @@ -229,7 +229,6 @@ private static RemoteMessageClient CreateClient(ITransportProtocolAdapter adapte adapter, new DefaultMessageCodec(new DefaultMessageCompressionRegistry(), 0, 512, 1024 * 1024, 1024 * 1024), new RequestResponseMatcher(), - new DefaultProtocolVersionNegotiator(), Array.Empty(), null, new AllowAllCircuitBreaker(), diff --git a/Tests/GameFrameX.Tests/ServerLink/ServerLinkFacadeTests.cs b/Tests/GameFrameX.Tests/ServerLink/ServerLinkFacadeTests.cs new file mode 100644 index 000000000..60b73eb3c --- /dev/null +++ b/Tests/GameFrameX.Tests/ServerLink/ServerLinkFacadeTests.cs @@ -0,0 +1,411 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please see the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others, as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes and liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== +using System.Collections.Concurrent; +using System.Net; +using System.Net.Sockets; +using GameFrameX.Discovery.Routing; +using GameFrameX.Network.Abstractions; +using GameFrameX.Network.Abstractions; +using GameFrameX.Network.Messages; +using GameFrameX.Network.RemoteMessaging.Contracts; +using GameFrameX.Network.RemoteMessaging.Transport; +using GameFrameX.Network.RemoteMessaging.Unified; +using GameFrameX.Network.RemoteMessaging.Versioning; +using GameFrameX.Proto.Proto; +using GameFrameX.ServerLink; +using GameFrameX.Tests.RemoteMessaging; +using ProtoBuf; + +namespace GameFrameX.Tests.ServerLink; + +/// +/// ServerLink 薄门面冒烟:直连拨号 + 固定重试上限构建约束、真实 TCP 回环上的跨服 RPC、 +/// 玩家路由解析内置默认(跨服投递定向路由实例 / 本服投递走本地发送器)。 +/// +/// +/// ServerLink thin-facade smoke tests: the direct-dial build constraints with the fixed retry +/// limit, a cross-server RPC round trip over a real TCP loopback, and the built-in player-route +/// resolution (cross-server delivery targeting the routed instance; local delivery going through +/// the local player sender). +/// +public sealed class ServerLinkFacadeTests +{ + public ServerLinkFacadeTests() + { + // 生产消息注册(RemoteMessaging 测试既有口径):仅当所需消息未注册时执行, + // 避免清空式重建与并行测试类的注册表竞态 + if (MessageProtoHelper.GetMessageIdByType(typeof(ReqHeartBeat)) <= 0 || + MessageProtoHelper.GetMessageIdByType(typeof(GameFrameX.Network.RemoteMessaging.Versioning.RespProtocolVersionNegotiation)) <= 0) + { + MessageProtoHelper.Init(typeof(ReqHeartBeat).Assembly, typeof(GameFrameX.Network.RemoteMessaging.Routing.RoleRouteEnvelopeMessage).Assembly); + } + } + + [Fact] + public void Build_WithoutRouteTable_ShouldThrowInvalidOperationException() + { + Assert.Throws(() => new ServerLinkBuilder().Build()); + } + + [Fact] + public async Task CrossServerRpc_OverRealTcpLoopback_ShouldRoundTrip() + { + var echoSurface = await TcpEchoServerSurface.StartAsync(); + var routeTable = new MutableRouteTableProvider() + .SetServiceEndpoint("Social", $"tcp://127.0.0.1:{echoSurface.Port}", "social-1"); + + var client = new ServerLinkBuilder() + .WithRouteTable(routeTable) + .Build(); + + const long echoIdentity = 424242; + var request = new ReqInnerFriendByAdd { PlayerId = echoIdentity, SourcePlayerId = echoIdentity }; + var result = await client.CallWithResultAsync( + RemoteCallContext.Create("Social", 15000), request); + + Assert.True(result.IsSuccess, $"call failed: {result.StatusCode} {result.ErrorMessage}; server errors: {string.Join(" | ", echoSurface.ServerErrors)}"); + Assert.NotNull(result.Response); + Assert.True(result.Response.Success); + Assert.Equal((int)(echoIdentity % 100000), result.Response.ErrorCode); + // 回环面确实先完成握手再处理业务帧(跨服调用经完整客户端栈) + Assert.True(echoSurface.Handshakes.Count >= 1, "echo surface should have observed the protocol handshake"); + await echoSurface.DisposeAsync(); + } + + [Fact] + public void EnvelopeForwarder_WithoutRoutingInitialization_ShouldThrow() + { + if (ServerLinkEnvelopeForwarder.IsRoutingInitialized) + { + // 同进程其它测试可能已装配路由缝;本用例只守护未装配契约,已装配时跳过断言体 + return; + } + + Assert.Throws(() => + ServerLinkEnvelopeForwarder.ForwardAsync("Game", new TestMessageObject()).GetAwaiter().GetResult()); + } + + [Fact] + public async Task PlayerRouting_CrossServerOnlineRoute_ShouldForwardToRoutedInstance() + { + var captureClient = new CapturingRemoteMessageClient(); + var routeTable = new MutableRouteTableProvider() + .SetServiceEndpoint("Game", "tcp://127.0.0.1:59999", "game-77"); + var resolver = new StaticPlayerRouteResolver(GameFrameX.Discovery.Routing.PlayerRouteInfo.Online("Game", 1001, "game-77", 1)); + var localSender = new RecordingLocalPlayerSender(); + + var sender = ServerLinkPlayerRouting.ComposeUnifiedSender( + captureClient, + routeTable, + resolver, + localSender, + "Social", + "social-local-1"); + + Assert.NotNull(sender); + var message = new TestMessageObject(); + var result = await sender.SendToPlayerAsync(701, message); + + Assert.True(result.IsSuccess, $"player delivery failed: {result.Status} {result.ErrorMessage}"); + // 跨服路由:经远程客户端按路由实例定向投递(非本地发送器) + Assert.Empty(localSender.Delivered); + var context = Assert.Single(captureClient.Contexts); + Assert.NotNull(context.ServiceName); + } + + [Fact] + public async Task PlayerRouting_LocalServerOnlineRoute_ShouldDeliverViaLocalSender() + { + var captureClient = new CapturingRemoteMessageClient(); + var routeTable = new MutableRouteTableProvider() + .SetServiceEndpoint("Social", "tcp://127.0.0.1:59998", "social-local-1"); + var resolver = new StaticPlayerRouteResolver(GameFrameX.Discovery.Routing.PlayerRouteInfo.Online("Social", 1001, "social-local-1", 1)); + var localSender = new RecordingLocalPlayerSender { OnlinePlayers = { [702] = true } }; + + var sender = ServerLinkPlayerRouting.ComposeUnifiedSender( + captureClient, + routeTable, + resolver, + localSender, + "Social", + "social-local-1"); + + var message = new TestMessageObject(); + var result = await sender.SendToPlayerAsync(702, message); + + Assert.True(result.IsSuccess, $"player delivery failed: {result.Status} {result.ErrorMessage}"); + // 本服路由:本地发送器收到投递,远程客户端零调用 + var delivered = Assert.Single(localSender.Delivered); + Assert.Equal(702, delivered.PlayerId); + Assert.Same(message, delivered.Message); + Assert.Empty(captureClient.Contexts); + } + + /// + /// TCP 回环接收面:握手短路(接受同 major 对端)+ 业务回声(响应回写请求负载)。 + /// + /// + /// A TCP loopback receive surface: a handshake short circuit (accepting same-major peers) + /// plus a business echo (the response echoes the request payload). + /// + private sealed class TcpEchoServerSurface : IAsyncDisposable + { + private readonly TcpListener _listener; + private readonly CancellationTokenSource _cancellationTokenSource = new(); + private Task _acceptLoop; + + public ConcurrentQueue ServerErrors { get; } = new(); + + private TcpEchoServerSurface(TcpListener listener, Task acceptLoop) + { + _listener = listener; + _acceptLoop = acceptLoop; + Port = ((IPEndPoint)listener.LocalEndpoint).Port; + } + + public int Port { get; } + + public ConcurrentQueue<(int Major, int Minor)> Handshakes { get; } = new(); + + public static async Task StartAsync() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var surface = new TcpEchoServerSurface(listener, Task.CompletedTask); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + surface._acceptLoop = Task.Run(() => surface.AcceptLoopAsync(started)); + await started.Task; + return surface; + } + + private async Task AcceptLoopAsync(TaskCompletionSource started) + { + started.TrySetResult(true); + try + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + var client = await _listener.AcceptTcpClientAsync(_cancellationTokenSource.Token); + _ = Task.Run(() => HandleConnectionAsync(client), _cancellationTokenSource.Token); + } + } + catch (OperationCanceledException) + { + } + } + + private async Task HandleConnectionAsync(TcpClient client) + { + try + { + using (var connection = client) + { + var codec = new DefaultMessageCodec(new DefaultMessageCompressionRegistry(), 0, 512, 1024 * 1024, 1024 * 1024); + var stream = connection.GetStream(); + while (!_cancellationTokenSource.IsCancellationRequested) + { + var message = await codec.DecodeAsync(stream, _cancellationTokenSource.Token); + if (message == null) + { + return; + } + + MessageObject reply; + if (message is ReqProtocolVersionNegotiation handshakeRequest) + { + Handshakes.Enqueue((handshakeRequest.Major, handshakeRequest.Minor)); + var local = RemoteMessagingProtocolVersion.Current; + reply = new RespProtocolVersionNegotiation + { + Major = local.Major, + Minor = local.Minor, + Accepted = handshakeRequest.Major == local.Major, + ErrorCode = handshakeRequest.Major == local.Major ? 0 : 1, + }; + } + else if (message is ReqInnerFriendByAdd friendRequest) + { + reply = new RespInnerFriendByAdd + { + Success = friendRequest.SourcePlayerId > 0, + ErrorCode = (int)(friendRequest.PlayerId % 100000), + }; + } + else + { + return; + } + + reply.UniqueId = message.UniqueId; + MessageProtoHelper.SetMessageId(reply); + using (var frame = codec.Encode(reply)) + { + await stream.WriteAsync(frame.Memory, _cancellationTokenSource.Token); + } + } + } + } + catch (Exception exception) + { + // 连接关闭/解码失败即结束该连接的处理循环;记录供失败断言输出 + ServerErrors.Enqueue(exception.ToString()); + } + } + + public async ValueTask DisposeAsync() + { + _cancellationTokenSource.Cancel(); + try + { + await _acceptLoop; + } + catch (OperationCanceledException) + { + } + + _listener.Stop(); + _cancellationTokenSource.Dispose(); + } + } + + private sealed class StaticPlayerRouteResolver : GameFrameX.Discovery.Routing.IPlayerRouteResolver + { + private readonly GameFrameX.Discovery.Routing.PlayerRouteInfo _route; + + public StaticPlayerRouteResolver(GameFrameX.Discovery.Routing.PlayerRouteInfo route) + { + _route = route; + } + + public Task ResolveAsync(long playerId) + { + return Task.FromResult(_route); + } + } + + private sealed class RecordingLocalPlayerSender : IPlayerLocalSender + { + public List<(long PlayerId, MessageObject Message)> Delivered { get; } = new(); + + public Dictionary OnlinePlayers { get; } = new(); + + public bool IsPlayerOnline(long playerId) + { + return OnlinePlayers.TryGetValue(playerId, out var online) && online; + } + + public Task SendToLocalPlayerAsync(long playerId, GameFrameX.Network.Messages.MessageObject message) + { + lock (Delivered) + { + Delivered.Add((playerId, message)); + } + + return Task.FromResult(true); + } + } + + private sealed class CapturingRemoteMessageClient : IRemoteMessageClient + { + public ConcurrentQueue Contexts { get; } = new(); + + public Task CallAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task CallAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage, CancellationToken cancellationToken) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task CallAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage, int timeoutMs, CancellationToken cancellationToken = default) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task> CallWithResultAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task> CallWithResultAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage, int timeoutMs) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task> CallWithResultAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage, int timeoutMs, CancellationToken cancellationToken) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task> CallWithResultAsync(RemoteCallContext context, GameFrameX.Network.Messages.MessageObject requestMessage) where TResponse : class, IResponseMessage + { + Contexts.Enqueue(context); + if (typeof(TResponse) != typeof(RespSendToPlayerInner)) + { + throw new NotSupportedException($"Unsupported response type: {typeof(TResponse).Name}"); + } + + var response = new RespSendToPlayerInner { Success = true, PlayerOffline = false }; + return Task.FromResult(RemoteCallResult.Ok((TResponse)(object)response, 0, context.TraceId, 0)); + } + + public Task> CallWithRetryAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage, int timeoutMs = RemoteCallContext.DefaultTimeoutMs, int maxRetryCount = RemoteCallContext.DefaultMaxRetryCount, CancellationToken cancellationToken = default) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task> CallWithoutRetryAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage, int timeoutMs = RemoteCallContext.DefaultTimeoutMs, CancellationToken cancellationToken = default) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task> CallWithMetadataAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage, Dictionary metadata, int timeoutMs = RemoteCallContext.DefaultTimeoutMs, CancellationToken cancellationToken = default) where TResponse : class, IResponseMessage + { + throw new NotImplementedException(); + } + + public Task SendOneWayAsync(string serviceName, GameFrameX.Network.Messages.MessageObject requestMessage, int timeoutMs = RemoteCallContext.DefaultTimeoutMs, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public Task SendOneWayAsync(RemoteCallContext context, GameFrameX.Network.Messages.MessageObject requestMessage) + { + Contexts.Enqueue(context); + return Task.CompletedTask; + } + + public Task IsServiceAvailableAsync(string serviceName) + { + return Task.FromResult(true); + } + } +} diff --git a/docker-compose.yml b/docker-compose.yml index e81a8eb9e..101cb731c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,10 +1,15 @@ services: + # ── 默认档:MongoDB(双主线之一)── `docker compose up` 即用 + # 示例配置按三档定档默认零依赖 Sqlite(quickstart 载体);容器内挂载 Mongo 档样例选型: + # 容器内经服务名互访(Configs/compose/ 下专用配置指向 mongo:27017,宿主机样例保留 127.0.0.1)。 mongo: image: mongo:8.2 container_name: gfx-mongo restart: unless-stopped ports: - "127.0.0.1:37017:27017" + volumes: + - mongo-data:/data/db healthcheck: test: [ "CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ ping: 1 }).ok" ] interval: 5s @@ -13,7 +18,9 @@ services: networks: - gameframex - # 单一镜像;启动参数经 GAMEFRAMEX_SERVER_ARGS 原样透传(当前仅启动 Game,Social 后续补充) + # 单一镜像;启动参数经 GAMEFRAMEX_SERVER_ARGS 原样透传(当前仅启动 Game,Social 后续补充)。 + # 数据库选型经挂载的 Configs/app_config.json 表达(启动期校验器要求 CLI 与文件一致,文件即选型载体)。 + # 管理 API(28090)无 HTTP 签名验证,仅绑定宿主机回环地址,不对局域网发布。 game: build: context: . @@ -22,21 +29,63 @@ services: depends_on: mongo: condition: service_healthy - environment: - GAMEFRAMEX_SERVER_ARGS: "--ServerType=Game --ServerId=1001 --ServerInstanceId=1 --InnerPort=29100 --OuterPort=29100 --HttpPort=28080 --WsPort=29110 --MetricsPort=29090 --MinModuleId=10 --MaxModuleId=9999 --OnlineTenantId=1 --OnlineAppId=1 --DataBaseUrl=mongodb://mongo:27017/?authSource=admin --DataBaseName=gameframex" + volumes: + - "./Configs/compose/app_config.mongo.json:/app/Configs/app_config.json:ro" + - "./running/game/logs:/app/data/logs" ports: - "39100:29100" - "38080:28080" - - "28090:28090" + - "127.0.0.1:28090:28090" + networks: + - gameframex + + # ── PostgreSQL 档(双主线之二):`docker compose --profile postgres up` 启用 ── + # 与 Mongo 档并列的完整 Provider 示例;两档不共享数据,切换 Provider 不迁移存量数据(无迁移工具,见 README)。 + postgres: + image: postgres:17 + container_name: gfx-postgres + restart: unless-stopped + profiles: + - postgres + environment: + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres} + POSTGRES_DB: gameframex + ports: + - "127.0.0.1:35432:5432" volumes: - # SQLite 场景(--DatabaseProvider=Sqlite --DataBaseUrl="Data Source=data/gameframex.db"): - # 缺省数据文件落 /app/data/gameframex.db(镜像 VOLUME 数据根),要持久化就给 /app/data 挂具名卷或 bind 卷,例如 - # - "gameframex_data:/app/data" - # 注意 WAL 模式不建议放网络卷/SMB(有损坏风险),本地卷优先。 - - "./running/game/logs:/app/data/logs" + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: [ "CMD-SHELL", "pg_isready -U postgres" ] + interval: 5s + timeout: 3s + retries: 20 + networks: + - gameframex + + game-postgres: + build: + context: . + image: gameframex-server:local + container_name: gfx-game-postgres + profiles: + - postgres + depends_on: + postgres: + condition: service_healthy + volumes: + - "./Configs/compose/app_config.postgres.json:/app/Configs/app_config.json:ro" + - "./running/game-postgres/logs:/app/data/logs" + ports: + - "39200:29100" + - "38081:28080" + - "127.0.0.1:28091:28090" networks: - gameframex networks: gameframex: driver: bridge + +volumes: + mongo-data: + postgres-data: diff --git a/docs/docfx.json b/docs/docfx.json index f3660074e..8021dbdaa 100644 --- a/docs/docfx.json +++ b/docs/docfx.json @@ -15,6 +15,7 @@ "**/GameFrameX.Log.csproj", "**/GameFrameX.Setting.csproj", "**/GameFrameX.StartUp.csproj", + "**/GameFrameX.ServerLink.csproj", "**/GameFrameX.Utility.csproj", "**/GameFrameX.ServerManager.csproj", "**/GameFrameX.Launcher.csproj", diff --git a/docs/remote-messaging.md b/docs/remote-messaging.md new file mode 100644 index 000000000..0181e4eea --- /dev/null +++ b/docs/remote-messaging.md @@ -0,0 +1,72 @@ +# 服务器间链路(ServerLink / RemoteMessaging) + +> 2.0 基础设施收敛后的定位:跨服玩法真正需要的服间通信 = **点对点 RPC + 一张心跳表 + 一张玩家路由表**。 +> 推荐入口是 `GameFrameX.ServerLink` 薄门面封装包;`GameFrameX.Network.RemoteMessaging` 原名保留、原位收缩。 + +## ServerLink 薄门面(推荐入口) + +`GameFrameX.ServerLink` 把服间链路的内置默认固化在一个薄门面上: + +- **直连拨号**:默认 TCP 直连(经心跳注册表路由表解析端点),KCP 可显式叠加(`WithKcpTransport()`,TCP 恒为回落传输)。 +- **固定重试上限**:默认 2 次重试(`WithFixedRetryLimit` 可调,0 = 不重试);非幂等写操作请在业务侧关停重试。 +- **玩家路由解析内置默认**:`ServerLinkPlayerRouting.ComposeUnifiedSender(...)` 以发现层玩家路由解析器为内置默认,装配统一消息发送器(`IUnifiedMessageSender`)与本服投递槽——跨服找人(合服后的刚需)开箱即用。 +- **信封转发门面**:`ServerLinkEnvelopeForwarder.ForwardAsync(role, message, ...)` 把跨 Role 消息交给进程级路由缝:本进程 Role 走本地投递,跨进程跳打包 `RoleRouteEnvelopeMessage` 经共享传输池转发。 + +```csharp +// 直连拨号 + 固定重试上限 +var client = new ServerLinkBuilder() + .WithRouteTable(ActiveDiscoveryRuntime.RouteTableProvider) + .Build(); + +// 玩家路由投递(统一消息发送器 + 本地投递槽一次装配) +var sender = ServerLinkPlayerRouting.ComposeUnifiedSender( + client, + ActiveDiscoveryRuntime.RouteTableProvider, + PlayerRouteResolverBootstrap.Resolver, + localPlayerSender, + localServerType: "Game", + localInstanceId: PlayerRouteResolverBootstrap.LocalInstanceId); +``` + +## RemoteMessaging 原位收缩清单 + +`GameFrameX.Network.RemoteMessaging` 保留原名,以下面为收缩后的边界: + +| 面 | 处置 | 说明 | +|---|---|---| +| 协议握手 | **保留(最小版本校验)** | 握手帧交换 + major 不符显式拒绝 + 超时按旧版本节点放行(滚动升级窗口);`InterNodeAuthentication` HMAC 节点间互信保留(fail-closed) | +| 多版本协商(Versioning) | **已移除** | 消息级 `ProtocolVersionAttribute` 标注与协商器抽象(多版本灰度面)已删除;线缆契约只剩握手帧的最小版本号校验 | +| 韧性(Resilience) | **默认 PassThrough** | 熔断器与端点健康评估默认直通(不熔断、不评分),重试默认关闭;`WithCircuitBreaker` / `WithRetry` 显式开启(自托管进阶配置,接口全部保留) | +| 治理(Unified 治理面) | **冻结** | `MessageGovernancePolicy` 与 `IServerInstanceSelector` / `ConsistentHashServerInstanceSelector` 保留现状供既有消费方使用、不再演进;`IUnifiedMessageSender` 玩家级投递为活跃面 | +| 观测(Observability) | **最小计数** | 调用计数 / 时延 / 错误计数常开(Metrics + 标准 OTel span);详细观测面板归运营台 | +| 发现(Discovery) | **保留本体** | 心跳注册表 + 角色路由表 + 玩家路由表是合服底座,全部保留 | + +环境变量开关(前缀 `RemoteMessaging__`):`EnableCircuitBreaker`(默认 false)、`EnableRetry`(默认 false)、`MaxRetryCount`、`DefaultTimeoutMs`、`HandshakeTimeoutMs`、`EnableFaultInjection`(默认 false,仅开发环境)。旧键 `EnableUnifiedClient` 已随收缩移除,不再生效。 + +## 跨服调用准入规则(自 Guides 收编) + +所有新增跨服务调用必须遵循以下规范: + +1. 【强制】所有跨服务调用必须通过 `IRemoteMessageClient`(推荐经 `ServerLinkBuilder` 构建)发起,禁止在 ComponentAgent 中直接使用 `TcpClient` / `NetworkStream`。 +2. 【强制】非幂等操作(写操作)必须设置 `AllowRetry = false`——重试默认关闭,显式开启重试时尤其要注意写操作的幂等性。 +3. 【强制】幂等操作(读操作 / 查询)可设置 `AllowRetry = true`,但最大重试不超过 2 次。 +4. 【推荐】使用 `CallWithResultAsync` 替代 `CallAsync`,获取结构化结果与状态码。 +5. 【推荐】使用 `ServerLinkBuilder` / `RemoteMessagingBuilder` 构建客户端,而非直接实例化 `RemoteMessageClient`。 +6. 【推荐】通过 `MessageObjectPoolHelper.Get/Return` 管理请求对象生命周期。 + +错误码映射参考: + +| RemoteStatusCode | 业务错误码 | 说明 | +|---|---|---| +| Success | 0 | 成功 | +| Timeout | -1 | 超时 | +| ConnectionFailed | -2 | 连接失败 | +| EndpointNotFound | -3 | 服务发现失败 | +| Cancelled | -4 | 取消 | +| RetryExhausted | -5 | 重试耗尽 | +| ConnectionClosed | -6 | 连接关闭 | +| UnexpectedResponse | -7 | 响应异常 | +| CircuitOpen | -10 | 熔断开启(显式开启熔断器后才会出现) | +| ServiceUnavailable | -11 | 服务不可用(显式开启健康评估后才会出现) | +| ProtocolVersionIncompatible | 12 | 握手版本不兼容(跨 major 混布被拒绝) | +| UnknownError | -99 | 未知错误 | diff --git a/docs/toc.yml b/docs/toc.yml index e3c8b9172..fe4a7bbb2 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -1,5 +1,7 @@ - name: API Reference href: api/ +- name: 服务器间链路(ServerLink / RemoteMessaging) + href: remote-messaging.md - name: 文档主页 href: https://gameframex.doc.alianblank.com - name: 框架主页