diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fbc57fe5..229e335d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ * Wrapper 生成器崩溃止血与不可编译产物清理(C431,GFX-1171,GitHub #917):`[TimeOut]` 实参防御式解析(仅数值字面量可静态求值——常量名/缺参/空参/表达式/下划线开头的常量名输出 Error 诊断并降级为框架默认超时,不再令生成器整体崩溃丢失全部 wrapper);`GetFullName` 重写为向上收集命名空间与嵌套类型段(无命名空间代理返回类型链短名,顺带覆盖 struct/enum 容器形态);`Tools.GetNameSpace` 取真命名空间(首个 `+` 前最后一个 `.`,无命名空间返回空串且不发射空 using),嵌套代理基类改容器限定名 `Outer.Inner`、wrapper 类名携带容器链(同命名空间同名代理不再碰撞);partial 合并键升为完全限定名(跨命名空间同名无关类不再产生幽灵 Wrapper);async 被包装方法统一 `return await`(修复非泛型 `async Task`/`async ValueTask` 生成体不可编译);含 `ref/out/in` 参数与 `[Discard]` 返回类型非 Task/ValueTask(按类型名最后一段比较,全限定名不误报)的方法报 Error 且不进入生成面(校验先行);`[Discard]` 非 ThreadSafe 入队 lambda 改 `async ()=> await` 统一绑定 `EnqueueAsync(Func)` 重载(ValueTask 一次性消费契约不再被违反)。新增 16 例生成器测试(含独立审查 R1/R2/R3 修复钉住),既有 3 例 Discard lambda 断言随契约更新。 ### Added +* 黄金路径默认开箱即通(C460,GFX-1195,GitHub #959):`OnlineLeaderboardProjectionOptions.MatchSettledBoardId` 默认值由空白(不投影)改为默认榜常量 `match-settled`(`OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId`)——零 Online JSON 配置起服即装配 Match.Settled 投影、激活期预建默认榜,RPS 对局→结算→Grant 发奖→上榜全链默认贯通;显式置空白 / null 或配置段覆盖为空白仍可关闭投影(不装配、不预建、不报错)。`OnlineCompetitionOptions.Validate` 补投影组合校验:`LeaderboardProjection` 须为非 null 对象,榜单标识非空白(投影开启)时长度 ≤128 且不得含空白字符(装配期 fail-fast,全部问题一次报全)。端到端验收以可重跑 xunit 钉住(GameFrameX.Tests 零 Settings 组合全链 + Hotfix.Tests 桥断言:好友桥→撮合桥→对局桥→默认榜条目),`Configs/app_config.json` Game 角色移除 `Online.Settings` 空节依赖。 * 行版本条件写内存管线收口共享助手(C409,GFX-1117):新增 `GameFrameX.DataBase/Abstractions/RowVersionCasWriteHelper` 与 `RowVersionBackfillWriteHelper`——`UpdateIfRowVersionAsync`(CAS)与 `UpdateIfRowVersionIsNullAsync`(回填)两原语在 Mongo/PostgreSQL/SQLite 三 Provider 重复的内存侧样板(Id 一致性校验、版本对齐 + checked 递增、写库前 `ToBytes()` 快照、失败回滚 / 成功精确提交)收敛为单一事实源,Provider 仅保留谓词 / 语句 / 重试外壳等写库差异;语义零变化(失败回滚、异常不回滚、`long.MaxValue` 溢出写库前抛出、SQLite null 守卫现状均冻结),回归依托 `DatabaseConditionalWritePrimitivesTests` 既有套件。 * 服务器间 RPC 端点改由心跳注册表解析并退役静态引导(C304,GitHub #643):`RemoteServiceTarget`(ServerType + 可选 InstanceId)结构化拨号取代 `{Role}_{InstanceId}` 字符串拼接;`DiscoveryServiceEndpointResolver` 成为唯一端点解析器(指定实例走 Instance 视图含 Draining 并校验 Role 一致,ServerType 级取 Active 中 InstanceId 序数最小者,端点集合 = TCP 主端点 + 附加端点,偏好 kcp > ws > wss > tcp);`RemoteMessagingBuilder.WithRouteTable(IRoleRouteTableProvider)` 绑定路由表、生产注册 KCP 拨号适配器(`IsEnableInnerKcp` 时,服务器间 KCP 首次生产可用);心跳新增附加广播端点(`InstanceDescriptor.AdditionalAdvertiseEndpoints`,监听器装配成功的实例级闸门后才广播,多 ServerType 进程非首选类型披露 Warning);`UnifiedMessageSender` 实例列表改读路由表 Active 视图且仅 InstanceId 集合变化才重建哈希环;玩家路由实例直达——`player_route.InstanceId` 写真实发现层实例 Id(`PlayerRouteResolverBootstrap` 同源注入),`ForwardToRemoteServerAsync` 按 `TargetInstanceId` 投递(Instance 视图含 Draining)、`IsCurrentServer` 改 InstanceId 比较;Mongo 心跳 class map 显式忽略未知字段(含继承传递)、写路径空集合归一化为 null(默认配置文档与旧版本逐字节同形);PostgreSQL 幂等补列 `additional_advertise_endpoints text[]`(命名经 `DiscoveryStorageNaming` 推导);删除 `services__*` 环境变量契约、`EnvironmentVariableEndpointResolver`、`EnvironmentServiceInstanceDiscovery`、`docker-compose.multi.legacy.yml` 与生成器静态引导映射。 diff --git a/Capability/GameFrameX.Capability.Hosting.Abstractions/CapabilityHostOptions.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/CapabilityHostOptions.cs index 7724bcbf0..50c45c842 100644 --- a/Capability/GameFrameX.Capability.Hosting.Abstractions/CapabilityHostOptions.cs +++ b/Capability/GameFrameX.Capability.Hosting.Abstractions/CapabilityHostOptions.cs @@ -33,21 +33,11 @@ namespace GameFrameX.Capability.Hosting.Abstractions; /// 能力宿主装配选项(本进程的运行时授权作用域身份 + 调度壳驱动参数; /// 原 OnlineRuntimeOptions 作用域半边的机制承接位,admin 监听参数归 AdminApiOptions)。 /// -/// 维护约束:三元组是本进程的服务端权威作用域(请求体作用域字段不可覆盖,跨租户/App/服请求拒绝)。 +/// 维护约束:单键化 D4 后区服键是本进程的服务端权威作用域(请求体作用域字段不可覆盖,跨服请求拒绝)。 /// /// public sealed class CapabilityHostOptions { - /// - /// 获取或设置授权租户标识(必须为正数)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置授权应用标识(必须为正数)。 - /// - public long AppId { get; set; } - /// /// 获取或设置授权区服标识(必须为正数)。 /// @@ -59,12 +49,12 @@ public sealed class CapabilityHostOptions public int SchedulerIntervalMilliseconds { get; set; } = 1000; /// - /// 校验选项合法性(作用域三元组与调度间隔)。 + /// 校验选项合法性(作用域区服键与调度间隔)。 /// /// 合法返回 true;否则 false(宿主不应在非法配置下启动)。 public bool IsValid() { - if (TenantId <= 0 || AppId <= 0 || ServerId <= 0) + if (ServerId <= 0) { return false; } diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiClaimedScope.cs b/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiClaimedScope.cs index 1d4dc24dc..6059c85ce 100644 --- a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiClaimedScope.cs +++ b/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiClaimedScope.cs @@ -30,33 +30,19 @@ namespace GameFrameX.Capability.Hosting.AdminApi; /// -/// admin 请求的声称作用域三元组(机制层不解释语义,判定由组合根注入的作用域适配器完成)。 +/// admin 请求的声称作用域区服键(机制层不解释语义,判定由组合根注入的作用域适配器完成;单键化 D4 后仅区服位)。 /// public sealed class AdminApiClaimedScope { /// /// 初始化 。 /// - /// 租户标识。 - /// 应用标识。 /// 区服标识。 - public AdminApiClaimedScope(long tenantId, long appId, long serverId) + public AdminApiClaimedScope(long serverId) { - TenantId = tenantId; - AppId = appId; ServerId = serverId; } - /// - /// 获取租户标识。 - /// - public long TenantId { get; } - - /// - /// 获取应用标识。 - /// - public long AppId { get; } - /// /// 获取区服标识。 /// diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiComposition.cs b/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiComposition.cs index eeb0a5863..064c42837 100644 --- a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiComposition.cs +++ b/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiComposition.cs @@ -101,7 +101,7 @@ public static ICapabilityAdminApiPlane CreateAdminApiPlane(CapabilityHost host, registry, errorCodes, scopeAdapter, - new AdminApiClaimedScope(host.TenantId, host.AppId, host.ServerId), + new AdminApiClaimedScope(host.ServerId), idempotencyAdapter, host.Report, host.Services); diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiDispatcher.cs b/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiDispatcher.cs index c51f7dc1a..548e29e34 100644 --- a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiDispatcher.cs +++ b/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiDispatcher.cs @@ -167,13 +167,13 @@ public async Task DispatchAsync(string action, string bodyJson) if (!_scopeAdapter.TryReadClaimedScope(request, out var claimedScope)) { - return WriteFail(_errorCodes.ScopeMissing, "Scope triple (TenantId/AppId/ServerId) missing or invalid in request body.", requestId); + return WriteFail(_errorCodes.ScopeMissing, "Scope key (ServerId) missing or invalid in request body.", requestId); } var deniedCode = _scopeAdapter.ValidateClaimed(claimedScope, _authorizedScope); if (deniedCode != null) { - return WriteFail(deniedCode, "Scope denied for tenant " + claimedScope.TenantId + ", app " + claimedScope.AppId + ", server " + claimedScope.ServerId + ".", requestId); + return WriteFail(deniedCode, "Scope denied for server " + claimedScope.ServerId + ".", requestId); } if (registration.WrapIdempotency && _idempotencyAdapter != null) diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiRequest.cs b/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiRequest.cs index c3e3ffe52..0670473d4 100644 --- a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiRequest.cs +++ b/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiRequest.cs @@ -106,26 +106,20 @@ public string ReadIdempotencyKey() } /// - /// 提取客户端声称的作用域三元组(POST 请求体顶层 TenantId/AppId/ServerId,大小写不敏感)。 + /// 提取客户端声称的作用域区服键(POST 请求体顶层 ServerId,大小写不敏感;单键化 D4 后仅区服位, + /// 客户端携带的租户位/App 位遗留字段一律忽略)。 /// - /// 输出:声称租户标识。 - /// 输出:声称应用标识。 /// 输出:声称区服标识。 - /// 三元组完整提取返回 true;任一字段缺失或格式非法返回 false(由调用方按作用域缺失拒绝)。 - public bool TryReadClaimedScope(out long tenantId, out long appId, out long serverId) + /// 区服键完整提取返回 true;字段缺失或格式非法返回 false(由调用方按作用域缺失拒绝)。 + public bool TryReadClaimedScope(out long serverId) { - tenantId = 0; - appId = 0; serverId = 0; if (Root.ValueKind != JsonValueKind.Object) { return false; } - var hasTenant = TryReadInt64("TenantId", out tenantId); - var hasApp = TryReadInt64("AppId", out appId); - var hasServer = TryReadInt64("ServerId", out serverId); - return hasTenant && hasApp && hasServer; + return TryReadInt64("ServerId", out serverId); } /// diff --git a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityHost.cs b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityHost.cs index 97bbc07f7..2bae2133f 100644 --- a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityHost.cs +++ b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityHost.cs @@ -102,21 +102,6 @@ public sealed class CapabilityHost /// private readonly SemaphoreSlim _lifecycleGate = new(1, 1); - /// - /// 获取授权租户标识。 - /// - public long TenantId - { - get { return Options.TenantId; } - } - - /// - /// 获取授权应用标识。 - /// - public long AppId - { - get { return Options.AppId; } - } /// /// 获取授权区服标识。 diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Audit/InMemoryOnlineAuditStore.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Audit/InMemoryOnlineAuditStore.cs index 197e15c82..91684eb5d 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Audit/InMemoryOnlineAuditStore.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Audit/InMemoryOnlineAuditStore.cs @@ -40,8 +40,8 @@ namespace GameFrameX.Capability.Online.Abstractions.Audit; /// 统一审计内存存储(单进程默认实现;生产持久化实现归运行时装配)。 /// /// 维护约束:「EventId 判重 + 落档」在 锁内**同一临界区**完成(幂等半边的 -/// 结构性保证);作用域索引键为 (TenantId, AppId) 两键——审计是跨区服检索域,区服过滤随查询载荷下推; -/// 每作用域维护按跨域检索全序(OccurredTime 倒序, EventId 序数升序)排列的有序索引, +/// 结构性保证);单键化(D4)后为单桶全序索引(无作用域分片键)——审计是跨区服检索域,区服过滤随查询载荷下推; +/// 维护按跨域检索全序(OccurredTime 倒序, EventId 序数升序)排列的有序索引, /// 在同一临界区内同步插入(只插不删——记录只追加不淘汰, /// EventId 全局唯一保证键无重复);出入参防御性拷贝(持久化行语义,调用方引用不得别名存储内部状态)。 /// @@ -69,10 +69,11 @@ public sealed class InMemoryOnlineAuditStore : IOnlineAuditStore private readonly HashSet _knownEventIds = new(StringComparer.Ordinal); /// - /// 作用域级有序索引(键 = "TenantId|AppId";值 = 按跨域检索全序排列的落档记录, - /// 正序枚举即 (OccurredTime 倒序, EventId 序数升序)——检索与游标定位的唯一排序事实来源)。 + /// 全序有序索引(按跨域检索全序排列的落档记录, + /// 正序枚举即 (OccurredTime 倒序, EventId 序数升序)——检索与游标定位的唯一排序事实来源; + /// 单键化 D4 后无作用域分片键,单桶承载全部落档记录)。 /// - private readonly Dictionary> _recordsByScope = new(StringComparer.Ordinal); + private readonly SortedList _records = new(OnlineAuditSortKeyComparer.Instance); /// /// 追加一条审计记录(锁内判重 + 落档 + 有序索引插入同一临界区)。 @@ -94,14 +95,7 @@ public Task AppendAsync(OnlineAuditRecord record, CancellationToken cancel return Task.FromResult(false); } - var scopeKey = BuildScopeKey(record.TenantId, record.AppId); - if (!_recordsByScope.TryGetValue(scopeKey, out var bucket)) - { - bucket = new SortedList(OnlineAuditSortKeyComparer.Instance); - _recordsByScope[scopeKey] = bucket; - } - - bucket.Add(new OnlineAuditSortKey(record.OccurredTime, record.EventId), CloneRecord(record)); + _records.Add(new OnlineAuditSortKey(record.OccurredTime, record.EventId), CloneRecord(record)); return Task.FromResult(true); } } @@ -109,9 +103,9 @@ public Task AppendAsync(OnlineAuditRecord record, CancellationToken cancel /// /// 按查询载荷检索审计页:索引上二分定位起点后有界扫描,过滤 + keyset 游标 + 全序 + 页大小全部在本实现内完成。 /// - /// 存储层查询载荷(作用域 / 过滤维度 / 已解码游标 / 页大小已由调用方校验)。 + /// 存储层查询载荷(过滤维度 / 已解码游标 / 页大小已由调用方校验)。 /// 取消令牌(内存实现无异步等待,令牌仅契约对齐)。 - /// 按全序排列、至多 PageSize 行的结果页(行集为防御性拷贝);作用域外结构性不可见。 + /// 按全序排列、至多 PageSize 行的结果页(行集为防御性拷贝)。 public Task QueryAsync(OnlineAuditStoreQuery query, CancellationToken cancellationToken = default) { if (query == null) @@ -124,17 +118,14 @@ public Task QueryAsync(OnlineAuditStoreQuery query, Cancel var hasMore = false; lock (_gate) { - if (_recordsByScope.TryGetValue(BuildScopeKey(query.TenantId, query.AppId), out var bucket)) - { - hasMore = CollectPageFromBucket(bucket, query, pageSize, records); - } + hasMore = CollectPageFromBucket(_records, query, pageSize, records); } return Task.FromResult(new OnlineAuditStorePage(records, hasMore)); } /// - /// 在作用域索引上有界顺序扫描一页:游标起点定位后命中过滤即收,页满后再探到一行命中即判 + /// 在全序索引上有界顺序扫描一页:游标起点定位后命中过滤即收,页满后再探到一行命中即判 /// HasMore 并停止;OccurredTime 低于时间窗起点即提前终止(全序倒序保证其后更旧,其后无更多行)。 /// 须在 临界区内调用(与追加共用同一索引快照);收入页行的均为防御性拷贝。 /// @@ -174,17 +165,6 @@ private static bool CollectPageFromBucket(SortedList - /// 构造作用域索引键("TenantId|AppId";审计是跨区服检索域,区服维度不进作用域键)。 - /// - /// 租户标识。 - /// App 标识。 - /// 作用域索引键。 - private static string BuildScopeKey(long tenantId, long appId) - { - return tenantId.ToString(System.Globalization.CultureInfo.InvariantCulture) + "|" + appId.ToString(System.Globalization.CultureInfo.InvariantCulture); - } - /// /// 二分定位「严格位于游标位之后」的首个索引下标(keyset 语义;游标行自身若仍在档则被跳过)。 /// @@ -311,8 +291,6 @@ private static OnlineAuditRecord CloneRecord(OnlineAuditRecord record) Domain = record.Domain, EventType = record.EventType, OccurredTime = record.OccurredTime, - TenantId = record.TenantId, - AppId = record.AppId, ServerId = record.ServerId, PlayerId = record.PlayerId, OperatorId = record.OperatorId, diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditEntry.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditEntry.cs index 0cce58aef..6d4d50c10 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditEntry.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditEntry.cs @@ -76,17 +76,7 @@ public sealed class OnlineAuditEntry public long OccurredTime { get; set; } /// - /// 获取或设置租户标识(必填,必须大于 0)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(必填,必须大于 0)。 - /// - public long AppId { get; set; } - - /// - /// 获取或设置区服标识(0 表示 App 级操作——支付、远程配置等无区服维度的审计)。 + /// 获取或设置区服标识(0 表示全局级操作——支付、远程配置等无区服维度的审计)。 /// public long ServerId { get; set; } diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditService.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditService.cs index d66bc7196..3c9bec461 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditService.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditService.cs @@ -44,15 +44,15 @@ namespace GameFrameX.Capability.Online.Abstractions.Audit; /// 维护约束(红线): /// ① **只写审计存储**——本服务不持有任何其它域服务/存储,不触碰 Online Actor 与资产状态 /// (「不得直写」由类型系统结构性保证,对齐「只依赖读取面」在写入侧的镜像); -/// ② **审计完整性**:接入条目缺 操作者/原因/标识/类型/租户/App 或域未知 → 拒绝 +/// ② **审计完整性**:接入条目缺 操作者/原因/标识/类型 或域未知 → 拒绝 /// 4001(宁拒毋缺——「关键操作无审计次数 = 0」的服务端结构性保障:不完整审计进不了链路); /// ③ **幂等**:EventId 全局唯一,判重与落档在存储临界区内完成,重复接入回执 /// IsDuplicate=true、无副作用; /// ④ **脱敏**:落档前经 生成 SanitizedFields, /// 存储与检索自落档起结构性无明文敏感值; -/// ⑤ **检索锚定**:QueryAsync 的作用域只锚定 TenantId/AppId 两键——审计是跨区服检索域 -/// (支付/远程配置等 App 级审计 ServerId=0),区服/玩家/操作者等维度走 -/// 可选过滤;scope.ServerId/scope.PlayerId 不参与审计过滤,防止误把跨域联查切割成单区服视角。 +/// ⑤ **检索无锚点**:单键化(D4)后审计检索不再有作用域锚定键——审计是跨区服检索域 +/// (支付/远程配置等全局级审计 ServerId=0),区服/玩家/操作者等维度走 +/// 可选过滤;防止误把跨域联查切割成单区服视角。 /// /// public sealed class OnlineAuditService : IOnlineAuditReader @@ -125,8 +125,6 @@ public async Task> IngestAsync(OnlineAudi Domain = entry.Domain, EventType = entry.EventType, OccurredTime = entry.OccurredTime, - TenantId = entry.TenantId, - AppId = entry.AppId, ServerId = entry.ServerId, PlayerId = entry.PlayerId, OperatorId = entry.OperatorId, @@ -142,31 +140,21 @@ public async Task> IngestAsync(OnlineAudi } /// - /// 跨域检索统一审计(只读;按作用域两键锚定 + 可选维度过滤 + keyset 全序分页)。 + /// 跨域检索统一审计(只读;可选维度过滤 + keyset 全序分页;单键化 D4 后无作用域锚定键)。 /// - /// 生效作用域(只锚定 TenantId/AppId 两键,须均大于 0;区服/玩家走查询条件)。 /// 查询条件;传 等价于默认条件(全部域、首页、默认页大小)。 /// 取消令牌。 - /// 审计分页结果;作用域两键缺失、页大小越界、游标非法返回 。 - /// 无任何数据时返回**空行集**(与跨作用域读取同构,不是错误)。 - public async Task> QueryAsync(OnlineScope scope, OnlineAuditQuery query = null, CancellationToken cancellationToken = default) + /// 审计分页结果;页大小越界、游标非法返回 。 + /// 无任何数据时返回**空行集**(与无匹配同构,不是错误)。 + public async Task> QueryAsync(OnlineAuditQuery query = null, CancellationToken cancellationToken = default) { - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - - if (scope.TenantId <= 0 || scope.AppId <= 0) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "统一审计检索必须锚定租户与 App(TenantId / AppId 大于 0;区服与玩家走查询条件可选过滤)"); - } - var request = query; if (request == null) { request = new OnlineAuditQuery(); } + var pageSize = request.PageSize <= 0 ? DefaultPageSize : request.PageSize; if (pageSize > MaxPageSize) { @@ -181,12 +169,10 @@ public async Task> QueryAsync(OnlineScope scope, O return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "游标格式非法(不透明令牌只回传不构造)"); } - // 反预言同构:存储按 (Tenant, App) 索引结构性隔离,跨作用域查询与「无数据」都得到空行集; + // 反预言同构:存储单桶全序索引,无匹配查询与「无数据」都得到空行集; // 过滤 + keyset 游标 + 全序排序 + 页大小下推存储层完成(服务层只做校验、游标编解码与页组装)。 var storeQuery = new OnlineAuditStoreQuery { - TenantId = scope.TenantId, - AppId = scope.AppId, Domains = request.Domains, PlayerId = request.PlayerId, OperatorId = request.OperatorId, @@ -251,14 +237,9 @@ private static OnlineResult ValidateEntry(OnlineAuditE return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "操作原因(Reason)必填——审计完整性要求含原因"); } - if (entry.TenantId <= 0 || entry.AppId <= 0) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "审计条目必须携带租户与 App(TenantId / AppId 大于 0)"); - } - if (entry.ServerId < 0 || entry.PlayerId < 0) { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "区服与玩家标识不可为负(0 分别表示 App 级操作与系统级操作)"); + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "区服与玩家标识不可为负(0 分别表示全局级操作与系统级操作)"); } return null; @@ -300,8 +281,6 @@ private static OnlineEvent ToEnvelope(OnlineAuditEntry entry) EventType = entry.EventType, OccurredTime = entry.OccurredTime, SchemaVersion = 1, - TenantId = entry.TenantId, - AppId = entry.AppId, ServerId = entry.ServerId, PlayerId = entry.PlayerId, Source = entry.Source, diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditStoreQuery.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditStoreQuery.cs index 9e572dea9..ccea3f9ab 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditStoreQuery.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Audit/OnlineAuditStoreQuery.cs @@ -34,7 +34,7 @@ namespace GameFrameX.Capability.Online.Abstractions.Audit; /// /// 统一审计存储层查询载荷( 的唯一入参; -/// 由 OnlineAuditService.QueryAsync 在完成作用域 / 页大小 / 游标校验与游标解码后组装)。 +/// 由 OnlineAuditService.QueryAsync 在完成页大小 / 游标校验与游标解码后组装;单键化 D4 后无作用域锚定键)。 /// /// 维护约束(红线):过滤语义与跨域检索口径**逐项同源**——全部可选过滤为合取(AND), /// 为空或 表示不限域,非空时命中集合内任一域即保留 @@ -45,16 +45,6 @@ namespace GameFrameX.Capability.Online.Abstractions.Audit; /// public sealed class OnlineAuditStoreQuery { - /// - /// 获取或设置租户标识(作用域锚定第一键;须大于 0,由调用方校验)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域锚定第二键;须大于 0,由调用方校验)。 - /// - public long AppId { get; set; } - /// /// 获取或设置审计域过滤集合(跨域联查:命中任一域即保留;空集合或 表示不限域)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineAuditReader.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineAuditReader.cs index fa493c182..c5a2a81e8 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineAuditReader.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineAuditReader.cs @@ -27,7 +27,6 @@ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== -using GameFrameX.Capability.Online.Abstractions.Scope; namespace GameFrameX.Capability.Online.Abstractions.Contracts; @@ -36,7 +35,8 @@ namespace GameFrameX.Capability.Online.Abstractions.Contracts; /// 叶子域 admin handler 的域内审计查询(如 query_asset_audit)经本接口读统一审计面, /// 不引入对聚合域(Operations/Audit 实现体)的编译期依赖。 /// -/// 维护约束:作用域只锚定 TenantId/AppId 两键(审计是跨区服检索域);实现方 = OnlineAuditService +/// 维护约束:检索无作用域锚定键(单键化 D4 后审计是跨区服检索域,区服走可选过滤); +/// 实现方 = OnlineAuditService ///(C294 起随族基建落在 Online.Abstractions.Audit,由 OnlineCapabilityFamily 预置到共享服务面)。 /// /// @@ -44,19 +44,19 @@ namespace GameFrameX.Capability.Online.Abstractions.Contracts; /// The unified audit read face (the narrowest contract through which leaf capability packages consume the /// aggregate audit domain — the same gate-lifting approach as C223, applied by C231): leaf-domain admin /// handlers query domain-scoped audit trails (e.g. query_asset_audit) through this interface without a -/// compile-time dependency on the aggregate domain (the Operations/Audit implementation). The scope anchors -/// on TenantId/AppId only (audit is a cross-server retrieval domain); the implementor is +/// compile-time dependency on the aggregate domain (the Operations/Audit implementation). Queries carry +/// no scope anchor (after single-key D4 audit is a cross-server retrieval domain; server is an optional +/// filter); the implementor is /// OnlineAuditService (relocated into Online.Abstractions.Audit as family infrastructure by /// C294, pre-seeded onto the shared service face by OnlineCapabilityFamily). /// public interface IOnlineAuditReader { /// - /// 按查询条件检索统一审计记录(游标分页;作用域只锚定 TenantId/AppId 两键)。 + /// 按查询条件检索统一审计记录(游标分页;无作用域锚定键,区服/玩家走可选过滤)。 /// - /// 授权作用域。 /// 查询条件(可空 = 缺省全量首页)。 /// 取消令牌。 /// 审计记录页(失败以 错误码表达)。 - Task> QueryAsync(OnlineScope scope, OnlineAuditQuery query = null, CancellationToken cancellationToken = default); + Task> QueryAsync(OnlineAuditQuery query = null, CancellationToken cancellationToken = default); } diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineChannelMembershipProbe.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineChannelMembershipProbe.cs index 8e9dc0623..6693ce191 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineChannelMembershipProbe.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineChannelMembershipProbe.cs @@ -52,13 +52,11 @@ public interface IOnlineChannelMembershipProbe /// /// 判定玩家当前是否为绑定主体的成员。 /// - /// 租户标识。 - /// App 标识。 /// 频道类型(只会是 或 /// ;Direct 与 Global 不走本探针)。 /// 绑定主体标识(PartyId 或 GroupId)。 /// 待判定的玩家。 /// 取消令牌。 /// 当前是成员返回 true。 - Task IsChannelMemberAsync(long tenantId, long appId, OnlineChatChannelKind kind, string boundId, long playerId, CancellationToken cancellationToken = default); + Task IsChannelMemberAsync(OnlineChatChannelKind kind, string boundId, long playerId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineMatchDomain.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineMatchDomain.cs index 589412632..2aa78db13 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineMatchDomain.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineMatchDomain.cs @@ -82,12 +82,10 @@ public interface IOnlineMatchDomain /// /// 按分配标识解析数值对局标识与成员表(通知推送方消费;幂等)。 /// - /// 租户标识。 - /// App 标识。 /// 分配标识。 /// 取消令牌。 /// 分配解析视图。 - Task> ResolveAssignmentAsync(long tenantId, long appId, string assignmentId, CancellationToken cancellationToken = default); + Task> ResolveAssignmentAsync(string assignmentId, CancellationToken cancellationToken = default); /// /// 会话中介断线通知(C204):物理连接断开时按「票据 → 分配登记 → 运行时成员表」定位玩家当前对局, diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlinePartyPresenceProbe.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlinePartyPresenceProbe.cs index 8eb8c0cfe..dc6d80be6 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlinePartyPresenceProbe.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlinePartyPresenceProbe.cs @@ -43,10 +43,8 @@ public interface IOnlinePartyPresenceProbe /// /// 查询玩家当前是否在线。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 在线返回 true。 - Task IsOnlineAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task IsOnlineAsync(long playerId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlinePlayerDirectory.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlinePlayerDirectory.cs index bca704ced..bfda8623e 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlinePlayerDirectory.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlinePlayerDirectory.cs @@ -44,23 +44,19 @@ namespace GameFrameX.Capability.Online.Abstractions.Contracts; public interface IOnlinePlayerDirectory { /// - /// 按展示名关键字检索玩家(作用域内)。 + /// 按展示名关键字检索玩家。 /// - /// 租户标识。 - /// App 标识。 /// 名称关键字(前后空白由实现忽略;空关键字不返回结果)。 /// 返回条数上限(调用方须传正值)。 /// 取消令牌。 /// 匹配的玩家目录条目(顺序由实现保证稳定)。 - Task> SearchByNameAsync(long tenantId, long appId, string keyword, int limit, CancellationToken cancellationToken = default); + Task> SearchByNameAsync(string keyword, int limit, CancellationToken cancellationToken = default); /// /// 按玩家标识批量解析目录条目(好友列表展示名的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识集合。 /// 取消令牌。 /// 解析到的条目(不存在的标识不出现在结果中)。 - Task> FindAsync(long tenantId, long appId, IReadOnlyList playerIds, CancellationToken cancellationToken = default); + Task> FindAsync(IReadOnlyList playerIds, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineSocialGate.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineSocialGate.cs index 46f692db2..5016b276d 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineSocialGate.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineSocialGate.cs @@ -56,12 +56,10 @@ public interface IOnlineSocialGate /// /// 裁决一次定向社交互动是否允许(屏蔽按双向生效、封禁拒绝全部、禁言只拒绝私聊)。 /// - /// 租户标识。 - /// App 标识。 /// 发起互动的玩家。 /// 互动的目标玩家。 /// 互动目的(决定裁决力度)。 /// 取消令牌。 /// 裁决结果;调用方在 为假时拒绝本次互动。 - Task EvaluateAsync(long tenantId, long appId, long fromPlayerId, long toPlayerId, OnlineSocialInteractionPurpose purpose, CancellationToken cancellationToken = default); + Task EvaluateAsync(long fromPlayerId, long toPlayerId, OnlineSocialInteractionPurpose purpose, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineSocialPresenceProbe.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineSocialPresenceProbe.cs index e88a6ef54..310ada3ad 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineSocialPresenceProbe.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/IOnlineSocialPresenceProbe.cs @@ -42,10 +42,8 @@ public interface IOnlineSocialPresenceProbe /// /// 查询玩家当前是否在线。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 在线返回 true。 - Task IsOnlineAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task IsOnlineAsync(long playerId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAdminApiAdapters.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAdminApiAdapters.cs index d84e36526..023035add 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAdminApiAdapters.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAdminApiAdapters.cs @@ -60,7 +60,7 @@ public static AdminApiErrorCodes ErrorCodes } /// - /// 构造作用域适配器(线缆三元组提取 + 比对)。 + /// 构造作用域适配器(线缆区服键提取 + 比对)。 /// /// 保留参数(既有公共签名兼容):比对用授权作用域由 AdminApiDispatcher 单独持有,经 实参传入。 /// 作用域适配器。 @@ -106,13 +106,13 @@ public static AdminActionHandler Wrap(Func - /// 三元素组作用域 → 。 + /// 机制管道作用域 → 。 /// /// 机制管道作用域。 /// Online 作用域。 internal static OnlineScope ToOnlineScope(AdminApiClaimedScope claimedScope) { - return new OnlineScope(claimedScope.TenantId, claimedScope.AppId, claimedScope.ServerId); + return new OnlineScope(claimedScope.ServerId); } /// @@ -131,10 +131,10 @@ internal static AdminApiErrorCode ToErrorCode(OnlineErrorCode code) private sealed class ScopeAdapter : IAdminApiScopeAdapter { /// - /// 从请求中读取声明的租户、应用、服务器三元素作用域;三者均可读取时组装为机制管道作用域并返回 true,否则输出 null 并返回 false。 + /// 从请求中读取声明的区服键作用域(单键化 D4 后仅 ServerId 位);可读取时组装为机制管道作用域并返回 true,否则输出 null 并返回 false。 /// /// - /// Reads the claimed tenant / app / server triple from the request; when all three are readable it builds an + /// Reads the claimed server key from the request; when readable it builds an /// and returns true, otherwise outputs null and returns false. /// /// 管理 API 请求 / Admin API request @@ -142,9 +142,9 @@ private sealed class ScopeAdapter : IAdminApiScopeAdapter /// 是否成功读取声明作用域 / Whether the claimed scope was read successfully public bool TryReadClaimedScope(AdminApiRequest request, out AdminApiClaimedScope claimedScope) { - if (request.TryReadClaimedScope(out var tenantId, out var appId, out var serverId)) + if (request.TryReadClaimedScope(out var serverId)) { - claimedScope = new AdminApiClaimedScope(tenantId, appId, serverId); + claimedScope = new AdminApiClaimedScope(serverId); return true; } diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAdminApiContract.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAdminApiContract.cs index a505bea67..f065fec95 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAdminApiContract.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAdminApiContract.cs @@ -92,7 +92,7 @@ public static long ReadPlayerId(AdminApiRequest request) /// 含玩家位的作用域。 public static OnlineScope ReadPlayerScope(AdminApiRequest request, OnlineScope scope) { - return new OnlineScope(scope.TenantId, scope.AppId, scope.ServerId, ReadPlayerId(request)); + return new OnlineScope(scope.ServerId, ReadPlayerId(request)); } /// diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAuditRecord.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAuditRecord.cs index fd4ce2c3b..755c5751e 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAuditRecord.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineAuditRecord.cs @@ -64,17 +64,7 @@ public sealed class OnlineAuditRecord public long OccurredTime { get; set; } /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } - - /// - /// 获取或设置区服标识(0 表示 App 级操作)。 + /// 获取或设置区服标识(0 表示全局级操作)。 /// public long ServerId { get; set; } diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineErrorCode.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineErrorCode.cs index b54a831f4..0d443d98c 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineErrorCode.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineErrorCode.cs @@ -32,7 +32,7 @@ namespace GameFrameX.Capability.Online.Abstractions.Contracts; /// /// GFX Online 平台协议错误码(八段分层,Server 侧承载)。 /// -/// 协议码分段固定:1xxx 系统与网络 / 2xxx 鉴权与 Session / 3xxx 租户·App·Server 作用域 / +/// 协议码分段固定:1xxx 系统与网络 / 2xxx 鉴权与 Session / 3xxx 区服作用域(单键化 D4 后租户位/App 位退役,3002/3003 保留数值契约不再产生) / /// 4xxx 参数与资源 / 5xxx 业务状态 / 6xxx 幂等与冲突 / 7xxx 限流与风控 / 8xxx 临时失败与可重试; /// 0 表示成功。成员集合与 Admin 侧错误码表快照(唯一权威详表)的 23 个错误成员一一同构, /// Admin 按「协议段 Nxxx ↔ 镜像段 32(N-1)」映射消费(Admin 仓 OnlineErrorCode 镜像码 32000001~32700002)。 @@ -84,7 +84,7 @@ public enum OnlineErrorCode /// SessionInvalid = 2003, - // ---- 段 3xxx:租户、App、Server 作用域 ---- + // ---- 段 3xxx:区服作用域(单键化 D4 后只剩区服位;3002/3003 为保留位不再产生) ---- /// /// 作用域越界拒绝(泛化越权:不归属其他更具体作用域错误时的兜底拒绝码)。 @@ -92,22 +92,22 @@ public enum OnlineErrorCode ScopeDenied = 3001, /// - /// 跨租户请求被拒绝(作用域三元组的租户与鉴权上下文不一致)。 + /// 跨租户请求被拒绝(保留位:单键化 D4 后作用域无租户位,本码不再产生;数值契约与 Admin 镜像锁定不动)。 /// CrossTenantDenied = 3002, /// - /// 跨 App 请求被拒绝(目标资源不归属当前 AppId)。 + /// 跨 App 请求被拒绝(保留位:单键化 D4 后作用域无 App 位,本码不再产生;数值契约与 Admin 镜像锁定不动)。 /// CrossAppDenied = 3003, /// - /// 区服作用域非法(ServerId 不存在或不归属当前 AppId)。 + /// 区服作用域非法(ServerId 不存在或不归属当前部署)。 /// ServerScopeDenied = 3004, /// - /// 作用域缺失(TenantId/AppId/ServerId 未提供且无法从鉴权上下文补齐)。 + /// 作用域缺失(ServerId 未提供且无法从鉴权上下文补齐)。 /// ScopeMissing = 3005, diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineRequestContext.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineRequestContext.cs index da61b9fde..fab77eeb7 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineRequestContext.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Contracts/OnlineRequestContext.cs @@ -33,8 +33,8 @@ namespace GameFrameX.Capability.Online.Abstractions.Contracts; /// Online 公共请求上下文(任何 Online 请求至少包含 RequestId、ProtocolVersion、 /// ClientVersion、Timestamp;产生副作用的请求必须携带 IdempotencyKey)。 /// -/// 维护约束:TenantId/AppId/ServerId 以鉴权或服务端路由为准,不由本上下文的客户端字段直接覆盖 -/// (作用域统一经 OnlineScope 由服务端管线注入);RequestId 标识一次请求尝试, +/// 维护约束:ServerId 以鉴权或服务端路由为准,不由本上下文的客户端字段直接覆盖 +/// (作用域统一经 OnlineScope 由服务端管线注入;单键化 D4 后无租户位/App 位);RequestId 标识一次请求尝试, /// IdempotencyKey 标识一次业务意图,二者语义不同不可混用。 /// /// diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEvent.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEvent.cs index 4f0ea0a5b..d90105a2b 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEvent.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEvent.cs @@ -31,7 +31,7 @@ namespace GameFrameX.Capability.Online.Abstractions.Events; /// /// Online 事件信封(事件契约:EventId/EventType/OccurredAt/SchemaVersion + -/// TenantId/AppId/ServerId/PlayerId + Source/CorrelationId/Payload)。 +/// ServerId/PlayerId + Source/CorrelationId/Payload;单键化 D4 后无租户位/App 位)。 /// /// 维护约束:事件代表已经发生的事实,不作为当前状态的唯一存储(状态由 Actor 持有); /// EventId 全局唯一(消费端去重键);CorrelationId 贯穿业务链路; @@ -62,16 +62,6 @@ public sealed class OnlineEvent /// public int SchemaVersion { get; set; } - /// - /// 获取或设置租户标识(Online 作用域字段)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(Online 作用域字段)。 - /// - public long AppId { get; set; } - /// /// 获取或设置区服标识(Online 作用域字段)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventAuditView.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventAuditView.cs index 8fd39cc11..613a381aa 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventAuditView.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventAuditView.cs @@ -58,16 +58,6 @@ public sealed class OnlineEventAuditView /// public int SchemaVersion { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置区服标识。 /// diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventEnvelopeMapper.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventEnvelopeMapper.cs index 055a42a1b..d03e0a8c2 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventEnvelopeMapper.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventEnvelopeMapper.cs @@ -35,23 +35,14 @@ namespace GameFrameX.Capability.Online.Abstractions.Events; /// Online 事件与 Foundation 事件信封的双向映射(红线:Online 领域语义不进 Foundation, /// 作用域字段经 Foundation 信封 Attributes 稳定键承载)。 /// -/// 维护约束:稳定键 online.tenantId/online.appId/online.serverId/online.playerId -/// 为跨端契约,禁止重命名或挪用;未知 Attributes 键在反向映射时原样保留于 ExtraAttributes 语义外(当前丢弃), +/// 维护约束:稳定键 online.serverId/online.playerId +/// 为跨端契约,禁止重命名或挪用(单键化 D4 后不再有租户位/App 位稳定键); +/// 未知 Attributes 键在反向映射时原样保留于 ExtraAttributes 语义外(当前丢弃), /// 新增传输字段必须走信封结构版本评审。 /// /// public static class OnlineEventEnvelopeMapper { - /// - /// Attributes 稳定键:租户标识。 - /// - public const string TenantAttributeKey = "online.tenantId"; - - /// - /// Attributes 稳定键:App 标识。 - /// - public const string AppAttributeKey = "online.appId"; - /// /// Attributes 稳定键:区服标识。 /// @@ -76,8 +67,6 @@ public static EventEnvelope ToEnvelope(OnlineEvent onlineEvent) var attributes = new Dictionary { - { TenantAttributeKey, onlineEvent.TenantId.ToString() }, - { AppAttributeKey, onlineEvent.AppId.ToString() }, { ServerAttributeKey, onlineEvent.ServerId.ToString() }, { PlayerAttributeKey, onlineEvent.PlayerId.ToString() }, }; @@ -106,8 +95,6 @@ public static OnlineEvent FromEnvelope(EventEnvelope envelope) Source = envelope.Source, CorrelationId = envelope.CorrelationId, Payload = envelope.Payload, - TenantId = ReadInt64(envelope, TenantAttributeKey), - AppId = ReadInt64(envelope, AppAttributeKey), ServerId = ReadInt64(envelope, ServerAttributeKey), PlayerId = ReadInt64(envelope, PlayerAttributeKey), }; diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventSanitizer.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventSanitizer.cs index 8526d77e0..3e15fb34e 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventSanitizer.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Events/OnlineEventSanitizer.cs @@ -105,8 +105,6 @@ public OnlineEventAuditView CreateAuditView(OnlineEvent onlineEvent) EventType = onlineEvent.EventType, OccurredTime = onlineEvent.OccurredTime, SchemaVersion = onlineEvent.SchemaVersion, - TenantId = onlineEvent.TenantId, - AppId = onlineEvent.AppId, ServerId = onlineEvent.ServerId, PlayerId = onlineEvent.PlayerId, Source = onlineEvent.Source, diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Keys/OnlineRowKey.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Keys/OnlineRowKey.cs new file mode 100644 index 000000000..dda50e383 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Keys/OnlineRowKey.cs @@ -0,0 +1,150 @@ +// ========================================================================================== +// 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 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 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.Capability.Online.Abstractions.Keys; + +/// +/// Online 物化行键唯一构造点(C462 单键化裁决 D4:全链只删 Tenant/App 两位,绝不新增 ServerId 位)。 +/// +/// 维护约束(红线): +/// ① 全部持久化行键 / InMemory 同构键**只能**经本类构造,禁止各包自拼字符串(键形漂移 = 唯一索引失效); +/// ② 行键分两类铁律——**全局域键**(好友对、身份、玩家存储、钱包/账本、库存、排行投影:主体是玩家或玩家对, +/// 跨服共享、合服零操作,键内**不得**出现 ServerId 位)与**区服域键**(对局结算等区服维度数据:合服按位重写; +/// 对局标识为 match-{Guid:N} 全局唯一,键内无需 ServerId 位,区服维度由行实体 ServerId 快照列承载); +/// ③ 键形变更必须递增 并走数据迁移评审(2.0 断代无存量数据,首代直接落位)。 +/// +/// +public static class OnlineRowKey +{ + /// + /// 行键 schema 代际(1 = 2.0 单键键形首代;旧三元组键形随 2.0 断代退役,不作迁移)。 + /// + public const int RowKeySchemaVersion = 1; + + /// + /// 构造好友关系全局域键(friend:{低玩家}:{高玩家};规范化无向对——好友是全局关系, + /// 跨服加好友天然成立,合服对全局域零操作)。 + /// + /// 无向对低标识侧玩家。 + /// 无向对高标识侧玩家。 + /// 物化复合键。 + public static string Friendship(long lowPlayerId, long highPlayerId) + { + return "friend:" + lowPlayerId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + highPlayerId.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// 构造登录身份全局域键({身份类型}:{身份标识串};身份归玩家全局所有,合服零操作)。 + /// + /// 身份类型(域枚举数值,调用点以 (int) 投影——本类不可下行引用域包枚举)。 + /// 身份标识串。 + /// 物化复合键。 + public static string Identity(int identityKind, string identifier) + { + return identityKind.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + identifier; + } + + /// + /// 构造玩家设备全局域键({游戏账号}:{设备标识})。 + /// + /// 游戏账号标识。 + /// 设备唯一标识串。 + /// 物化复合键。 + public static string PlayerDevice(long gameAccountId, string deviceIdentifier) + { + return gameAccountId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + deviceIdentifier; + } + + /// + /// 构造玩家存储条目全局域键({玩家}:{集合名}:{条目键};玩家数据跨服共享,合服零操作)。 + /// + /// 玩家标识。 + /// 集合名。 + /// 条目键。 + /// 物化复合键。 + public static string PlayerStorage(long playerId, string collection, string key) + { + return playerId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + collection + ":" + key; + } + + /// + /// 构造玩家账本序键控序列名({玩家};账本追加式天然可并,合服零操作)。 + /// + /// 玩家标识。 + /// 键控序列名。 + public static string LedgerSequence(long playerId) + { + return playerId.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// 构造钱包账户全局域键({玩家}:{货币代码};钱包归玩家全局所有,合服零操作)。 + /// + /// 玩家标识。 + /// 货币代码。 + /// 物化复合键。 + public static string WalletAccount(long playerId, string currencyId) + { + return playerId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + currencyId; + } + + /// + /// 构造库存堆叠全局域键({玩家}:{道具标识})。 + /// + /// 玩家标识。 + /// 道具标识。 + /// 物化复合键。 + public static string InventoryStack(long playerId, string itemId) + { + return playerId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + itemId; + } + + /// + /// 构造批次内资产去重键({玩家}:{c|i}:{资产标识};c=货币 i=道具)。 + /// + /// 玩家标识。 + /// 是否货币类资产(true=c 货币位 / false=i 道具位;域枚举在调用点判定——本类不可下行引用域包枚举)。 + /// 资产标识。 + /// 物化复合键。 + public static string AssetDedup(long playerId, bool isCurrency, string assetId) + { + return playerId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + (isCurrency ? "c" : "i") + ":" + assetId; + } + + /// + /// 构造对局结算结果区服域键({对局标识};对局标识为 match-{Guid:N} 全局唯一, + /// GUID 消解跨服碰撞;区服维度由行实体 ServerId 快照列承载,合服按列过滤重写归属)。 + /// + /// 对局标识(服务端生成的全局唯一字符串)。 + /// 物化复合键。 + public static string MatchResult(string matchId) + { + return matchId; + } +} diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/OnlineCapabilityFamily.cs b/Capability/GameFrameX.Capability.Online.Abstractions/OnlineCapabilityFamily.cs index 1cc2435a2..1e085f0c7 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/OnlineCapabilityFamily.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/OnlineCapabilityFamily.cs @@ -43,8 +43,8 @@ namespace GameFrameX.Capability.Online.Abstractions; /// 族基建收敛在族脊柱包内)。族标识 online,配置段 Online,部署程序集前缀 /// GameFrameX.Capability.Online。 /// -/// 维护约束(族基建预置,语句级迁移自旧组合根 BuildScannedRuntime):授权作用域(三元组取自 -/// 族配置段 TenantId/AppId/ServerId,缺失或非法 = 装配期 fail-fast——作用域是 +/// 维护约束(族基建预置,语句级迁移自旧组合根 BuildScannedRuntime):授权作用域(单键化 D4 后 +/// 区服键取自族配置段 ServerId,缺失或非法 = 装配期 fail-fast——作用域是 /// 数据隔离根边界,无默认值可回落)、Online 事件出口( 委托机制 /// 事件总线)、幂等(,InMemory 协调器 + 失败重放策略 ReExecute)、 /// 统一审计( 具型 + 读面,同源单例)。 @@ -94,11 +94,9 @@ public void RegisterInfrastructure(CapabilityFamilyContext context) throw new ArgumentNullException(nameof(context)); } - // 授权作用域:三元组取自族配置段;缺失 / 非正数 = 装配期 fail-fast(无默认值可回落)。 - var tenantId = ReadScopeKey(context.ConfigurationSection, "TenantId"); - var appId = ReadScopeKey(context.ConfigurationSection, "AppId"); + // 授权作用域:区服键取自族配置段;缺失 / 非正数 = 装配期 fail-fast(无默认值可回落)。 var serverId = ReadScopeKey(context.ConfigurationSection, "ServerId"); - var scope = new OnlineScope(tenantId, appId, serverId); + var scope = new OnlineScope(serverId); context.AddService(scope); // 事件出口:业务发布面委托机制事件总线(主题 = 事件类型字符串,Activate 开始前拒绝发布)。 diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/OnlineChatMessage.cs b/Capability/GameFrameX.Capability.Online.Abstractions/OnlineChatMessage.cs index 3c6246e92..9a0aacfbe 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/OnlineChatMessage.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/OnlineChatMessage.cs @@ -48,16 +48,6 @@ public sealed class OnlineChatMessage /// public string MessageId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置所属频道标识。 /// @@ -118,8 +108,6 @@ public OnlineChatMessage Copy() return new OnlineChatMessage { MessageId = MessageId, - TenantId = TenantId, - AppId = AppId, ChannelId = ChannelId, ChannelKind = ChannelKind, SenderId = SenderId, diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScope.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScope.cs index 37a306d0f..04ec03208 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScope.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScope.cs @@ -30,9 +30,10 @@ namespace GameFrameX.Capability.Online.Abstractions.Scope; /// -/// Online 作用域(TenantId/AppId/ServerId 以鉴权或服务端路由为准,不能由客户端字段直接覆盖)。 +/// Online 作用域(ServerId 以鉴权或服务端路由为准,不能由客户端字段直接覆盖;单键化裁决 D4—— +/// 租户位/App 位随 2.0 断代移除,区服键是唯一数据隔离根边界)。 /// -/// 维护约束:作用域三元组是数据隔离的根边界——跨租户/跨 App/跨服请求必须被拒绝并留审计; +/// 维护约束:跨服请求必须被拒绝并留审计; /// PlayerId 为可选主体位,面向玩家级操作(幂等键绑定、事件归属)时必填。客户端提交的同名字段 /// 一律经 OnlineScopeResolver.EnforceAuthorized 以鉴权上下文覆盖,服务端不信任请求体作用域。 /// @@ -40,17 +41,7 @@ namespace GameFrameX.Capability.Online.Abstractions.Scope; public sealed class OnlineScope { /// - /// 获取租户标识(鉴权上下文强制注入,请求任何入口都不可覆盖)。 - /// - public long TenantId { get; } - - /// - /// 获取 App 标识(必须归属当前租户,经租户归属校验)。 - /// - public long AppId { get; } - - /// - /// 获取区服标识(必须归属当前 AppId,经区服归属校验)。 + /// 获取区服标识(鉴权上下文强制注入,请求任何入口都不可覆盖;经区服归属校验)。 /// public long ServerId { get; } @@ -62,27 +53,23 @@ public sealed class OnlineScope /// /// 构造作用域。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 玩家标识(无主体时传 0)。 - public OnlineScope(long tenantId, long appId, long serverId, long playerId = 0) + public OnlineScope(long serverId, long playerId = 0) { - TenantId = tenantId; - AppId = appId; ServerId = serverId; PlayerId = playerId; } /// - /// 计算作用域的稳定字符串形式(tenant:app:server[:player];玩家级操作含玩家位), + /// 计算作用域的稳定字符串形式(online:server[:player];玩家级操作含玩家位), /// 作为幂等记录的作用域绑定键与日志留痕标识。 /// /// 是否包含玩家位(玩家级幂等绑定时必须为 true,防止跨玩家复用幂等键)。 /// 作用域键字符串。 public string ToScopeKey(bool includePlayer) { - var key = "online:" + TenantId + ":" + AppId + ":" + ServerId; + var key = "online:" + ServerId; if (includePlayer) { key += ":" + PlayerId; diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScopeGuard.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScopeGuard.cs index 0924de6e9..1a98cf930 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScopeGuard.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScopeGuard.cs @@ -32,7 +32,8 @@ namespace GameFrameX.Capability.Online.Abstractions.Scope; /// -/// Online 作用域守卫(跨 Tenant/App/Server 请求被稳定拒绝且留审计)。 +/// Online 作用域守卫(跨服请求被稳定拒绝且留审计;单键化 D4 后租户位/App 位不复存在, +/// CrossTenantDenied/CrossAppDenied 数值契约保留但不再产生)。 /// /// 维护约束:四端(Server / Client API / Hub API / Admin API)统一经本守卫判定,禁止各 Handler 自行判断; /// 判定拒绝必须 100% 留痕(审计钩子由调用方接线,拒绝码走 3xxx 段)。 @@ -45,7 +46,7 @@ public static class OnlineScopeGuard /// /// 目标作用域(被访问资源或目标操作的归属作用域)。 /// 实际生效作用域(鉴权上下文解析产物)。 - /// 接纳返回 ;拒绝返回 3xxx 段错误码(跨租户/跨 App/跨服分别映射)。 + /// 接纳返回 ;拒绝返回 3xxx 段错误码(跨服映射 、缺失映射 )。 public static OnlineErrorCode? Validate(OnlineScope targetScope, OnlineScope actualScope) { if (targetScope == null || actualScope == null) @@ -53,22 +54,11 @@ public static class OnlineScopeGuard return OnlineErrorCode.ScopeMissing; } - if (targetScope.TenantId <= 0 || targetScope.AppId <= 0 || targetScope.ServerId <= 0 || - actualScope.TenantId <= 0 || actualScope.AppId <= 0 || actualScope.ServerId <= 0) + if (targetScope.ServerId <= 0 || actualScope.ServerId <= 0) { return OnlineErrorCode.ScopeMissing; } - if (actualScope.TenantId != targetScope.TenantId) - { - return OnlineErrorCode.CrossTenantDenied; - } - - if (actualScope.AppId != targetScope.AppId) - { - return OnlineErrorCode.CrossAppDenied; - } - if (actualScope.ServerId != targetScope.ServerId) { return OnlineErrorCode.ServerScopeDenied; diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScopeResolver.cs b/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScopeResolver.cs index 468ecf996..08a580c9c 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScopeResolver.cs +++ b/Capability/GameFrameX.Capability.Online.Abstractions/Scope/OnlineScopeResolver.cs @@ -35,25 +35,16 @@ namespace GameFrameX.Capability.Online.Abstractions.Scope; /// Online 作用域解析器(作用域在 Server / Client API / Hub API / Admin API 四端间传递, /// 以鉴权上下文为准,客户端伪造字段被忽略)。 /// -/// 维护约束:字段名兼容 Admin 既成事实——GET 查询参数 camelCase(tenantId/appId/serverId)、 -/// POST 请求体 PascalCase 合并字段(TenantId/AppId/ServerId),本解析器按键名大小写不敏感统一提取; +/// 维护约束:字段名兼容 Admin 既成事实——GET 查询参数 camelCase(serverId)、 +/// POST 请求体 PascalCase 合并字段(ServerId),本解析器按键名大小写不敏感统一提取; /// 提取结果只是「客户端声称」,必须经 与鉴权上下文合并后方可使用。 +/// 单键化(D4)后客户端携带的租户位/App 位遗留字段一律忽略(无对应作用域位)。 /// /// public static class OnlineScopeResolver { /// - /// 作用域租户字段名(查询参数 camelCase 形态;body PascalCase 形态经大小写不敏感匹配覆盖)。 - /// - public const string TenantFieldName = "tenantId"; - - /// - /// 作用域 App 字段名。 - /// - public const string AppFieldName = "appId"; - - /// - /// 作用域区服字段名。 + /// 作用域区服字段名(查询参数 camelCase 形态;body PascalCase 形态经大小写不敏感匹配覆盖)。 /// public const string ServerFieldName = "serverId"; @@ -62,7 +53,7 @@ public static class OnlineScopeResolver /// /// 请求参数字典(键大小写不敏感处理)。 /// 鉴权上下文作用域(服务端权威值,客户端同名字段不可覆盖)。 - /// 提取失败时的错误码(三元组缺失或格式非法时为 )。 + /// 提取失败时的错误码(区服键缺失或格式非法时为 )。 /// 提取成功返回合并鉴权上下文后的作用域;失败返回 。 public static OnlineScope TryResolve(IReadOnlyDictionary parameters, OnlineScope authorizedScope, out OnlineErrorCode error) { @@ -73,26 +64,22 @@ public static OnlineScope TryResolve(IReadOnlyDictionary paramet } // 鉴权上下文(服务端权威)直接生效;客户端字段仅用于服务端路由参考,永远不覆盖鉴权值。 - var claimedTenantId = ReadInt64(parameters, TenantFieldName, authorizedScope.TenantId); - var claimedAppId = ReadInt64(parameters, AppFieldName, authorizedScope.AppId); var claimedServerId = ReadInt64(parameters, ServerFieldName, authorizedScope.ServerId); - if (claimedTenantId != authorizedScope.TenantId || claimedAppId != authorizedScope.AppId || claimedServerId != authorizedScope.ServerId) + if (claimedServerId != authorizedScope.ServerId) { // 客户端声称与鉴权上下文不一致:以鉴权为准忽略声称值;是否构成越权拒绝由 Guard 判定(留审计)。 - claimedTenantId = authorizedScope.TenantId; - claimedAppId = authorizedScope.AppId; claimedServerId = authorizedScope.ServerId; } - if (authorizedScope.TenantId <= 0 || authorizedScope.AppId <= 0 || authorizedScope.ServerId <= 0) + if (authorizedScope.ServerId <= 0) { error = OnlineErrorCode.ScopeMissing; return null; } error = OnlineErrorCode.None; - return new OnlineScope(authorizedScope.TenantId, authorizedScope.AppId, authorizedScope.ServerId, authorizedScope.PlayerId); + return new OnlineScope(authorizedScope.ServerId, authorizedScope.PlayerId); } /// diff --git a/Capability/GameFrameX.Capability.Online.Assets/AdminApi/OnlineAdminAssetHandlers.cs b/Capability/GameFrameX.Capability.Online.Assets/AdminApi/OnlineAdminAssetHandlers.cs index 3100f7a22..3a9687942 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/AdminApi/OnlineAdminAssetHandlers.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/AdminApi/OnlineAdminAssetHandlers.cs @@ -256,7 +256,7 @@ public async Task QueryAssetAuditAsync(AdminApiRequest request, OnlineSc Cursor = OnlineAdminApiContract.ReadCursor(request), PageSize = OnlineAdminApiContract.ReadPageSize(request), }; - var page = OnlineAdminApiContract.Unwrap(await _audit.QueryAsync(scope, query, cancellationToken).ConfigureAwait(false)); + var page = OnlineAdminApiContract.Unwrap(await _audit.QueryAsync(query, cancellationToken).ConfigureAwait(false)); var items = new List(); foreach (var record in page.Records) { @@ -296,14 +296,14 @@ public async Task QueryTransactionDetailAsync(AdminApiRequest request, O { var transactionId = OnlineAdminApiContract.RequireString(request, "TransactionId"); var storedTransaction = await _assetTransactionStore.FindAsync(transactionId, cancellationToken).ConfigureAwait(false); - if (storedTransaction == null || storedTransaction.TenantId != scope.TenantId || storedTransaction.AppId != scope.AppId) + if (storedTransaction == null) { // Localization: Online.AdminApi.TransactionNotFound - 交易不存在:{0} throw new OnlineServiceException(OnlineErrorCode.ResourceNotFound, LocalizationService.GetString(Localization.Keys.Online.AdminApi.TransactionNotFound, transactionId)); } // 线缆契约:query_transaction_detail 只携带交易标识;玩家位由交易记录回查补全(查询面按玩家位校验)。 - var playerScope = new OnlineScope(scope.TenantId, scope.AppId, scope.ServerId, storedTransaction.PlayerId); + var playerScope = new OnlineScope(scope.ServerId, storedTransaction.PlayerId); var detail = OnlineAdminApiContract.Unwrap(await _assetQuery.GetTransactionDetailAsync(playerScope, transactionId, cancellationToken).ConfigureAwait(false)); if (detail == null || detail.Transaction == null) { diff --git a/Capability/GameFrameX.Capability.Online.Assets/IOnlineAssetStore.cs b/Capability/GameFrameX.Capability.Online.Assets/IOnlineAssetStore.cs index bad7c75ce..617b7ec75 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/IOnlineAssetStore.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/IOnlineAssetStore.cs @@ -47,38 +47,30 @@ namespace GameFrameX.Capability.Online.Assets; public interface IOnlineAssetStore { /// 查找货币账户快照。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 货币代码。 /// 取消令牌。 /// 账户快照;从未发生过变更返回 null(视余额为 0)。 - Task FindWalletAsync(long tenantId, long appId, long playerId, string currencyId, CancellationToken cancellationToken = default); + Task FindWalletAsync(long playerId, string currencyId, CancellationToken cancellationToken = default); /// 查找道具库存堆栈快照。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 道具标识。 /// 取消令牌。 /// 库存快照;从未发生过变更返回 null(视数量为 0)。 - Task FindInventoryAsync(long tenantId, long appId, long playerId, string itemId, CancellationToken cancellationToken = default); + Task FindInventoryAsync(long playerId, string itemId, CancellationToken cancellationToken = default); /// 列举玩家全部货币账户快照(对账与 Admin 查询输入)。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 账户快照列表(按货币代码字典序)。 - Task> ListWalletAccountsAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task> ListWalletAccountsAsync(long playerId, CancellationToken cancellationToken = default); /// 列举玩家全部道具库存快照(对账与 Admin 查询输入)。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 库存快照列表(按道具标识字典序)。 - Task> ListInventoryStacksAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task> ListInventoryStacksAsync(long playerId, CancellationToken cancellationToken = default); /// 原子应用变更批次(玩家分片事务:先全量校验下限 0,后统一追加账本并同步快照)。 /// 变更批次(仅限本程序集统一入口构造)。 @@ -99,17 +91,13 @@ public interface IOnlineAssetStore Task> FindLedgerEntriesByTransactionIdAsync(string transactionId, CancellationToken cancellationToken = default); /// 聚合玩家账本带符号数额(对账的账本侧事实源;键 = 类别前缀 + 资产标识)。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 各资产账本累加(键:c: 货币 / i: 道具 + 资产标识)。 - Task> SumLedgerDeltasByAssetAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task> SumLedgerDeltasByAssetAsync(long playerId, CancellationToken cancellationToken = default); - /// 列举 (租户, App) 下发生过资产活动的玩家(全量对账的遍历输入)。 - /// 租户标识。 - /// App 标识。 + /// 列举发生过资产活动的玩家(全量对账的遍历输入)。 /// 取消令牌。 /// 玩家标识列表(升序去重)。 - Task> ListPlayerIdsAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListPlayerIdsAsync(CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Assets/InMemoryOnlineAssetStore.cs b/Capability/GameFrameX.Capability.Online.Assets/InMemoryOnlineAssetStore.cs index afee2aa7a..586cf8839 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/InMemoryOnlineAssetStore.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/InMemoryOnlineAssetStore.cs @@ -33,6 +33,7 @@ namespace GameFrameX.Capability.Online.Assets; using System.Threading; using System.Threading.Tasks; using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Keys; /// /// 资产存储内存默认实现(单进程/测试默认实现;生产装配以持久化实现替换)。 @@ -49,67 +50,61 @@ public sealed class InMemoryOnlineAssetStore : IOnlineAssetStore /// 分片锁注册表守卫锁。 private readonly object _registryLock = new(); - /// 玩家分片锁注册表:键 = tenant:app:player。 + /// 玩家分片锁注册表:键 = 玩家标识。 private readonly Dictionary _playerLocks = new(); - /// 货币账户快照:键 = tenant:app:player:货币代码。 + /// 货币账户快照:键 = player:货币代码()。 private readonly Dictionary _wallets = new(); - /// 道具库存快照:键 = tenant:app:player:道具标识。 + /// 道具库存快照:键 = player:道具标识()。 private readonly Dictionary _inventories = new(); - /// 账本条目(按玩家归组,组内按账本序升序):键 = tenant:app:player。 + /// 账本条目(按玩家归组,组内按账本序升序):键 = 玩家标识()。 private readonly Dictionary> _ledgerByPlayer = new(); /// 交易 → 账本条目反查索引(追加时维护)。 private readonly Dictionary> _ledgerByTransaction = new(); - /// 玩家维度账本序计数器:键 = tenant:app:player。 + /// 玩家维度账本序计数器:键 = 玩家标识()。 private readonly Dictionary _sequenceByPlayer = new(); /// 查找货币账户快照。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 货币代码。 /// 取消令牌。 /// 账户快照;未发生过变更返回 null。 - public Task FindWalletAsync(long tenantId, long appId, long playerId, string currencyId, CancellationToken cancellationToken = default) + public Task FindWalletAsync(long playerId, string currencyId, CancellationToken cancellationToken = default) { lock (_registryLock) { - _wallets.TryGetValue(BuildAssetKey(tenantId, appId, playerId, OnlineAssetKind.Currency, currencyId), out var account); + _wallets.TryGetValue(OnlineRowKey.WalletAccount(playerId, currencyId), out var account); return Task.FromResult(account); } } /// 查找道具库存快照。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 道具标识。 /// 取消令牌。 /// 库存快照;未发生过变更返回 null。 - public Task FindInventoryAsync(long tenantId, long appId, long playerId, string itemId, CancellationToken cancellationToken = default) + public Task FindInventoryAsync(long playerId, string itemId, CancellationToken cancellationToken = default) { lock (_registryLock) { - _inventories.TryGetValue(BuildAssetKey(tenantId, appId, playerId, OnlineAssetKind.Item, itemId), out var stack); + _inventories.TryGetValue(OnlineRowKey.InventoryStack(playerId, itemId), out var stack); return Task.FromResult(stack); } } /// 列举玩家全部货币账户快照。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 账户快照列表(按货币代码字典序)。 - public Task> ListWalletAccountsAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListWalletAccountsAsync(long playerId, CancellationToken cancellationToken = default) { lock (_registryLock) { - var prefix = BuildPlayerPrefix(tenantId, appId, playerId); + var prefix = OnlineRowKey.LedgerSequence(playerId) + ":"; var accounts = new List(); foreach (var pair in _wallets) { @@ -125,16 +120,14 @@ public Task> ListWalletAccountsAsync(long ten } /// 列举玩家全部道具库存快照。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 库存快照列表(按道具标识字典序)。 - public Task> ListInventoryStacksAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListInventoryStacksAsync(long playerId, CancellationToken cancellationToken = default) { lock (_registryLock) { - var prefix = BuildPlayerPrefix(tenantId, appId, playerId); + var prefix = OnlineRowKey.LedgerSequence(playerId) + ":"; var stacks = new List(); foreach (var pair in _inventories) { @@ -160,7 +153,7 @@ public Task ApplyAsync(OnlineAssetChangeBatch batch, Can throw new ArgumentNullException(nameof(batch)); } - var playerLock = GetPlayerLock(batch.TenantId, batch.AppId, batch.PlayerId); + var playerLock = GetPlayerLock(batch.PlayerId); lock (playerLock) { // 校验 1:同批次同一 (类别, 资产标识) 只允许一行。 @@ -179,7 +172,7 @@ public Task ApplyAsync(OnlineAssetChangeBatch batch, Can } // 落账:快照同步 + 账本追加 + 索引维护(分片锁内原子,中途不可见)。 - CommitEntries(batch.TenantId, batch.AppId, batch.PlayerId, planned, occurredTime); + CommitEntries(batch.PlayerId, planned, occurredTime); return Task.FromResult(new OnlineAssetApplyResult(true, OnlineErrorCode.None, string.Empty, planned)); } } @@ -194,7 +187,7 @@ private OnlineAssetApplyResult ValidateBatchAssetUniqueness(OnlineAssetChangeBat var seenAssets = new HashSet(StringComparer.Ordinal); foreach (var line in batch.Lines) { - if (!seenAssets.Add(BuildAssetKey(batch.TenantId, batch.AppId, batch.PlayerId, line.AssetKind, line.AssetId))) + if (!seenAssets.Add(OnlineRowKey.AssetDedup(batch.PlayerId, line.AssetKind == OnlineAssetKind.Currency, line.AssetId))) { return new OnlineAssetApplyResult(false, OnlineErrorCode.ParameterInvalid, "同一批次内资产重复:" + line.AssetId, Array.Empty()); } @@ -236,26 +229,23 @@ private OnlineAssetApplyResult PlanEntries(OnlineAssetChangeBatch batch, long oc /// 变更前数量。 private long ReadAmountBefore(OnlineAssetChangeBatch batch, OnlineAssetChangeLine line) { - var assetKey = BuildAssetKey(batch.TenantId, batch.AppId, batch.PlayerId, line.AssetKind, line.AssetId); if (line.AssetKind == OnlineAssetKind.Currency) { - return _wallets.TryGetValue(assetKey, out var wallet) ? wallet.Balance : 0; + return _wallets.TryGetValue(OnlineRowKey.WalletAccount(batch.PlayerId, line.AssetId), out var wallet) ? wallet.Balance : 0; } - return _inventories.TryGetValue(assetKey, out var stack) ? stack.Quantity : 0; + return _inventories.TryGetValue(OnlineRowKey.InventoryStack(batch.PlayerId, line.AssetId), out var stack) ? stack.Quantity : 0; } /// /// 落账:快照同步 + 账本追加 + 索引维护(分片锁内原子,中途不可见;必须在玩家分片锁内调用)。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 预演构造的账本条目。 /// 落账时刻。 - private void CommitEntries(long tenantId, long appId, long playerId, List planned, long occurredTime) + private void CommitEntries(long playerId, List planned, long occurredTime) { - var playerKey = BuildPlayerKey(tenantId, appId, playerId); + var playerKey = OnlineRowKey.LedgerSequence(playerId); foreach (var entry in planned) { if (entry.AssetKind == OnlineAssetKind.Currency) @@ -276,10 +266,10 @@ private void CommitEntries(long tenantId, long appId, long playerId, List落账时刻。 private void UpsertWallet(OnlineLedgerEntry entry, long occurredTime) { - var assetKey = BuildAssetKey(entry.TenantId, entry.AppId, entry.PlayerId, entry.AssetKind, entry.AssetId); + var assetKey = OnlineRowKey.WalletAccount(entry.PlayerId, entry.AssetId); if (!_wallets.TryGetValue(assetKey, out var wallet)) { - wallet = new OnlineWalletAccount { TenantId = entry.TenantId, AppId = entry.AppId, PlayerId = entry.PlayerId, CurrencyId = entry.AssetId, Balance = 0, Version = 0, }; + wallet = new OnlineWalletAccount { PlayerId = entry.PlayerId, CurrencyId = entry.AssetId, Balance = 0, Version = 0, }; _wallets[assetKey] = wallet; } @@ -293,10 +283,10 @@ private void UpsertWallet(OnlineLedgerEntry entry, long occurredTime) /// 落账时刻。 private void UpsertInventoryStack(OnlineLedgerEntry entry, long occurredTime) { - var assetKey = BuildAssetKey(entry.TenantId, entry.AppId, entry.PlayerId, entry.AssetKind, entry.AssetId); + var assetKey = OnlineRowKey.InventoryStack(entry.PlayerId, entry.AssetId); if (!_inventories.TryGetValue(assetKey, out var stack)) { - stack = new OnlineInventoryStack { TenantId = entry.TenantId, AppId = entry.AppId, PlayerId = entry.PlayerId, ItemId = entry.AssetId, Quantity = 0, Version = 0, }; + stack = new OnlineInventoryStack { PlayerId = entry.PlayerId, ItemId = entry.AssetId, Quantity = 0, Version = 0, }; _inventories[assetKey] = stack; } @@ -332,14 +322,12 @@ private void AppendToLedgerIndexes(string playerKey, OnlineLedgerEntry entry) /// 账本条目列表(按序升序)。 public Task> ListLedgerEntriesAsync(OnlineLedgerPageQuery query, CancellationToken cancellationToken = default) { - var tenantId = query.TenantId; - var appId = query.AppId; var playerId = query.PlayerId; var afterSequenceNumber = query.AfterSequenceNumber; var maxCount = query.MaxCount; lock (_registryLock) { - if (!_ledgerByPlayer.TryGetValue(BuildPlayerKey(tenantId, appId, playerId), out var ledger)) + if (!_ledgerByPlayer.TryGetValue(OnlineRowKey.LedgerSequence(playerId), out var ledger)) { return Task.FromResult>(Array.Empty()); } @@ -379,17 +367,15 @@ public Task> FindLedgerEntriesByTransactionIdAs } /// 聚合玩家账本带符号数额。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 各资产账本累加。 - public Task> SumLedgerDeltasByAssetAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> SumLedgerDeltasByAssetAsync(long playerId, CancellationToken cancellationToken = default) { lock (_registryLock) { var sums = new Dictionary(); - if (_ledgerByPlayer.TryGetValue(BuildPlayerKey(tenantId, appId, playerId), out var ledger)) + if (_ledgerByPlayer.TryGetValue(OnlineRowKey.LedgerSequence(playerId), out var ledger)) { foreach (var entry in ledger) { @@ -404,25 +390,16 @@ public Task> SumLedgerDeltasByAssetAsync(long } /// 列举发生过资产活动的玩家。 - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 玩家标识列表(升序去重)。 - public Task> ListPlayerIdsAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListPlayerIdsAsync(CancellationToken cancellationToken = default) { lock (_registryLock) { - var prefix = tenantId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + appId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":"; var playerIds = new HashSet(); foreach (var pair in _ledgerByPlayer) { - if (!pair.Key.StartsWith(prefix, StringComparison.Ordinal)) - { - continue; - } - - var segments = pair.Key.Split(':'); - if (segments.Length == 3 && long.TryParse(segments[2], out var playerId)) + if (long.TryParse(pair.Key, System.Globalization.CultureInfo.InvariantCulture, out var playerId)) { playerIds.Add(playerId); } @@ -445,21 +422,19 @@ public Task> ListPlayerIdsAsync(long tenantId, long appId, C /// 账本条目。 private OnlineLedgerEntry BuildEntry(OnlineAssetChangeBatch batch, OnlineAssetChangeLine line, long amountBefore, long amountAfter, long occurredTime) { - var playerKey = BuildPlayerKey(batch.TenantId, batch.AppId, batch.PlayerId); + var playerKey = OnlineRowKey.LedgerSequence(batch.PlayerId); _sequenceByPlayer.TryGetValue(playerKey, out var sequence); sequence++; _sequenceByPlayer[playerKey] = sequence; - return new OnlineLedgerEntry("led-" + Guid.NewGuid().ToString("N"), batch.TransactionId, new OnlineLedgerHeader { TenantId = batch.TenantId, AppId = batch.AppId, PlayerId = batch.PlayerId, HomeServerId = batch.HomeServerId, InitiatingServerId = batch.InitiatingServerId, Source = batch.Source, Operation = batch.Operation, Reason = batch.Reason, BusinessOrderId = batch.BusinessOrderId, OperatorId = batch.OperatorId, }, line.AssetKind, line.AssetId, amountBefore, line.Amount, amountAfter, batch.CompensatesTransactionId, sequence, occurredTime); + return new OnlineLedgerEntry("led-" + Guid.NewGuid().ToString("N"), batch.TransactionId, new OnlineLedgerHeader { PlayerId = batch.PlayerId, HomeServerId = batch.HomeServerId, InitiatingServerId = batch.InitiatingServerId, Source = batch.Source, Operation = batch.Operation, Reason = batch.Reason, BusinessOrderId = batch.BusinessOrderId, OperatorId = batch.OperatorId, }, line.AssetKind, line.AssetId, amountBefore, line.Amount, amountAfter, batch.CompensatesTransactionId, sequence, occurredTime); } /// 获取玩家分片锁(不存在则注册)。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 分片锁对象。 - private object GetPlayerLock(long tenantId, long appId, long playerId) + private object GetPlayerLock(long playerId) { - var playerKey = BuildPlayerKey(tenantId, appId, playerId); + var playerKey = OnlineRowKey.LedgerSequence(playerId); lock (_registryLock) { if (!_playerLocks.TryGetValue(playerKey, out var playerLock)) @@ -472,35 +447,4 @@ private object GetPlayerLock(long tenantId, long appId, long playerId) } } - /// 构造玩家键(tenant:app:player)。 - /// 租户标识。 - /// App 标识。 - /// 玩家标识。 - /// 玩家键。 - private static string BuildPlayerKey(long tenantId, long appId, long playerId) - { - return tenantId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + appId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + playerId.ToString(System.Globalization.CultureInfo.InvariantCulture); - } - - /// 构造玩家前缀键(tenant:app:player:)。 - /// 租户标识。 - /// App 标识。 - /// 玩家标识。 - /// 前缀键。 - private static string BuildPlayerPrefix(long tenantId, long appId, long playerId) - { - return BuildPlayerKey(tenantId, appId, playerId) + ":"; - } - - /// 构造资产键(tenant:app:player:类别:资产标识)。 - /// 租户标识。 - /// App 标识。 - /// 玩家标识。 - /// 资产类别。 - /// 资产标识。 - /// 资产键。 - private static string BuildAssetKey(long tenantId, long appId, long playerId, OnlineAssetKind assetKind, string assetId) - { - return BuildPlayerPrefix(tenantId, appId, playerId) + (assetKind == OnlineAssetKind.Currency ? "c" : "i") + ":" + assetId; - } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Assets/InMemoryOnlineAssetTransactionStore.cs b/Capability/GameFrameX.Capability.Online.Assets/InMemoryOnlineAssetTransactionStore.cs index 215d67d7e..d511bc56f 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/InMemoryOnlineAssetTransactionStore.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/InMemoryOnlineAssetTransactionStore.cs @@ -135,8 +135,6 @@ private static OnlineAssetTransaction Clone(OnlineAssetTransaction source) TransactionId = source.TransactionId, IdempotencyKey = source.IdempotencyKey, RequestDigest = source.RequestDigest, - TenantId = source.TenantId, - AppId = source.AppId, PlayerId = source.PlayerId, HomeServerId = source.HomeServerId, InitiatingServerId = source.InitiatingServerId, diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetAlertRecord.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetAlertRecord.cs index 0492be15e..200d26bac 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetAlertRecord.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetAlertRecord.cs @@ -50,7 +50,7 @@ public sealed class OnlineAssetAlertRecord public string TransactionId { get; set; } /// - /// 获取或设置作用域键(可追溯到租户/App/区服/玩家)。 + /// 获取或设置作用域键(可追溯到区服/玩家)。 /// public string ScopeKey { get; set; } diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetChangeBatch.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetChangeBatch.cs index 54cf21963..35a820c08 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetChangeBatch.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetChangeBatch.cs @@ -45,16 +45,6 @@ public sealed class OnlineAssetChangeBatch /// public string TransactionId { get; } - /// - /// 获取租户标识。 - /// - public long TenantId { get; } - - /// - /// 获取 App 标识。 - /// - public long AppId { get; } - /// /// 获取玩家标识。 /// @@ -115,8 +105,6 @@ public sealed class OnlineAssetChangeBatch internal OnlineAssetChangeBatch(string transactionId, OnlineLedgerHeader header, IReadOnlyList lines, string compensatesTransactionId) { TransactionId = transactionId; - TenantId = header.TenantId; - AppId = header.AppId; PlayerId = header.PlayerId; HomeServerId = header.HomeServerId; InitiatingServerId = header.InitiatingServerId; diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetEvents.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetEvents.cs index 9755345ed..4fa6203d6 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetEvents.cs @@ -59,8 +59,6 @@ public static class OnlineAssetEvents /// /// 构造资产变更事件(按操作类型名选择事件类型;混合批次以操作类型为准,逐资产前后值在载荷内)。 /// - /// 租户标识。 - /// App 标识。 /// 发起区服标识。 /// 玩家标识。 /// 交易标识。 @@ -69,7 +67,7 @@ public static class OnlineAssetEvents /// 业务单号(可空;载荷落空字符串)。 /// 逐资产变更行(类别名 / 标识 / 带符号数额 / 变更前后值)。 /// 事件信封实例。 - public static OnlineEvent Create(long tenantId, long appId, long serverId, long playerId, string transactionId, string operation, string changeSource, string businessOrderId, IReadOnlyList<(string AssetKind, string AssetId, long Delta, long AmountBefore, long AmountAfter)> lines) + public static OnlineEvent Create(long serverId, long playerId, string transactionId, string operation, string changeSource, string businessOrderId, IReadOnlyList<(string AssetKind, string AssetId, long Delta, long AmountBefore, long AmountAfter)> lines) { string eventType; switch (operation) @@ -109,8 +107,6 @@ public static OnlineEvent Create(long tenantId, long appId, long serverId, long EventType = eventType, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = playerId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetQueryService.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetQueryService.cs index a7e8ee2c1..0f8278347 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetQueryService.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetQueryService.cs @@ -82,10 +82,10 @@ public async Task> GetWalletAsync(OnlineScope return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "货币代码不得为空"); } - var account = await _assetStore.FindWalletAsync(scope.TenantId, scope.AppId, scope.PlayerId, currencyId, cancellationToken); + var account = await _assetStore.FindWalletAsync(scope.PlayerId, currencyId, cancellationToken); if (account == null) { - account = new OnlineWalletAccount { TenantId = scope.TenantId, AppId = scope.AppId, PlayerId = scope.PlayerId, CurrencyId = currencyId, Balance = 0, Version = 0, UpdatedTime = 0, }; + account = new OnlineWalletAccount { PlayerId = scope.PlayerId, CurrencyId = currencyId, Balance = 0, Version = 0, UpdatedTime = 0, }; } return OnlineResult.Ok(account); @@ -105,7 +105,7 @@ public async Task>> ListWalletsA return failure; } - var accounts = await _assetStore.ListWalletAccountsAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var accounts = await _assetStore.ListWalletAccountsAsync(scope.PlayerId, cancellationToken); return OnlineResult>.Ok(accounts); } @@ -123,7 +123,7 @@ public async Task>> ListInvento return failure; } - var stacks = await _assetStore.ListInventoryStacksAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var stacks = await _assetStore.ListInventoryStacksAsync(scope.PlayerId, cancellationToken); return OnlineResult>.Ok(stacks); } @@ -154,13 +154,13 @@ public async Task> GetLedgerPageAsync(OnlineScope return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "游标格式非法(不透明令牌只回传不构造)"); } - var entries = await _assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = scope.TenantId, AppId = scope.AppId, PlayerId = scope.PlayerId, AfterSequenceNumber = afterSequenceNumber, MaxCount = maxCount, }, cancellationToken); + var entries = await _assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = scope.PlayerId, AfterSequenceNumber = afterSequenceNumber, MaxCount = maxCount, }, cancellationToken); if (entries.Count < maxCount) { return OnlineResult.Ok(new OnlineLedgerPage(entries, new OnlinePageCursor(string.Empty, false))); } - var nextPage = await _assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = scope.TenantId, AppId = scope.AppId, PlayerId = scope.PlayerId, AfterSequenceNumber = entries[entries.Count - 1].SequenceNumber, MaxCount = 1, }, cancellationToken); + var nextPage = await _assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = scope.PlayerId, AfterSequenceNumber = entries[entries.Count - 1].SequenceNumber, MaxCount = 1, }, cancellationToken); var hasMore = nextPage.Count > 0; return OnlineResult.Ok(new OnlineLedgerPage(entries, new OnlinePageCursor(hasMore ? entries[entries.Count - 1].SequenceNumber.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty, hasMore))); } @@ -186,7 +186,7 @@ public async Task> GetTransactionDeta } var transaction = await _transactionStore.FindAsync(transactionId, cancellationToken); - if (transaction == null || transaction.TenantId != scope.TenantId || transaction.AppId != scope.AppId || transaction.PlayerId != scope.PlayerId) + if (transaction == null || transaction.PlayerId != scope.PlayerId) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "交易不存在"); } diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetReconciliationService.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetReconciliationService.cs index a44875820..baeca97e8 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetReconciliationService.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetReconciliationService.cs @@ -76,24 +76,22 @@ public async Task ReconcilePlayerAsync(OnlineSc throw new ArgumentException(LocalizationService.GetString(Localization.Keys.Online.Assets.ReconciliationRequiresPlayerScope), nameof(scope)); } - var differences = await CollectDifferencesAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var differences = await CollectDifferencesAsync(scope.PlayerId, cancellationToken); return new OnlineAssetReconciliationReport(1, differences); } /// - /// 对 (租户, App) 下全部有资产活动的玩家对账(全量巡检入口)。 + /// 对全部有资产活动的玩家对账(全量巡检入口)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 对账报告。 - public async Task ReconcileAllAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public async Task ReconcileAllAsync(CancellationToken cancellationToken = default) { - var playerIds = await _assetStore.ListPlayerIdsAsync(tenantId, appId, cancellationToken); + var playerIds = await _assetStore.ListPlayerIdsAsync(cancellationToken); var differences = new List(); foreach (var playerId in playerIds) { - var playerDifferences = await CollectDifferencesAsync(tenantId, appId, playerId, cancellationToken); + var playerDifferences = await CollectDifferencesAsync(playerId, cancellationToken); differences.AddRange(playerDifferences); } @@ -103,17 +101,15 @@ public async Task ReconcileAllAsync(long tenant /// /// 收集单玩家差异(账本累加 vs 快照,双向并集比对)。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 差异列表。 - private async Task> CollectDifferencesAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken) + private async Task> CollectDifferencesAsync(long playerId, CancellationToken cancellationToken) { var differences = new List(); - var ledgerSums = await _assetStore.SumLedgerDeltasByAssetAsync(tenantId, appId, playerId, cancellationToken); - var wallets = await _assetStore.ListWalletAccountsAsync(tenantId, appId, playerId, cancellationToken); - var stacks = await _assetStore.ListInventoryStacksAsync(tenantId, appId, playerId, cancellationToken); + var ledgerSums = await _assetStore.SumLedgerDeltasByAssetAsync(playerId, cancellationToken); + var wallets = await _assetStore.ListWalletAccountsAsync(playerId, cancellationToken); + var stacks = await _assetStore.ListInventoryStacksAsync(playerId, cancellationToken); var snapshotByAsset = new Dictionary(StringComparer.Ordinal); foreach (var wallet in wallets) diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetTransaction.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetTransaction.cs index 4bf8a0e3f..0e1940b42 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetTransaction.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineAssetTransaction.cs @@ -60,15 +60,6 @@ public sealed class OnlineAssetTransaction /// public string CompensatesTransactionId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置玩家标识。 diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineGrantService.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineGrantService.cs index 05f74e8f2..8b9cd5d5a 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineGrantService.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineGrantService.cs @@ -120,8 +120,6 @@ public async Task> ExecuteAsync(OnlineGrantReque TransactionId = "tx-" + Guid.NewGuid().ToString("N"), IdempotencyKey = request.IdempotencyKey, RequestDigest = string.Empty, - TenantId = scope.TenantId, - AppId = scope.AppId, PlayerId = scope.PlayerId, HomeServerId = homeServerId, InitiatingServerId = scope.ServerId, @@ -215,10 +213,10 @@ private async Task> SettleSucceededAsync(OnlineA transaction.AppliedLedgerEntryIds = entries.Select(entry => entry.EntryId).ToList(); await _transactionStore.SaveAsync(transaction, cancellationToken); - var scope = new OnlineScope(transaction.TenantId, transaction.AppId, transaction.InitiatingServerId, transaction.PlayerId); + var scope = new OnlineScope(transaction.InitiatingServerId, transaction.PlayerId); await _idempotencyService.CompleteAsync(scope, transaction.IdempotencyKey, EncodeReplayToken(transaction.TransactionId, OnlineAssetTransactionState.Succeeded), true, cancellationToken); - var changeEvent = OnlineAssetEvents.Create(transaction.TenantId, transaction.AppId, transaction.InitiatingServerId, transaction.PlayerId, transaction.TransactionId, transaction.Operation.ToString(), transaction.Source.ToString(), transaction.BusinessOrderId, entries.Select(entry => (AssetKind: entry.AssetKind.ToString(), AssetId: entry.AssetId, Delta: entry.Delta, AmountBefore: entry.AmountBefore, AmountAfter: entry.AmountAfter)).ToList()); + var changeEvent = OnlineAssetEvents.Create(transaction.InitiatingServerId, transaction.PlayerId, transaction.TransactionId, transaction.Operation.ToString(), transaction.Source.ToString(), transaction.BusinessOrderId, entries.Select(entry => (AssetKind: entry.AssetKind.ToString(), AssetId: entry.AssetId, Delta: entry.Delta, AmountBefore: entry.AmountBefore, AmountAfter: entry.AmountAfter)).ToList()); await _eventPublisher.PublishAsync(changeEvent, cancellationToken); return OnlineResult.Ok(new OnlineGrantResult { TransactionId = transaction.TransactionId, State = transaction.State, IsReplay = false, Entries = entries, }); @@ -236,13 +234,13 @@ private async Task> SettleSucceededAsync(OnlineA private async Task> SettleInterruptedAsync(OnlineAssetTransaction transaction, CancellationToken cancellationToken) { var appliedEntries = await _assetStore.FindLedgerEntriesByTransactionIdAsync(transaction.TransactionId, cancellationToken); - var scope = new OnlineScope(transaction.TenantId, transaction.AppId, transaction.InitiatingServerId, transaction.PlayerId); + var scope = new OnlineScope(transaction.InitiatingServerId, transaction.PlayerId); - // 归属校验:仅统计 Tenant/App/Player 与交易主体一致的条目;异主体条目属数据完整性异常,告警留痕。 + // 归属校验:仅统计 Player 与交易主体一致的条目;异主体条目属数据完整性异常,告警留痕。 var ownedEntries = new List(); foreach (var entry in appliedEntries) { - if (entry.TenantId == transaction.TenantId && entry.AppId == transaction.AppId && entry.PlayerId == transaction.PlayerId) + if (entry.PlayerId == transaction.PlayerId) { ownedEntries.Add(entry); continue; @@ -300,7 +298,7 @@ private async Task CompensateAsync(OnlineAssetTransaction transaction, Can transaction.State = OnlineAssetTransactionState.Compensated; transaction.SettledTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await _transactionStore.SaveAsync(transaction, cancellationToken).ConfigureAwait(false); - var existingScope = new OnlineScope(transaction.TenantId, transaction.AppId, transaction.InitiatingServerId, transaction.PlayerId); + var existingScope = new OnlineScope(transaction.InitiatingServerId, transaction.PlayerId); await FailIdempotencyAsync(existingScope, transaction.IdempotencyKey, cancellationToken).ConfigureAwait(false); return true; } @@ -326,8 +324,6 @@ private async Task CompensateAsync(OnlineAssetTransaction transaction, Can TransactionId = "tx-" + Guid.NewGuid().ToString("N"), IdempotencyKey = "compensate-" + transaction.TransactionId, CompensatesTransactionId = transaction.TransactionId, - TenantId = transaction.TenantId, - AppId = transaction.AppId, PlayerId = transaction.PlayerId, HomeServerId = transaction.HomeServerId, InitiatingServerId = transaction.InitiatingServerId, @@ -346,7 +342,7 @@ private async Task CompensateAsync(OnlineAssetTransaction transaction, Can var apply = await _assetStore.ApplyAsync(batch, cancellationToken); if (!apply.Success) { - await AlertAsync(OnlineAssetAlertKind.CompensationFailed, transaction.TransactionId, new OnlineScope(transaction.TenantId, transaction.AppId, transaction.InitiatingServerId, transaction.PlayerId).ToScopeKey(true), string.Empty, "补偿批次被拒:" + apply.Message, cancellationToken); + await AlertAsync(OnlineAssetAlertKind.CompensationFailed, transaction.TransactionId, new OnlineScope(transaction.InitiatingServerId, transaction.PlayerId).ToScopeKey(true), string.Empty, "补偿批次被拒:" + apply.Message, cancellationToken); return false; } @@ -359,7 +355,7 @@ private async Task CompensateAsync(OnlineAssetTransaction transaction, Can transaction.SettledTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await _transactionStore.SaveAsync(transaction, cancellationToken); - var scope = new OnlineScope(transaction.TenantId, transaction.AppId, transaction.InitiatingServerId, transaction.PlayerId); + var scope = new OnlineScope(transaction.InitiatingServerId, transaction.PlayerId); await FailIdempotencyAsync(scope, transaction.IdempotencyKey, cancellationToken); await AlertAsync(OnlineAssetAlertKind.CompensatedAfterApplyFailure, transaction.TransactionId, scope.ToScopeKey(true), string.Empty, "已追加反转条目,净效应 0", cancellationToken); return true; @@ -469,7 +465,7 @@ private static OnlineResult ValidateChangeLines(IReadOnlyList private static string BuildCanonicalRequestText(OnlineGrantRequest request) { var builder = new StringBuilder(); - builder.Append("v1|").Append(request.Scope.TenantId).Append(':').Append(request.Scope.AppId).Append(':').Append(request.Scope.PlayerId); + builder.Append("v1|").Append(request.Scope.PlayerId); builder.Append('|').Append((int)request.Operation).Append('|').Append((int)request.Source); builder.Append('|').Append(request.BusinessOrderId).Append('|').Append(request.Reason); var orderedLines = request.Changes.OrderBy(line => line.AssetKind).ThenBy(line => line.AssetId, StringComparer.Ordinal); diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineInventoryStack.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineInventoryStack.cs index 01a61f839..b8ca6ca5e 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineInventoryStack.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineInventoryStack.cs @@ -33,21 +33,13 @@ namespace GameFrameX.Capability.Online.Assets; /// 玩家道具库存堆栈快照(Inventory = 玩家道具和数量;数量可由账本重算校验)。 /// /// 维护约束:数量快照只经统一入口在玩家分片事务内与账本条目原子同步; -/// 键 = (TenantId, AppId, PlayerId, ItemId),区服不参与隔离; +/// 键 = (PlayerId, ItemId),区服不参与隔离; /// 数量下限 0;堆叠上限等业务约束归调用方前置校验,本层只守护一致性红线。 /// /// public sealed class OnlineInventoryStack { /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置玩家标识。 diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerEntry.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerEntry.cs index 85221a1d7..13ff2e89c 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerEntry.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerEntry.cs @@ -38,7 +38,7 @@ namespace GameFrameX.Capability.Online.Assets; /// 维护约束(资产红线):本类型一经落账即为事实,任何代码路径不得修改或删除历史条目; /// 错误发放只能通过追加带符号反转条目(来源 , /// 指向原交易)纠正;每条必须携带完整追溯字段—— -/// 作用域(Player/App/Server 双侧)、来源、原因、业务单号、操作者、前后值与所属交易 +/// 作用域(Player/Server 双侧)、来源、原因、业务单号、操作者、前后值与所属交易 /// (反查依据); + == /// 由构造函数强制校验(checked 防溢出回绕,违反抛 ArgumentException;存量脏数据读取即暴露); 为玩家维度单调递增账本序 /// (对账与游标分页的稳定排序键)。 @@ -56,16 +56,6 @@ public sealed class OnlineLedgerEntry /// public string TransactionId { get; } - /// - /// 获取租户标识。 - /// - public long TenantId { get; } - - /// - /// 获取 App 标识。 - /// - public long AppId { get; } - /// /// 获取玩家标识。 /// @@ -179,8 +169,6 @@ public OnlineLedgerEntry(string entryId, string transactionId, OnlineLedgerHeade EntryId = entryId; TransactionId = transactionId; - TenantId = header.TenantId; - AppId = header.AppId; PlayerId = header.PlayerId; HomeServerId = header.HomeServerId; InitiatingServerId = header.InitiatingServerId; diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerHeader.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerHeader.cs index 001086e05..63b7adacb 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerHeader.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerHeader.cs @@ -31,25 +31,13 @@ namespace GameFrameX.Capability.Online.Assets; /// /// 账本头载荷( 与 共享的追溯头字段: -/// 作用域(租户/App/玩家/归属服/发起服)+ 来源/操作/原因/业务单号/操作者——全字段追溯的公共半边)。 +/// 作用域(玩家/归属服/发起服)+ 来源/操作/原因/业务单号/操作者——全字段追溯的公共半边)。 /// /// 维护约束:头字段一经落账即为事实;新增追溯维度只改本载荷,不再加长实体构造器。 /// /// public sealed class OnlineLedgerHeader { - /// - /// 获取或设置租户标识。 - /// - /// Gets or sets the tenant id. - public long TenantId { get; init; } - - /// - /// 获取或设置 App 标识。 - /// - /// Gets or sets the app id. - public long AppId { get; init; } - /// /// 获取或设置玩家标识。 /// @@ -107,8 +95,6 @@ public static OnlineLedgerHeader FromTransaction(OnlineAssetTransaction transact { return new OnlineLedgerHeader { - TenantId = transaction.TenantId, - AppId = transaction.AppId, PlayerId = transaction.PlayerId, HomeServerId = transaction.HomeServerId, InitiatingServerId = transaction.InitiatingServerId, diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerPageQuery.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerPageQuery.cs index 4e247ac81..8f3296d7c 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerPageQuery.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineLedgerPageQuery.cs @@ -35,18 +35,6 @@ namespace GameFrameX.Capability.Online.Assets; /// public sealed class OnlineLedgerPageQuery { - /// - /// 获取或设置租户标识。 - /// - /// Gets or sets the tenant id. - public long TenantId { get; init; } - - /// - /// 获取或设置 App 标识。 - /// - /// Gets or sets the app id. - public long AppId { get; init; } - /// /// 获取或设置玩家标识。 /// diff --git a/Capability/GameFrameX.Capability.Online.Assets/OnlineWalletAccount.cs b/Capability/GameFrameX.Capability.Online.Assets/OnlineWalletAccount.cs index fd13082c1..91a0bc7c4 100644 --- a/Capability/GameFrameX.Capability.Online.Assets/OnlineWalletAccount.cs +++ b/Capability/GameFrameX.Capability.Online.Assets/OnlineWalletAccount.cs @@ -33,22 +33,13 @@ namespace GameFrameX.Capability.Online.Assets; /// 玩家货币账户快照(Wallet = 货币账户和余额快照;余额可由账本重算校验)。 /// /// 维护约束:余额快照只经统一入口在玩家分片事务内与账本条目原子同步(唯一写入口); -/// 键 = (TenantId, AppId, PlayerId, CurrencyId),区服不参与隔离(换服资产随身); +/// 键 = (PlayerId, CurrencyId),区服不参与隔离(换服资产随身); /// 余额下限 0; 为快照乐观锁版本,每次随账本追加递增。 /// 对账以账本累加为事实源,快照漂移即差异告警。 /// /// public sealed class OnlineWalletAccount { - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置玩家标识。 diff --git a/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLeaderboardHandlers.cs b/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLeaderboardHandlers.cs index 0c15b3f6c..c4eea3308 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLeaderboardHandlers.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLeaderboardHandlers.cs @@ -40,7 +40,7 @@ namespace GameFrameX.Capability.Online.Competition.AdminApi; /// /// 排行榜域 admin 命令(query_leaderboard——只读榜单查询:单元信息 + Top 条目 + 可选玩家附近窗口)。 /// -/// 维护约束:只读幂等包裹 false(无状态变更,与 query_match_settlement 同族);跨 App / 跨租户与 +/// 维护约束:只读幂等包裹 false(无状态变更,与 query_match_settlement 同族);作用域校验失败与 /// 榜单不存在同构 ResourceNotFound(排行榜服务反预言红线);玩家附近窗口为尽力投影(玩家未上榜时省略)。 /// /// diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/IOnlineLeaderboardStore.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/IOnlineLeaderboardStore.cs index b3419f779..aca5e7d49 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/IOnlineLeaderboardStore.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/IOnlineLeaderboardStore.cs @@ -37,7 +37,7 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// 排行榜存储契约(榜单定义 + 条目;InMemory 为单进程默认实现,生产持久化归 Server 仓运行时装配)。 /// /// 维护约束(红线): -/// (1) 作用域隔离——所有查询以 (TenantId, AppId) 为前置条件,跨作用域访问与不存在同构(null,反预言); +/// (1) 榜单为全局域投影目标——字典键即 LeaderboardId(无区服隔离位,同键即同榜); /// (2) 是唯一条目写入入口,**累计策略裁决与条目落档必须在同一临界区**, /// 并发投递不得交错撕裂(形态对齐票据 / 通知存储的临界区约定); /// (3) 出入参一律防御性拷贝——返回对象与内部状态无别名,调用方改写不影响存储。 @@ -46,33 +46,29 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; public interface IOnlineLeaderboardStore { /// - /// 创建榜单(同作用域同名榜单已存在时拒绝,返回 null,不覆盖)。 + /// 创建榜单(同名榜单已存在时拒绝,返回 null,不覆盖)。 /// - /// 榜单定义(作用域取其 TenantId / AppId)。 + /// 榜单定义。 /// 取消令牌。 /// 创建后的榜单副本;已存在返回 null。 Task CreateAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default); /// - /// 按作用域查找榜单定义。 + /// 按榜单标识查找榜单定义。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识。 /// 取消令牌。 - /// 榜单副本;不存在或跨作用域返回 null。 - Task FindAsync(long tenantId, long appId, string leaderboardId, CancellationToken cancellationToken = default); + /// 榜单副本;不存在返回 null。 + Task FindAsync(string leaderboardId, CancellationToken cancellationToken = default); /// /// 查找单玩家条目。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识。 /// 玩家标识。 /// 取消令牌。 /// 条目副本;未上榜或榜单不存在返回 null。 - Task FindEntryAsync(long tenantId, long appId, string leaderboardId, long playerId, CancellationToken cancellationToken = default); + Task FindEntryAsync(string leaderboardId, long playerId, CancellationToken cancellationToken = default); /// /// 应用一笔分数提交(原子:累计策略裁决 + 条目落档在同一临界区)。 diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/InMemoryOnlineLeaderboardStore.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/InMemoryOnlineLeaderboardStore.cs index e7a17cd3c..787dd0166 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/InMemoryOnlineLeaderboardStore.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/InMemoryOnlineLeaderboardStore.cs @@ -29,7 +29,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Threading; using System.Threading.Tasks; using GameFrameX.Foundation.Localization.Core; @@ -49,7 +48,7 @@ public sealed class InMemoryOnlineLeaderboardStore : IOnlineLeaderboardStore /// 全局读写锁(榜单与条目共用,保证快照一致性)。 private readonly object _syncRoot = new(); - /// 榜单定义表:键 = (TenantId, AppId, LeaderboardId)。 + /// 榜单定义表:键 = LeaderboardId(全局域投影,无区服隔离位)。 private readonly Dictionary _boards = new(); /// 条目表:键 = 榜单键 → (PlayerId → 条目)。 @@ -63,12 +62,12 @@ public InMemoryOnlineLeaderboardStore() } /// - /// 在全局锁内创建榜单:同作用域同标识已存在时拒绝返回 null,否则落档定义副本并初始化空条目表。 + /// 在全局锁内创建榜单:同标识已存在时拒绝返回 null,否则落档定义副本并初始化空条目表。 /// /// - /// Creates the leaderboard under the global lock: refuses with null when the same id already exists in the scope, otherwise stores a defensive copy of the definition and initializes an empty entry table. + /// Creates the leaderboard under the global lock: refuses with null when the same id already exists, otherwise stores a defensive copy of the definition and initializes an empty entry table. /// - /// 榜单定义(作用域取自其 TenantId 与 AppId)/ The leaderboard definition (scope taken from its TenantId and AppId) + /// 榜单定义 / The leaderboard definition /// 取消令牌 / Cancellation token /// 创建后的榜单副本;已存在返回 null / A copy of the created leaderboard; null when it already exists /// 当 为 null 时抛出 / Thrown when is null @@ -81,7 +80,7 @@ public Task CreateAsync(OnlineLeaderboard leaderboard, Cancel lock (_syncRoot) { - var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + var key = BuildKey(leaderboard.LeaderboardId); if (_boards.ContainsKey(key)) { return Task.FromResult(null); @@ -94,21 +93,19 @@ public Task CreateAsync(OnlineLeaderboard leaderboard, Cancel } /// - /// 在全局锁内按作用域与榜单标识查找榜单定义,返回防御性副本。 + /// 在全局锁内按榜单标识查找榜单定义,返回防御性副本。 /// /// - /// Finds the leaderboard definition by scope and leaderboard id under the global lock, returning a defensive copy. + /// Finds the leaderboard definition by leaderboard id under the global lock, returning a defensive copy. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 榜单标识 / The leaderboard id /// 取消令牌 / Cancellation token - /// 榜单副本;不存在或跨作用域返回 null / A copy of the leaderboard; null when not found or cross-scope - public Task FindAsync(long tenantId, long appId, string leaderboardId, CancellationToken cancellationToken = default) + /// 榜单副本;不存在返回 null / A copy of the leaderboard; null when not found + public Task FindAsync(string leaderboardId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(TryFindBoard(tenantId, appId, leaderboardId, out var board) ? board.Copy() : null); + return Task.FromResult(TryFindBoard(leaderboardId, out var board) ? board.Copy() : null); } } @@ -118,17 +115,15 @@ public Task FindAsync(long tenantId, long appId, string leade /// /// Finds a single player's entry on the board under the global lock, returning a defensive copy. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 榜单标识 / The leaderboard id /// 玩家标识 / The player id /// 取消令牌 / Cancellation token /// 条目副本;未上榜或榜单不存在返回 null / A copy of the entry; null when the player is unranked or the board does not exist - public Task FindEntryAsync(long tenantId, long appId, string leaderboardId, long playerId, CancellationToken cancellationToken = default) + public Task FindEntryAsync(string leaderboardId, long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - if (!TryFindBoard(tenantId, appId, leaderboardId, out _) || !_entries.TryGetValue(BuildKey(tenantId, appId, leaderboardId), out var boardEntries) || !boardEntries.TryGetValue(playerId, out var entry)) + if (!TryFindBoard(leaderboardId, out _) || !_entries.TryGetValue(BuildKey(leaderboardId), out var boardEntries) || !boardEntries.TryGetValue(playerId, out var entry)) { return Task.FromResult(null); } @@ -167,7 +162,7 @@ public Task ApplySubmissionAsync(OnlineLeaderboard lock (_syncRoot) { - var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + var key = BuildKey(leaderboard.LeaderboardId); if (!_boards.ContainsKey(key) || !_entries.TryGetValue(key, out var boardEntries)) { // Localization: Online.Leaderboard.NotFoundOnWrite - 榜单不存在或已失效,写入前必须先经 FindAsync 解析 @@ -229,7 +224,7 @@ public Task> ListOrderedEntriesAsync(OnlineLeaderbo List copies; lock (_syncRoot) { - var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + var key = BuildKey(leaderboard.LeaderboardId); if (!_entries.TryGetValue(key, out var boardEntries)) { // Localization: Online.Leaderboard.NotFoundOnQuery - 榜单不存在或已失效,查询前必须先经 FindAsync 解析 @@ -273,7 +268,7 @@ public Task TryResetAsync(OnlineLeaderboard leaderboard, IReadOnlyList /// 在锁内解析榜单定义(调用方已持锁)。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识。 /// 解析到的榜单定义。 /// 存在返回 true。 - private bool TryFindBoard(long tenantId, long appId, string leaderboardId, out OnlineLeaderboard board) + private bool TryFindBoard(string leaderboardId, out OnlineLeaderboard board) { board = null; if (string.IsNullOrEmpty(leaderboardId)) @@ -348,7 +341,7 @@ private bool TryFindBoard(long tenantId, long appId, string leaderboardId, out O return false; } - if (!_boards.TryGetValue(BuildKey(tenantId, appId, leaderboardId), out var stored)) + if (!_boards.TryGetValue(BuildKey(leaderboardId), out var stored)) { return false; } @@ -397,14 +390,12 @@ private static bool TryResolveScore(OnlineLeaderboard leaderboard, OnlineLeaderb } /// - /// 构造存储键(作用域 + 榜单标识;跨作用域访问因键不同而自然隔离)。 + /// 构造存储键(榜单标识即键——全局域投影目标,同键即同榜)。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识。 /// 存储键。 - private static string BuildKey(long tenantId, long appId, string leaderboardId) + private static string BuildKey(string leaderboardId) { - return tenantId.ToString(CultureInfo.InvariantCulture) + ":" + appId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboardId; + return leaderboardId ?? string.Empty; } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboard.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboard.cs index 62bffdfba..93fe0723e 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboard.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboard.cs @@ -30,10 +30,9 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// -/// 排行榜榜单定义(第一版个人榜;作用域 = (TenantId, AppId),App 内跨区服聚合)。 +/// 排行榜榜单定义(第一版个人榜;全局域投影目标,无区服隔离位——同 LeaderboardId 即同榜)。 /// -/// 维护约束(红线):榜单归属租户与 App 双键隔离——跨 App / 跨租户读写一律查不到(ResourceNotFound 反预言, -/// 对齐存储与频道的既有先例,不泄露榜单存在性);ServerId 不参与榜单隔离, +/// 维护约束(红线):榜单为全局域数据——同键读写天然成立,无跨区服隔离维度; /// 队伍榜 / 公会榜 / 复杂跨服排名延后(超出首版范围)。排序方向与累计策略创建后固化,运行期不可变更; /// 赛季维度的生命周期(重置 / 快照)归赛季域,本类型不承载赛季字段。 /// @@ -41,20 +40,10 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; public sealed class OnlineLeaderboard { /// - /// 获取或设置榜单标识(App 内唯一,创建方提供)。 + /// 获取或设置榜单标识(全局唯一,创建方提供)。 /// public string LeaderboardId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置排序方向(创建后固化)。 /// @@ -84,8 +73,6 @@ public OnlineLeaderboard Copy() return new OnlineLeaderboard { LeaderboardId = LeaderboardId, - TenantId = TenantId, - AppId = AppId, SortOrder = SortOrder, ScoreUpdatePolicy = ScoreUpdatePolicy, MaxScorePerSubmission = MaxScorePerSubmission, diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardCreateRequest.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardCreateRequest.cs index 8934ef8ae..69b643a0c 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardCreateRequest.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardCreateRequest.cs @@ -32,14 +32,14 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// /// 排行榜创建请求(服务端运营 / 运行时装配入口;客户端无此入口)。 /// -/// 维护约束:作用域取鉴权上下文的 ,请求体不携带 TenantId / AppId(服务端不信任请求体作用域); -/// 同名榜单在 (TenantId, AppId) 内已存在时创建被拒绝(ParameterInvalid),不覆盖既有榜单。 +/// 维护约束:作用域取鉴权上下文的 ,请求体不携带作用域键位(服务端不信任请求体作用域); +/// 同名榜单已存在时创建被拒绝(ParameterInvalid),不覆盖既有榜单。 /// /// public sealed class OnlineLeaderboardCreateRequest { /// - /// 获取或设置榜单标识(App 内唯一,非空)。 + /// 获取或设置榜单标识(全局唯一,非空)。 /// public string LeaderboardId { get; set; } diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEvents.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEvents.cs index 797125442..286b8b092 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEvents.cs @@ -57,14 +57,12 @@ public static class OnlineLeaderboardEvents /// /// 构造榜单创建事件。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识(可空;载荷落空字符串)。 /// 排序方向名。 /// 累计策略名。 /// 创建时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, string leaderboardId, string sortOrder, string scoreUpdatePolicy, long createdTime) + public static OnlineEvent CreateLeaderboardCreated(string leaderboardId, string sortOrder, string scoreUpdatePolicy, long createdTime) { var payload = new LeaderboardCreatedPayload { @@ -86,8 +84,6 @@ public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, st EventType = LeaderboardCreated, OccurredTime = createdTime > 0 ? createdTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -100,8 +96,6 @@ public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, st /// /// 构造榜上分数更新事件。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识(可空;载荷落空字符串)。 /// 玩家标识。 /// 变更前分数。 @@ -109,7 +103,7 @@ public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, st /// 来源结算结果标识(追溯键,兼作 CorrelationId)。 /// 变更时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateScoreUpdated(long tenantId, long appId, string leaderboardId, long playerId, long oldScore, long newScore, string sourceMatchResultId, long updatedTime) + public static OnlineEvent CreateScoreUpdated(string leaderboardId, long playerId, long oldScore, long newScore, string sourceMatchResultId, long updatedTime) { var payload = new ScoreUpdatedPayload { @@ -137,8 +131,6 @@ public static OnlineEvent CreateScoreUpdated(long tenantId, long appId, string l EventType = ScoreUpdated, OccurredTime = updatedTime > 0 ? updatedTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = playerId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs index 241945c3f..3084bc100 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs @@ -31,13 +31,19 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// /// 排行榜投影选项( 的子对象; -/// 非空白才装配 Match.Settled 投影与激活期榜单预建, -/// 空白 / 缺省 = 不投影,不报错)。 +/// 默认投影到默认榜(C460:默认值服务黄金路径开箱即通—— +/// 零 JSON 配置起服即装配 Match.Settled 投影并在激活期预建默认榜);显式置空白 / null +/// 或经配置段覆盖为空白 = 关闭投影(不装配、不预建,不报错)。 /// public sealed class OnlineLeaderboardProjectionOptions { /// - /// 获取或设置 Match.Settled 事件的目标榜单标识(空白 = 不投影)。 + /// 默认投影目标榜单标识(Match.Settled 投影的默认榜;装配期由 Leaderboard 能力预建)。 /// - public string MatchSettledBoardId { get; set; } + public const string DefaultMatchSettledBoardId = "match-settled"; + + /// + /// 获取或设置 Match.Settled 事件的目标榜单标识(默认 = ;空白 = 不投影)。 + /// + public string MatchSettledBoardId { get; set; } = DefaultMatchSettledBoardId; } diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardRateLimiter.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardRateLimiter.cs index eaecf9a1b..49301c31c 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardRateLimiter.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardRateLimiter.cs @@ -35,7 +35,7 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// /// 排行榜提交限流器(防刷校验的高频半边:高频提交被拒、正常玩家不受影响)。 /// -/// 维护约束(天花板):滑动窗口计数,按 (TenantId, AppId, PlayerId) 分桶——阈值与窗口由 +/// 维护约束(天花板):滑动窗口计数,按 PlayerId 分桶——阈值与窗口由 /// 覆盖;只在幂等 Execute 分支计数(重放不烧配额)。 /// 形态对齐 OnlineMatchRateLimiter / OnlineChatRateLimiter(滑动窗口,不新增依赖); /// 桶在窗口过期后整桶重置,进程重启即清零——限流是速率保护不是配额,可接受;多实例共享存储归运行时装配。 @@ -46,7 +46,7 @@ public sealed class OnlineLeaderboardRateLimiter /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 窗口计数桶:键 = (TenantId, AppId, PlayerId)。 + /// 窗口计数桶:键 = PlayerId。 private readonly Dictionary _windows = new(); /// 上一次全量清扫时刻(UTC 毫秒)。 @@ -80,15 +80,13 @@ public OnlineLeaderboardRateLimiter(int maxSubmissions, int windowSeconds) /// /// Tries to acquire one submission slot for the player within the sliding window. /// - /// 租户 ID / The tenant id - /// 应用 ID / The app id /// 玩家 ID / The player id /// 当前 Unix 毫秒时间戳(0 表示取当前时间)/ The current Unix time in milliseconds (0 for now) /// 窗口未满获取成功返回 true;已满返回 false / true if acquired within the window; false when the window is full - public bool TryAcquire(long tenantId, long appId, long playerId, long nowUnixMilliseconds = 0) + public bool TryAcquire(long playerId, long nowUnixMilliseconds = 0) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var key = tenantId + ":" + appId + ":" + playerId; + var key = playerId.ToString(System.Globalization.CultureInfo.InvariantCulture); lock (_syncRoot) { diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardResultProjector.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardResultProjector.cs index 52dda6631..120dfb553 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardResultProjector.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardResultProjector.cs @@ -44,7 +44,7 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// /// 维护约束(红线): /// (1) **载荷零信任**——结算结果只从 (结算唯一落定点)按 -/// (TenantId, AppId, MatchId) 读取,且核对调用方传入的 MatchResultId 与存储值一致;本类型不接受 +/// MatchId 读取,且核对调用方传入的 MatchResultId 与存储值一致;本类型不接受 /// 任何调用方直接携带分数 / 结果载荷的入口(伪造标识 → ResourceNotFound,篡改载荷 → RiskControlRejected); /// (2) **写入幂等**——复用 ,键确定性派生 /// lb-{MatchResultId}-{LeaderboardId}-{PlayerId}(沿用「业务单号由结果标识派生」的既有约定), @@ -79,7 +79,7 @@ public OnlineLeaderboardResultProjector(IOnlineMatchResultStore matchResultStore /// /// 将一局已结算结果投影到目标榜单(幂等;逐玩家失败隔离)。 /// - /// 生效作用域(榜单与结果的 TenantId / AppId 以此为准)。 + /// 生效作用域。 /// 目标榜单标识。 /// 对局标识(据此从结算存储读取结果)。 /// 调用方持有的结果标识(与存储值核对,防伪造载荷)。 @@ -115,7 +115,7 @@ public async Task> ProjectAsync } var board = boardResult.Data; - var stored = await _matchResultStore.FindByMatchAsync(scope.TenantId, scope.AppId, matchId, cancellationToken).ConfigureAwait(false); + var stored = await _matchResultStore.FindByMatchAsync(matchId, cancellationToken).ConfigureAwait(false); if (stored == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "对局结果不存在或未结算"); @@ -163,7 +163,7 @@ public async Task> ProjectAsync /// 完成通知。 private async Task ProjectEntryAsync(OnlineLeaderboard board, OnlineMatchResult result, OnlineMatchResultEntry entry, long now, OnlineLeaderboardProjectionOutcome outcome, CancellationToken cancellationToken) { - var playerScope = new OnlineScope(result.TenantId, result.AppId, result.ServerId, entry.PlayerId); + var playerScope = new OnlineScope(result.ServerId, entry.PlayerId); var idempotencyKey = BuildIdempotencyKey(result.MatchResultId, board.LeaderboardId, entry.PlayerId); var decision = await _idempotencyService.BeginAsync(playerScope, idempotencyKey, BuildCanonicalRequestText(result.MatchResultId, board.LeaderboardId, entry.PlayerId, entry.Score), true, cancellationToken).ConfigureAwait(false); diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardService.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardService.cs index 87fd6d486..1d3bd44b8 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardService.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardService.cs @@ -45,7 +45,7 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// (1) **本服务没有任何接受「裸分数」的公开提交 API**——分数写入只经内部 /// (由可信写入链路 调用), /// 客户端无入口可刷分; -/// (2) 跨 App / 跨租户读写与「榜单不存在」同构返回 ResourceNotFound(反预言,不泄露榜单存在性); +/// (2) 作用域校验失败与「榜单不存在」同构返回 ResourceNotFound(反预言,不泄露榜单存在性); /// (3) Top N 读缓存 TTL + 写失效——任何成功写榜立即失效该榜缓存,缓存只影响读延迟不影响正确性。 /// /// @@ -84,9 +84,9 @@ public OnlineLeaderboardService(IOnlineLeaderboardStore store, OnlineLeaderboard } /// - /// 创建榜单(同作用域同名榜单已存在时拒绝;创建成功发布 Online.Leaderboard.Created 事件)。 + /// 创建榜单(同名榜单已存在时拒绝;创建成功发布 Online.Leaderboard.Created 事件)。 /// - /// 生效作用域(鉴权上下文产物;榜单归属取其 TenantId / AppId)。 + /// 生效作用域(鉴权上下文产物)。 /// 创建请求。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -126,8 +126,6 @@ public async Task> CreateAsync(OnlineScope scope var board = new OnlineLeaderboard { LeaderboardId = request.LeaderboardId, - TenantId = scope.TenantId, - AppId = scope.AppId, SortOrder = request.SortOrder, ScoreUpdatePolicy = request.ScoreUpdatePolicy, MaxScorePerSubmission = request.MaxScorePerSubmission, @@ -140,14 +138,14 @@ public async Task> CreateAsync(OnlineScope scope return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识已存在"); } - await PublishAsync(OnlineLeaderboardEvents.CreateLeaderboardCreated(created.TenantId, created.AppId, created.LeaderboardId, created.SortOrder.ToString(), created.ScoreUpdatePolicy.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineLeaderboardEvents.CreateLeaderboardCreated(created.LeaderboardId, created.SortOrder.ToString(), created.ScoreUpdatePolicy.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(created); } /// /// 查询 Top N(带 keyset 游标分页;游标由本服务编码,客户端不透明)。 /// - /// 生效作用域(跨 App / 跨租户与不存在同构拒绝)。 + /// 生效作用域。 /// Top N 查询载荷。 /// 取消令牌。 /// 本页条目与后继游标;失败返回对应错误码。 @@ -302,7 +300,7 @@ public async Task> GetAroundPlayerAsyn } /// - /// 内部:按作用域解析榜单定义(跨作用域与不存在同构返回失败 ResourceNotFound)。 + /// 内部:解析榜单定义(不存在同构返回失败 ResourceNotFound)。 /// /// 生效作用域。 /// 榜单标识。 @@ -320,7 +318,7 @@ internal async Task> ResolveBoardAsync(OnlineSco return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识不能为空"); } - var board = await _store.FindAsync(scope.TenantId, scope.AppId, leaderboardId, cancellationToken).ConfigureAwait(false); + var board = await _store.FindAsync(leaderboardId, cancellationToken).ConfigureAwait(false); if (board == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "排行榜不存在"); @@ -361,7 +359,7 @@ internal async Task ApplyTrustedScoreAsync(Online } var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - if (!_rateLimiter.TryAcquire(leaderboard.TenantId, leaderboard.AppId, submission.PlayerId, now)) + if (!_rateLimiter.TryAcquire(submission.PlayerId, now)) { return Failed(OnlineErrorCode.RateLimitExceeded, "提交过于频繁,已限流"); } @@ -374,7 +372,7 @@ internal async Task ApplyTrustedScoreAsync(Online } InvalidateCache(leaderboard); - await PublishAsync(OnlineLeaderboardEvents.CreateScoreUpdated(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId, submission.PlayerId, applied.OldScore, applied.Entry.Score, submission.SourceMatchResultId, applied.Entry.LastUpdateTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineLeaderboardEvents.CreateScoreUpdated(leaderboard.LeaderboardId, submission.PlayerId, applied.OldScore, applied.Entry.Score, submission.SourceMatchResultId, applied.Entry.LastUpdateTime), cancellationToken).ConfigureAwait(false); return new OnlineLeaderboardWriteOutcome { @@ -450,7 +448,7 @@ private static OnlineLeaderboardWriteOutcome Failed(OnlineErrorCode code, string private async Task> GetSnapshotAsync(OnlineLeaderboard leaderboard, long nowUnixMilliseconds, CancellationToken cancellationToken) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var cacheKey = leaderboard.TenantId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.AppId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.LeaderboardId; + var cacheKey = leaderboard.LeaderboardId ?? string.Empty; if (_options.CacheEnabled) { lock (_cacheSyncRoot) @@ -484,7 +482,7 @@ private async Task> GetSnapshotAsync(OnlineLeaderbo /// 榜单定义。 private void InvalidateCache(OnlineLeaderboard leaderboard) { - var cacheKey = leaderboard.TenantId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.AppId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.LeaderboardId; + var cacheKey = leaderboard.LeaderboardId ?? string.Empty; lock (_cacheSyncRoot) { _snapshotCache.Remove(cacheKey); diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineMatchSettledLeaderboardProjector.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineMatchSettledLeaderboardProjector.cs index 86031ada5..723f6d7f5 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineMatchSettledLeaderboardProjector.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineMatchSettledLeaderboardProjector.cs @@ -127,7 +127,7 @@ public async Task HandleEventAsync(OnlineEvent onlineEvent) try { // 榜单级作用域(PlayerId=0):投影器内部逐玩家以结算事实重建 scope。 - var scope = new OnlineScope(sourceEvent.TenantId, sourceEvent.AppId, sourceEvent.ServerId, 0); + var scope = new OnlineScope(sourceEvent.ServerId, 0); var projected = await _projector.ProjectAsync(scope, _leaderboardId, payload.MatchId, payload.MatchResultId).ConfigureAwait(false); if (!projected.IsSuccess) { @@ -163,7 +163,7 @@ public async Task RetryPendingAsync(CancellationToken cancellationToken) foreach (var entry in snapshot) { - var stored = await _matchResultStore.FindByMatchAsync(entry.TenantId, entry.AppId, entry.MatchId, cancellationToken).ConfigureAwait(false); + var stored = await _matchResultStore.FindByMatchAsync(entry.MatchId, cancellationToken).ConfigureAwait(false); if (stored == null) { // 结果已被清理:不可投影终态,移除。 @@ -171,7 +171,7 @@ public async Task RetryPendingAsync(CancellationToken cancellationToken) continue; } - var scope = new OnlineScope(entry.TenantId, entry.AppId, entry.ServerId, 0); + var scope = new OnlineScope(entry.ServerId, 0); var projected = await _projector.ProjectAsync(scope, _leaderboardId, entry.MatchId, entry.MatchResultId, 0, cancellationToken).ConfigureAwait(false); if (projected.IsSuccess) { @@ -232,7 +232,7 @@ private static MatchSettledPayload DeserializePayload(ReadOnlyMemory paylo /// /// 记录待重试条目(按 MatchResultId 去重;重复失败 Attempts 不衰减)。 /// - /// 来源事件(作用域三元组)。 + /// 来源事件(区服键)。 /// 已解析载荷。 private void RecordPending(OnlineEvent onlineEvent, MatchSettledPayload payload) { @@ -248,8 +248,6 @@ private void RecordPending(OnlineEvent onlineEvent, MatchSettledPayload payload) { MatchResultId = payload.MatchResultId, MatchId = payload.MatchId, - TenantId = onlineEvent.TenantId, - AppId = onlineEvent.AppId, ServerId = onlineEvent.ServerId, Attempts = 1, }; @@ -364,12 +362,6 @@ private sealed class PendingProjection /// 对局标识。 public string MatchId { get; set; } - /// 租户标识。 - public long TenantId { get; set; } - - /// App 标识。 - public long AppId { get; set; } - /// 区服标识。 public long ServerId { get; set; } diff --git a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs index 54587807c..e68b61919 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs @@ -52,9 +52,10 @@ namespace GameFrameX.Capability.Online.Competition; /// 锦标赛三个 store 以懒默认描述符注册(族 / 宿主覆盖恒胜出,模块不感知);赛季 / 锦标赛对发放服务 /// (,assets 域产物)的依赖经 manifest 可选声明 + GetOptionalService, /// 缺席(assets 能力被过滤)时不装配两者;对外产物(榜单 / 赛季 / 锦标赛服务与 LiveOps 注册表)注册回 -/// 共享面。 为唯一参数面(含榜单组件参数与 Match.Settled 投影配置, -/// 后者收编族级键 MatchBridgeLeaderboardId):投影榜 id 非空白且对局结果存储(online-match 可选产物) -/// 在场时装配 Match.Settled 排行榜投影(机制总线订阅 + 失败重投 tick); +/// 为唯一参数面(含榜单组件参数与 Match.Settled 投影配置, +/// 后者收编族级键 MatchBridgeLeaderboardId):投影榜 id 非空白(C460 起默认投影到默认榜 +/// ,显式空白可关闭)且对局结果存储 +/// (online-match 可选产物)在场时装配 Match.Settled 排行榜投影(机制总线订阅 + 失败重投 tick); /// ActivateAsync 在投影榜 id 非空白时经榜单服务预建目标榜(查询-创建,见方法注释)。 /// /// diff --git a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs index f548b97a9..e015d44fd 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs @@ -45,17 +45,19 @@ public sealed class OnlineCompetitionOptions : ICapabilityOptions public OnlineLeaderboardOptions Leaderboard { get; set; } = new OnlineLeaderboardOptions(); /// - /// 获取或设置 Match.Settled 写榜投影配置(MatchSettledBoardId 空白 = 不投影不预建)。 + /// 获取或设置 Match.Settled 写榜投影配置(默认投影到默认榜;显式置空白或配置段覆盖可关闭)。 /// public OnlineLeaderboardProjectionOptions LeaderboardProjection { get; set; } = new OnlineLeaderboardProjectionOptions(); /// - /// 校验排行榜组件选项:单次提交最大分数、限流最大提交次数、限流窗口秒数、缓存有效期秒数与最大分页大小均须为正数;投影配置不做校验(空白榜单标识表示不投影)。 + /// 校验排行榜组件与投影组合选项:单次提交最大分数、限流最大提交次数、限流窗口秒数、缓存有效期秒数与最大分页大小均须为正数; + /// 投影配置须为非 null 对象,目标榜单标识非空白(投影开启)时长度不得超过上限且不得包含空白字符(装配期 fail-fast,全部问题一次报全)。 /// /// /// Validates the leaderboard options: default maximum score per submission, rate-limit maximum submissions, rate-limit window - /// seconds, cache time-to-live seconds and maximum page size must all be positive. The projection settings are not validated because - /// a blank board id simply disables the projection. Failures are recorded on the validation collector. + /// seconds, cache time-to-live seconds and maximum page size must all be positive. The projection settings must be a non-null + /// object, and when the target board id is not blank (projection enabled) it must not exceed the maximum length or contain any + /// whitespace characters. All problems are collected and reported together on the validation collector. /// /// 选项校验结果收集器 / Options validation collector public void Validate(CapabilityOptionsValidation validation) @@ -65,5 +67,38 @@ public void Validate(CapabilityOptionsValidation validation) validation.RequirePositive("Leaderboard.RateLimitWindowSeconds", Leaderboard.RateLimitWindowSeconds); validation.RequirePositive("Leaderboard.CacheTtlSeconds", Leaderboard.CacheTtlSeconds); validation.RequirePositive("Leaderboard.MaxPageSize", Leaderboard.MaxPageSize); + + // 投影组合校验(C460):子对象缺席 = 代码 Configure 写坏,fail-fast;榜单 id 非空白(投影开启)时 + // 校验长度与空白字符——该 id 会拼进事件幂等键与读缓存键,超长 / 含空白属于配置错误而非运行期输入。 + if (LeaderboardProjection == null) + { + validation.AddError("LeaderboardProjection", "must be a non-null options object"); + return; + } + + var boardId = LeaderboardProjection.MatchSettledBoardId; + if (string.IsNullOrWhiteSpace(boardId)) + { + return; + } + + if (boardId.Length > MaxMatchSettledBoardIdLength) + { + validation.AddError("LeaderboardProjection.MatchSettledBoardId", "must be at most " + MaxMatchSettledBoardIdLength + " characters (actual: " + boardId.Length + ")"); + } + + for (var index = 0; index < boardId.Length; index++) + { + if (char.IsWhiteSpace(boardId[index])) + { + validation.AddError("LeaderboardProjection.MatchSettledBoardId", "must not contain whitespace characters"); + break; + } + } } + + /// + /// 投影目标榜单标识的最大长度( 非空白时的上限)。 + /// + public const int MaxMatchSettledBoardIdLength = 128; } diff --git a/Capability/GameFrameX.Capability.Online.Competition/Season/IOnlineSeasonStore.cs b/Capability/GameFrameX.Capability.Online.Competition/Season/IOnlineSeasonStore.cs index 90ed41682..c4f67c0d6 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Season/IOnlineSeasonStore.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Season/IOnlineSeasonStore.cs @@ -36,7 +36,7 @@ namespace GameFrameX.Capability.Online.Competition.Season; /// 赛季存储契约(赛季定义 + 历史快照;InMemory 为单进程默认实现,生产持久化归 Server 仓运行时装配)。 /// /// 维护约束(红线): -/// (1) 作用域隔离——所有查询以 (TenantId, AppId) 为前置条件,跨作用域访问与不存在同构(null,反预言); +/// (1) 赛季为全局域数据——字典键即 SeasonId(无区服隔离位,同键即同季); /// (2) 快照与赛季定义**分离存储**:快照一经写入即为冻结历史,赛季状态推进() /// 不得改写快照内容——「赛季结束不删除历史数据」的存储层保证; /// (3) 出入参一律防御性拷贝——返回对象与内部状态无别名,调用方改写不影响存储。 @@ -45,25 +45,23 @@ namespace GameFrameX.Capability.Online.Competition.Season; public interface IOnlineSeasonStore { /// - /// 创建赛季(同作用域同标识赛季已存在时拒绝,返回 null,不覆盖)。 + /// 创建赛季(同标识赛季已存在时拒绝,返回 null,不覆盖)。 /// - /// 赛季定义(作用域取其 TenantId / AppId)。 + /// 赛季定义。 /// 取消令牌。 /// 创建后的赛季副本;已存在返回 null。 Task CreateAsync(OnlineSeason season, CancellationToken cancellationToken = default); /// - /// 按作用域查找赛季定义。 + /// 按赛季标识查找赛季定义。 /// - /// 租户标识。 - /// App 标识。 /// 赛季标识。 /// 取消令牌。 - /// 赛季副本;不存在或跨作用域返回 null。 - Task FindAsync(long tenantId, long appId, string seasonId, CancellationToken cancellationToken = default); + /// 赛季副本;不存在返回 null。 + Task FindAsync(string seasonId, CancellationToken cancellationToken = default); /// - /// 保存赛季定义(状态推进落档;按作用域 + 赛季标识覆盖既有定义,赛季必须已存在)。 + /// 保存赛季定义(状态推进落档;按赛季标识覆盖既有定义,赛季必须已存在)。 /// /// 赛季定义(含推进后的状态与时间戳)。 /// 取消令牌。 @@ -71,7 +69,7 @@ public interface IOnlineSeasonStore Task SaveAsync(OnlineSeason season, CancellationToken cancellationToken = default); /// - /// 保存历史快照(按作用域 + 赛季标识覆盖;赛季结束流程在**清空榜单之前**调用——快照先行)。 + /// 保存历史快照(按赛季标识覆盖;赛季结束流程在**清空榜单之前**调用——快照先行)。 /// /// 历史快照。 /// 取消令牌。 @@ -79,12 +77,10 @@ public interface IOnlineSeasonStore Task SaveSnapshotAsync(OnlineSeasonSnapshot snapshot, CancellationToken cancellationToken = default); /// - /// 按作用域查找历史快照。 + /// 按赛季标识查找历史快照。 /// - /// 租户标识。 - /// App 标识。 /// 赛季标识。 /// 取消令牌。 - /// 快照副本;不存在或跨作用域返回 null。 - Task FindSnapshotAsync(long tenantId, long appId, string seasonId, CancellationToken cancellationToken = default); + /// 快照副本;不存在返回 null。 + Task FindSnapshotAsync(string seasonId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Season/InMemoryOnlineSeasonStore.cs b/Capability/GameFrameX.Capability.Online.Competition/Season/InMemoryOnlineSeasonStore.cs index 625cd6f1a..1f30c8197 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Season/InMemoryOnlineSeasonStore.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Season/InMemoryOnlineSeasonStore.cs @@ -29,7 +29,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Threading; using System.Threading.Tasks; using GameFrameX.Foundation.Localization.Core; @@ -48,10 +47,10 @@ public sealed class InMemoryOnlineSeasonStore : IOnlineSeasonStore /// 全局锁(赛季定义与快照共用,保证出入参一致性)。 private readonly object _syncRoot = new(); - /// 赛季定义表:键 = (TenantId, AppId, SeasonId)。 + /// 赛季定义表:键 = SeasonId(全局域数据,无区服隔离位)。 private readonly Dictionary _seasons = new(); - /// 历史快照表:键 = (TenantId, AppId, SeasonId)。 + /// 历史快照表:键 = SeasonId。 private readonly Dictionary _snapshots = new(); /// @@ -62,12 +61,12 @@ public InMemoryOnlineSeasonStore() } /// - /// 深拷贝赛季后写入内存赛季表:同作用域同标识已存在时拒绝并返回 null、不覆盖;否则落档并返回创建后的副本。 + /// 深拷贝赛季后写入内存赛季表:同标识已存在时拒绝并返回 null、不覆盖;否则落档并返回创建后的副本。 /// /// - /// Stores a defensive copy of the season into the in-memory season table: rejects with null and does not overwrite when the same season id already exists within the scope; otherwise archives it and returns a copy of the created season. + /// Stores a defensive copy of the season into the in-memory season table: rejects with null and does not overwrite when the same season id already exists; otherwise archives it and returns a copy of the created season. /// - /// 赛季定义(作用域取其 TenantId / AppId)/ The season definition (scope taken from its TenantId / AppId) + /// 赛季定义 / The season definition /// 取消令牌 / Cancellation token /// 创建后的赛季副本;已存在返回 null / A copy of the created season, or null when it already exists /// 当 为 null 时抛出 / Thrown when is null @@ -80,7 +79,7 @@ public Task CreateAsync(OnlineSeason season, CancellationToken can lock (_syncRoot) { - var key = BuildKey(season.TenantId, season.AppId, season.SeasonId); + var key = BuildKey(season.SeasonId); if (_seasons.ContainsKey(key)) { return Task.FromResult(null); @@ -92,29 +91,27 @@ public Task CreateAsync(OnlineSeason season, CancellationToken can } /// - /// 按作用域与赛季标识从内存赛季表读取赛季定义副本。 + /// 按赛季标识从内存赛季表读取赛季定义副本。 /// /// - /// Reads a copy of the season definition from the in-memory season table by scope and season id. + /// Reads a copy of the season definition from the in-memory season table by season id. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 赛季标识 / Season id /// 取消令牌 / Cancellation token - /// 赛季副本;不存在或跨作用域返回 null / A copy of the season, or null when not found or out of scope - public Task FindAsync(long tenantId, long appId, string seasonId, CancellationToken cancellationToken = default) + /// 赛季副本;不存在返回 null / A copy of the season, or null when not found + public Task FindAsync(string seasonId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(_seasons.TryGetValue(BuildKey(tenantId, appId, seasonId), out var stored) ? stored.Copy() : null); + return Task.FromResult(_seasons.TryGetValue(BuildKey(seasonId), out var stored) ? stored.Copy() : null); } } /// - /// 深拷贝后按作用域与赛季标识覆盖保存赛季定义:赛季必须已经 CreateAsync 建立,不存在时抛出 ,不会隐式创建。 + /// 深拷贝后按赛季标识覆盖保存赛季定义:赛季必须已经 CreateAsync 建立,不存在时抛出 ,不会隐式创建。 /// /// - /// Overwrites the season definition with a defensive copy, keyed by scope and season id: the season must already exist via CreateAsync; throws when it does not, and never creates it implicitly. + /// Overwrites the season definition with a defensive copy, keyed by season id: the season must already exist via CreateAsync; throws when it does not, and never creates it implicitly. /// /// 赛季定义(含推进后的状态与时间戳)/ The season definition (with the advanced state and timestamps) /// 取消令牌 / Cancellation token @@ -130,7 +127,7 @@ public Task SaveAsync(OnlineSeason season, CancellationToken cancellationToken = lock (_syncRoot) { - var key = BuildKey(season.TenantId, season.AppId, season.SeasonId); + var key = BuildKey(season.SeasonId); if (!_seasons.ContainsKey(key)) { // Localization: Online.Season.NotFoundOnSave - 赛季不存在,保存前必须先经 CreateAsync 建立 @@ -143,10 +140,10 @@ public Task SaveAsync(OnlineSeason season, CancellationToken cancellationToken = } /// - /// 深拷贝后按作用域与赛季标识覆盖写入内存快照表(快照一经落档不受后续赛季状态推进影响)。 + /// 深拷贝后按赛季标识覆盖写入内存快照表(快照一经落档不受后续赛季状态推进影响)。 /// /// - /// Overwrites the in-memory snapshot table with a defensive copy, keyed by scope and season id (an archived snapshot is never affected by later season state advances). + /// Overwrites the in-memory snapshot table with a defensive copy, keyed by season id (an archived snapshot is never affected by later season state advances). /// /// 历史快照 / The season snapshot /// 取消令牌 / Cancellation token @@ -161,39 +158,35 @@ public Task SaveSnapshotAsync(OnlineSeasonSnapshot snapshot, CancellationToken c lock (_syncRoot) { - _snapshots[BuildKey(snapshot.TenantId, snapshot.AppId, snapshot.SeasonId)] = snapshot.Copy(); + _snapshots[BuildKey(snapshot.SeasonId)] = snapshot.Copy(); return Task.CompletedTask; } } /// - /// 按作用域与赛季标识从内存快照表读取历史快照副本。 + /// 按赛季标识从内存快照表读取历史快照副本。 /// /// - /// Reads a copy of the season snapshot from the in-memory snapshot table by scope and season id. + /// Reads a copy of the season snapshot from the in-memory snapshot table by season id. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 赛季标识 / Season id /// 取消令牌 / Cancellation token - /// 快照副本;不存在或跨作用域返回 null / A copy of the snapshot, or null when not found or out of scope - public Task FindSnapshotAsync(long tenantId, long appId, string seasonId, CancellationToken cancellationToken = default) + /// 快照副本;不存在返回 null / A copy of the snapshot, or null when not found + public Task FindSnapshotAsync(string seasonId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(_snapshots.TryGetValue(BuildKey(tenantId, appId, seasonId), out var stored) ? stored.Copy() : null); + return Task.FromResult(_snapshots.TryGetValue(BuildKey(seasonId), out var stored) ? stored.Copy() : null); } } /// - /// 构造存储键(作用域 + 赛季标识;跨作用域访问因键不同而自然隔离)。 + /// 构造存储键(赛季标识即键——全局域数据,同键即同季)。 /// - /// 租户标识。 - /// App 标识。 /// 赛季标识。 /// 存储键。 - private static string BuildKey(long tenantId, long appId, string seasonId) + private static string BuildKey(string seasonId) { - return tenantId.ToString(CultureInfo.InvariantCulture) + ":" + appId.ToString(CultureInfo.InvariantCulture) + ":" + (seasonId ?? string.Empty); + return seasonId ?? string.Empty; } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeason.cs b/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeason.cs index 51637703e..4f82de3cc 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeason.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeason.cs @@ -35,8 +35,7 @@ namespace GameFrameX.Capability.Online.Competition.Season; /// 赛季定义(开始/结束时间、关联榜单、赛季奖励与结算状态)。 /// /// 维护约束(红线): -/// (1) 作用域 = (TenantId, AppId),与榜单同口径(App 内跨区服聚合)——跨 App / 跨租户读写一律查不到 -/// (ResourceNotFound 反预言,对齐既有先例); +/// (1) 赛季为全局域数据(与榜单同口径)——键即 SeasonId,无区服隔离位,同键即同季; /// (2) 赛季本身**不承载分数**:成绩只存在于榜单与快照中,赛季只描述周期与奖励口径; /// (3) 奖励规则创建后固化,运行期不可变更(配置变更与结算并发的冻结要求); /// (4) / 是**排期元数据**,由运行时装配的调度器到点驱动 @@ -46,20 +45,10 @@ namespace GameFrameX.Capability.Online.Competition.Season; public sealed class OnlineSeason { /// - /// 获取或设置赛季标识(App 内唯一,创建方提供)。 + /// 获取或设置赛季标识(全局唯一,创建方提供)。 /// public string SeasonId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置关联榜单标识(赛季成绩的累积榜单;结束时的快照即取自该榜)。 /// @@ -121,8 +110,6 @@ public OnlineSeason Copy() return new OnlineSeason { SeasonId = SeasonId, - TenantId = TenantId, - AppId = AppId, LeaderboardId = LeaderboardId, StartTime = StartTime, EndTime = EndTime, diff --git a/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonEvents.cs b/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonEvents.cs index 25d71cfe5..21795093a 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonEvents.cs @@ -65,8 +65,6 @@ public static class OnlineSeasonEvents /// 构造赛季创建事件。 /// /// 赛季标识。 - /// 租户标识。 - /// App 标识。 /// 关联榜单标识。 /// 排期开始时刻(UTC 毫秒)。 /// 排期结束时刻(UTC 毫秒)。 @@ -74,7 +72,7 @@ public static class OnlineSeasonEvents /// 创建后的状态名。 /// 创建时刻(UTC 毫秒;非正数取当前时钟)。 /// 事件信封实例。 - public static OnlineEvent CreateSeasonCreated(string seasonId, long tenantId, long appId, string leaderboardId, long startTime, long endTime, int rewardRuleCount, string state, long createdTime) + public static OnlineEvent CreateSeasonCreated(string seasonId, string leaderboardId, long startTime, long endTime, int rewardRuleCount, string state, long createdTime) { var payload = new SeasonCreatedPayload { @@ -100,8 +98,6 @@ public static OnlineEvent CreateSeasonCreated(string seasonId, long tenantId, lo EventType = SeasonCreated, OccurredTime = createdTime > 0 ? createdTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -115,13 +111,11 @@ public static OnlineEvent CreateSeasonCreated(string seasonId, long tenantId, lo /// 构造赛季开始事件。 /// /// 赛季标识。 - /// 租户标识。 - /// App 标识。 /// 关联榜单标识。 /// 排期开始时刻(UTC 毫秒)。 /// 排期结束时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateSeasonStarted(string seasonId, long tenantId, long appId, string leaderboardId, long startTime, long endTime) + public static OnlineEvent CreateSeasonStarted(string seasonId, string leaderboardId, long startTime, long endTime) { var payload = new SeasonStartedPayload { @@ -143,8 +137,6 @@ public static OnlineEvent CreateSeasonStarted(string seasonId, long tenantId, lo EventType = SeasonStarted, OccurredTime = startTime > 0 ? startTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -158,14 +150,12 @@ public static OnlineEvent CreateSeasonStarted(string seasonId, long tenantId, lo /// 构造赛季结束事件(快照先行已完成的落定点)。 /// /// 赛季标识。 - /// 租户标识。 - /// App 标识。 /// 关联榜单标识。 /// 结束时刻(UTC 毫秒;非正数取当前时钟)。 /// 落档快照的条目数。 /// 快照生成时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateSeasonEnded(string seasonId, long tenantId, long appId, string leaderboardId, long endedTime, int snapshotEntryCount, long snapshottedTime) + public static OnlineEvent CreateSeasonEnded(string seasonId, string leaderboardId, long endedTime, int snapshotEntryCount, long snapshottedTime) { var payload = new SeasonEndedPayload { @@ -187,8 +177,6 @@ public static OnlineEvent CreateSeasonEnded(string seasonId, long tenantId, long EventType = SeasonEnded, OccurredTime = endedTime > 0 ? endedTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -202,14 +190,12 @@ public static OnlineEvent CreateSeasonEnded(string seasonId, long tenantId, long /// 构造赛季结算事件(仅在全量发放成功、赛季推进到结算完成态时发布)。 /// /// 赛季标识。 - /// 租户标识。 - /// App 标识。 /// 结算完成时刻(UTC 毫秒;非正数取当前时钟)。 /// 本次首次发放成功玩家数。 /// 本次命中幂等回放玩家数。 /// 本次发放失败玩家数(正常路径恒为 0)。 /// 事件信封实例。 - public static OnlineEvent CreateSeasonSettled(string seasonId, long tenantId, long appId, long settledTime, int grantedCount, int replayCount, int failedCount) + public static OnlineEvent CreateSeasonSettled(string seasonId, long settledTime, int grantedCount, int replayCount, int failedCount) { var payload = new SeasonSettledPayload { @@ -231,8 +217,6 @@ public static OnlineEvent CreateSeasonSettled(string seasonId, long tenantId, lo EventType = SeasonSettled, OccurredTime = settledTime > 0 ? settledTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonService.cs b/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonService.cs index 09bd93f17..a9904f472 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonService.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonService.cs @@ -56,7 +56,7 @@ namespace GameFrameX.Capability.Online.Competition.Season; /// 需待保留期过期后重新占位方可补发(本服务不自行改写全局幂等策略); /// (4) **逐玩家失败隔离**——单玩家发放失败只计入回执明细,不阻塞其余玩家;仅当无失败玩家才把赛季推进到 /// 结算完成态(部分发奖不得标记完成); -/// (5) 跨 App / 跨租户读写与「赛季不存在」同构返回 ResourceNotFound(反预言,对齐既有先例)。 +/// (5) 作用域校验失败与「赛季不存在」同构返回 ResourceNotFound(反预言,对齐既有先例)。 /// /// /// 运行时边界:StartTime/EndTime 只是排期元数据,到点驱动 / @@ -71,7 +71,7 @@ public sealed class OnlineSeasonService private const int MaxResetAttempts = 3; /// - /// 赛季奖励发放使用的区服位(恒为 0):赛季与榜单同为 (TenantId, AppId) 作用域,**没有归属服**。 + /// 赛季奖励发放使用的区服位(恒为 0):赛季与榜单同为全局域数据,**没有归属服**。 /// 若改取调用方作用域的区服,同一赛季从不同区服触发结算会落到不同的幂等绑定键上,重试将不再回放首次结果 /// 而重复发奖——故必须用与调用方无关的稳定值。 /// @@ -105,9 +105,9 @@ public OnlineSeasonService(IOnlineSeasonStore seasonStore, OnlineLeaderboardServ } /// - /// 创建赛季(同作用域同名赛季已存在时拒绝;关联榜单必须已存在;奖励规则区间必须互不重叠)。 + /// 创建赛季(同名赛季已存在时拒绝;关联榜单必须已存在;奖励规则区间必须互不重叠)。 /// - /// 生效作用域(赛季归属取其 TenantId / AppId)。 + /// 生效作用域。 /// 创建请求。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -153,8 +153,6 @@ public async Task> CreateAsync(OnlineScope scope, Onl var season = new OnlineSeason { SeasonId = request.SeasonId, - TenantId = scope.TenantId, - AppId = scope.AppId, LeaderboardId = request.LeaderboardId, StartTime = request.StartTime, EndTime = request.EndTime, @@ -169,14 +167,14 @@ public async Task> CreateAsync(OnlineScope scope, Onl return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "赛季标识已存在"); } - await PublishAsync(OnlineSeasonEvents.CreateSeasonCreated(created.SeasonId, created.TenantId, created.AppId, created.LeaderboardId, created.StartTime, created.EndTime, created.RewardRules == null ? 0 : created.RewardRules.Count, created.State.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineSeasonEvents.CreateSeasonCreated(created.SeasonId, created.LeaderboardId, created.StartTime, created.EndTime, created.RewardRules == null ? 0 : created.RewardRules.Count, created.State.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(created); } /// /// 开始赛季( → )。 /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛季标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -197,7 +195,7 @@ public async Task> StartAsync(OnlineScope scope, stri season.State = OnlineSeasonState.Active; await _seasonStore.SaveAsync(season, cancellationToken).ConfigureAwait(false); - await PublishAsync(OnlineSeasonEvents.CreateSeasonStarted(season.SeasonId, season.TenantId, season.AppId, season.LeaderboardId, season.StartTime, season.EndTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineSeasonEvents.CreateSeasonStarted(season.SeasonId, season.LeaderboardId, season.StartTime, season.EndTime), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(season); } @@ -209,7 +207,7 @@ public async Task> StartAsync(OnlineScope scope, stri /// 未被改变(期间落档的中间快照不匹配任何已清空的榜单,会被下次成功重试整体覆盖),由调用方稍后重试。 /// /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛季标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -249,7 +247,7 @@ public async Task> EndAsync(OnlineScope scope season.State = OnlineSeasonState.Ended; season.EndedTime = now; await _seasonStore.SaveAsync(season, cancellationToken).ConfigureAwait(false); - await PublishAsync(OnlineSeasonEvents.CreateSeasonEnded(season.SeasonId, season.TenantId, season.AppId, season.LeaderboardId, season.EndedTime, snapshot.Entries == null ? 0 : snapshot.Entries.Count, snapshot.SnapshottedTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineSeasonEvents.CreateSeasonEnded(season.SeasonId, season.LeaderboardId, season.EndedTime, snapshot.Entries == null ? 0 : snapshot.Entries.Count, snapshot.SnapshottedTime), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(snapshot); } @@ -259,7 +257,7 @@ public async Task> EndAsync(OnlineScope scope /// /// 查询赛季历史快照(重置后可回溯旧榜;快照是长期保留的冻结事实,不随新一届写入变化)。 /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛季标识。 /// 取消令牌。 /// 历史快照;失败返回对应错误码。 @@ -271,7 +269,7 @@ public async Task> GetSnapshotAsync(OnlineSco return OnlineResult.Fail(seasonResult.Code, seasonResult.Message); } - var snapshot = await _seasonStore.FindSnapshotAsync(scope.TenantId, scope.AppId, seasonResult.Data.SeasonId, cancellationToken).ConfigureAwait(false); + var snapshot = await _seasonStore.FindSnapshotAsync(seasonResult.Data.SeasonId, cancellationToken).ConfigureAwait(false); if (snapshot == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "赛季尚未结束,无历史快照"); @@ -288,7 +286,7 @@ public async Task> GetSnapshotAsync(OnlineSco /// 不会被重复发放,此前失败的玩家能否补发取决于宿主的幂等失败重放策略(见类型级维护约束 (3))。 /// /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛季标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -308,7 +306,7 @@ public async Task> SettleAsync(Onlin return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "赛季尚未结束,不能结算:" + season.State); } - var snapshot = await _seasonStore.FindSnapshotAsync(scope.TenantId, scope.AppId, season.SeasonId, cancellationToken).ConfigureAwait(false); + var snapshot = await _seasonStore.FindSnapshotAsync(season.SeasonId, cancellationToken).ConfigureAwait(false); if (snapshot == null) { return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "赛季快照缺失,拒绝结算"); @@ -328,7 +326,7 @@ public async Task> SettleAsync(Onlin season.State = OnlineSeasonState.Settled; season.SettledTime = now; await _seasonStore.SaveAsync(season, cancellationToken).ConfigureAwait(false); - await PublishAsync(OnlineSeasonEvents.CreateSeasonSettled(season.SeasonId, season.TenantId, season.AppId, season.SettledTime, outcome.GrantedCount, outcome.ReplayCount, outcome.FailedPlayers == null ? 0 : outcome.FailedPlayers.Count), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineSeasonEvents.CreateSeasonSettled(season.SeasonId, season.SettledTime, outcome.GrantedCount, outcome.ReplayCount, outcome.FailedPlayers == null ? 0 : outcome.FailedPlayers.Count), cancellationToken).ConfigureAwait(false); } return OnlineResult.Ok(outcome); @@ -337,7 +335,7 @@ public async Task> SettleAsync(Onlin /// /// 按冻结快照逐条目结算奖励(跳过无效视图与名次未命中规则的条目;发放经 幂等执行)。 /// - /// 赛季定义(提供作用域与奖励规则)。 + /// 赛季定义(提供奖励规则)。 /// 结算依据的冻结快照。 /// 累计回执。 /// 取消令牌。 @@ -369,7 +367,7 @@ private async Task SettleSnapshotEntriesAsync(OnlineSeason season, OnlineSeasonS /// /// 结算单玩家:经统一资产入口发放(幂等键确定性派生,重试回放首次结果);失败逐玩家隔离。 /// - /// 赛季定义(提供作用域与结算标识)。 + /// 赛季定义(提供结算标识)。 /// 玩家标识。 /// 奖励变更行。 /// 累计回执。 @@ -378,7 +376,7 @@ private async Task SettleSnapshotEntriesAsync(OnlineSeason season, OnlineSeasonS private async Task SettlePlayerAsync(OnlineSeason season, long playerId, IReadOnlyList rewards, OnlineSeasonSettlementOutcome outcome, CancellationToken cancellationToken) { var businessOrderId = BuildBusinessOrderId(season.SeasonId, playerId); - var playerScope = new OnlineScope(season.TenantId, season.AppId, SeasonScopeServerId, playerId); + var playerScope = new OnlineScope(SeasonScopeServerId, playerId); var request = new OnlineGrantRequest( playerScope, OnlineAssetChangeSource.MatchReward, @@ -414,7 +412,7 @@ private async Task SettlePlayerAsync(OnlineSeason season, long playerId, IReadOn } /// - /// 按作用域解析赛季定义(跨作用域与不存在同构返回失败 ResourceNotFound)。 + /// 按标识解析赛季定义(不存在同构返回失败 ResourceNotFound)。 /// /// 生效作用域。 /// 赛季标识。 @@ -432,7 +430,7 @@ private async Task> ResolveSeasonAsync(OnlineScope sc return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "赛季标识不能为空"); } - var season = await _seasonStore.FindAsync(scope.TenantId, scope.AppId, seasonId, cancellationToken).ConfigureAwait(false); + var season = await _seasonStore.FindAsync(seasonId, cancellationToken).ConfigureAwait(false); if (season == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "赛季不存在"); @@ -453,8 +451,6 @@ private static OnlineSeasonSnapshot BuildSnapshot(OnlineSeason season, List(), diff --git a/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonSnapshot.cs b/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonSnapshot.cs index 92ff6e5e4..c4b24f889 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonSnapshot.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Season/OnlineSeasonSnapshot.cs @@ -51,16 +51,6 @@ public sealed class OnlineSeasonSnapshot /// public string SeasonId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置快照来源的榜单标识。 /// @@ -97,8 +87,6 @@ public OnlineSeasonSnapshot Copy() return new OnlineSeasonSnapshot { SeasonId = SeasonId, - TenantId = TenantId, - AppId = AppId, LeaderboardId = LeaderboardId, SnapshottedTime = SnapshottedTime, Entries = entries, diff --git a/Capability/GameFrameX.Capability.Online.Competition/Tournament/IOnlineTournamentStore.cs b/Capability/GameFrameX.Capability.Online.Competition/Tournament/IOnlineTournamentStore.cs index 4f0f1c718..eeb6cf173 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Tournament/IOnlineTournamentStore.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Tournament/IOnlineTournamentStore.cs @@ -37,7 +37,7 @@ namespace GameFrameX.Capability.Online.Competition.Tournament; /// 赛事存储契约(赛事定义 + 报名登记 + 冻结成绩;InMemory 为单进程默认实现,生产持久化归 Server 仓运行时装配)。 /// /// 维护约束(红线): -/// (1) 作用域隔离——所有查询以 (TenantId, AppId) 为前置条件,跨作用域访问与不存在同构(null,反预言); +/// (1) 赛事为全局域数据——字典键即 TournamentId(报名登记键 = (TournamentId, PlayerId),无区服隔离位); /// (2) 冻结成绩与赛事定义**分离存储**:成绩一经写入即为冻结事实,赛事状态推进() /// 不得改写成绩内容——「结果查询」的存储层保证; /// (3) 报名的「判定重复 + 落档」必须在**同一临界区**完成(), @@ -48,25 +48,23 @@ namespace GameFrameX.Capability.Online.Competition.Tournament; public interface IOnlineTournamentStore { /// - /// 创建赛事(同作用域同标识赛事已存在时拒绝,返回 null,不覆盖)。 + /// 创建赛事(同标识赛事已存在时拒绝,返回 null,不覆盖)。 /// - /// 赛事定义(作用域取其 TenantId / AppId)。 + /// 赛事定义。 /// 取消令牌。 /// 创建后的赛事副本;已存在返回 null。 Task CreateAsync(OnlineTournament tournament, CancellationToken cancellationToken = default); /// - /// 按作用域查找赛事定义。 + /// 按赛事标识查找赛事定义。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 取消令牌。 - /// 赛事副本;不存在或跨作用域返回 null。 - Task FindAsync(long tenantId, long appId, string tournamentId, CancellationToken cancellationToken = default); + /// 赛事副本;不存在返回 null。 + Task FindAsync(string tournamentId, CancellationToken cancellationToken = default); /// - /// 保存赛事定义(状态推进落档;按作用域 + 赛事标识覆盖既有定义,赛事必须已存在)。 + /// 保存赛事定义(状态推进落档;按赛事标识覆盖既有定义,赛事必须已存在)。 /// /// 赛事定义(含推进后的状态与时间戳)。 /// 取消令牌。 @@ -85,26 +83,22 @@ public interface IOnlineTournamentStore /// /// 查找单个玩家的报名登记。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 玩家标识。 /// 取消令牌。 - /// 登记副本;未报名或跨作用域返回 null。 - Task FindRegistrationAsync(long tenantId, long appId, string tournamentId, long playerId, CancellationToken cancellationToken = default); + /// 登记副本;未报名返回 null。 + Task FindRegistrationAsync(string tournamentId, long playerId, CancellationToken cancellationToken = default); /// /// 列出赛事的全部报名登记(按报名时刻升序,供参赛名册查询与测试断言)。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 取消令牌。 /// 登记副本列表;无报名返回空列表。 - Task> ListRegistrationsAsync(long tenantId, long appId, string tournamentId, CancellationToken cancellationToken = default); + Task> ListRegistrationsAsync(string tournamentId, CancellationToken cancellationToken = default); /// - /// 保存冻结成绩(按作用域 + 赛事标识覆盖;赛事结束流程在推进状态**之前**调用——成绩先行)。 + /// 保存冻结成绩(按赛事标识覆盖;赛事结束流程在推进状态**之前**调用——成绩先行)。 /// /// 冻结成绩。 /// 取消令牌。 @@ -112,12 +106,10 @@ public interface IOnlineTournamentStore Task SaveStandingsAsync(OnlineTournamentStandings standings, CancellationToken cancellationToken = default); /// - /// 按作用域查找冻结成绩。 + /// 按赛事标识查找冻结成绩。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 取消令牌。 - /// 成绩副本;不存在或跨作用域返回 null。 - Task FindStandingsAsync(long tenantId, long appId, string tournamentId, CancellationToken cancellationToken = default); + /// 成绩副本;不存在返回 null。 + Task FindStandingsAsync(string tournamentId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Tournament/InMemoryOnlineTournamentStore.cs b/Capability/GameFrameX.Capability.Online.Competition/Tournament/InMemoryOnlineTournamentStore.cs index 2138237b4..efe97d5fc 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Tournament/InMemoryOnlineTournamentStore.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Tournament/InMemoryOnlineTournamentStore.cs @@ -49,13 +49,13 @@ public sealed class InMemoryOnlineTournamentStore : IOnlineTournamentStore /// 全局锁(三张表共用,保证出入参一致性与报名的临界区语义)。 private readonly object _syncRoot = new(); - /// 赛事定义表:键 = (TenantId, AppId, TournamentId)。 + /// 赛事定义表:键 = TournamentId(全局域数据,无区服隔离位)。 private readonly Dictionary _tournaments = new(); - /// 报名登记表:键 = (TenantId, AppId, TournamentId, PlayerId)。 + /// 报名登记表:键 = (TournamentId, PlayerId)。 private readonly Dictionary _registrations = new(); - /// 冻结成绩表:键 = (TenantId, AppId, TournamentId)。 + /// 冻结成绩表:键 = TournamentId。 private readonly Dictionary _standings = new(); /// @@ -66,14 +66,14 @@ public InMemoryOnlineTournamentStore() } /// - /// 创建赛事(内存实现:在全局锁内完成重复判定与落档,同作用域同标识已存在时返回 null 且不覆盖,出入参均为防御性副本)。 + /// 创建赛事(内存实现:在全局锁内完成重复判定与落档,同标识已存在时返回 null 且不覆盖,出入参均为防御性副本)。 /// /// - /// Creates a tournament (in-memory implementation: duplicate check and persistence complete inside the global lock; returns null without overwriting when the same identifier already exists in the same scope; inputs and outputs are defensive copies). + /// Creates a tournament (in-memory implementation: duplicate check and persistence complete inside the global lock; returns null without overwriting when the same identifier already exists; inputs and outputs are defensive copies). /// - /// 赛事定义(作用域取其 TenantId / AppId)/ The tournament definition (scope taken from its TenantId / AppId) + /// 赛事定义 / The tournament definition /// 取消令牌(内存实现忽略)/ The cancellation token (ignored by the in-memory implementation) - /// 创建后的赛事副本;同作用域同标识已存在时为 null / A copy of the created tournament; null when the identifier already exists in the same scope + /// 创建后的赛事副本;同标识已存在时为 null / A copy of the created tournament; null when the identifier already exists /// 当 为 null 时抛出 / Thrown when is null public Task CreateAsync(OnlineTournament tournament, CancellationToken cancellationToken = default) { @@ -84,7 +84,7 @@ public Task CreateAsync(OnlineTournament tournament, Cancellat lock (_syncRoot) { - var key = BuildKey(tournament.TenantId, tournament.AppId, tournament.TournamentId); + var key = BuildKey(tournament.TournamentId); if (_tournaments.ContainsKey(key)) { return Task.FromResult(null); @@ -96,21 +96,19 @@ public Task CreateAsync(OnlineTournament tournament, Cancellat } /// - /// 按作用域查找赛事定义(内存实现:全局锁内按作用域 + 赛事标识查表,返回防御性副本;不存在返回 null)。 + /// 按赛事标识查找赛事定义(内存实现:全局锁内按赛事标识查表,返回防御性副本;不存在返回 null)。 /// /// - /// Finds a tournament definition by scope (in-memory implementation: looks the table up by scope plus tournament identifier inside the global lock and returns a defensive copy; null when absent). + /// Finds a tournament definition (in-memory implementation: looks the table up by tournament identifier inside the global lock and returns a defensive copy; null when absent). /// - /// 租户标识 / The tenant identifier - /// App 标识 / The app identifier /// 赛事标识 / The tournament identifier /// 取消令牌(内存实现忽略)/ The cancellation token (ignored by the in-memory implementation) /// 赛事副本;不存在时为 null / A copy of the tournament; null when absent - public Task FindAsync(long tenantId, long appId, string tournamentId, CancellationToken cancellationToken = default) + public Task FindAsync(string tournamentId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(_tournaments.TryGetValue(BuildKey(tenantId, appId, tournamentId), out var stored) ? stored.Copy() : null); + return Task.FromResult(_tournaments.TryGetValue(BuildKey(tournamentId), out var stored) ? stored.Copy() : null); } } @@ -123,7 +121,7 @@ public Task FindAsync(long tenantId, long appId, string tourna /// 赛事定义(含推进后的状态与时间戳)/ The tournament definition (with the advanced state and timestamps) /// 取消令牌(内存实现忽略)/ The cancellation token (ignored by the in-memory implementation) /// 当 为 null 时抛出 / Thrown when is null - /// 当同作用域同标识的赛事不存在时抛出 / Thrown when the tournament with the same identifier in the same scope does not exist + /// 当同标识的赛事不存在时抛出 / Thrown when the tournament with the same identifier does not exist public Task SaveAsync(OnlineTournament tournament, CancellationToken cancellationToken = default) { if (tournament == null) @@ -133,7 +131,7 @@ public Task SaveAsync(OnlineTournament tournament, CancellationToken cancellatio lock (_syncRoot) { - var key = BuildKey(tournament.TenantId, tournament.AppId, tournament.TournamentId); + var key = BuildKey(tournament.TournamentId); if (!_tournaments.ContainsKey(key)) { // Localization: Online.Tournament.NotFoundOnSave - 赛事不存在,保存前必须先经 CreateAsync 建立 @@ -164,7 +162,7 @@ public Task TryRegisterAsync(OnlineTournamen lock (_syncRoot) { - var key = BuildRegistrationKey(registration.TenantId, registration.AppId, registration.TournamentId, registration.PlayerId); + var key = BuildRegistrationKey(registration.TournamentId, registration.PlayerId); if (_registrations.TryGetValue(key, out var existing)) { return Task.FromResult(new OnlineTournamentRegistrationResult { IsNew = false, Registration = existing.Copy(), }); @@ -176,22 +174,20 @@ public Task TryRegisterAsync(OnlineTournamen } /// - /// 查找单个玩家的报名登记(内存实现:全局锁内按作用域 + 赛事标识 + 玩家标识查表,返回防御性副本;未报名返回 null)。 + /// 查找单个玩家的报名登记(内存实现:全局锁内按赛事标识 + 玩家标识查表,返回防御性副本;未报名返回 null)。 /// /// - /// Finds a single player's registration (in-memory implementation: looks the table up by scope, tournament identifier and player identifier inside the global lock and returns a defensive copy; null when not registered). + /// Finds a single player's registration (in-memory implementation: looks the table up by tournament identifier and player identifier inside the global lock and returns a defensive copy; null when not registered). /// - /// 租户标识 / The tenant identifier - /// App 标识 / The app identifier /// 赛事标识 / The tournament identifier /// 玩家标识 / The player identifier /// 取消令牌(内存实现忽略)/ The cancellation token (ignored by the in-memory implementation) /// 登记副本;未报名时为 null / A copy of the registration; null when not registered - public Task FindRegistrationAsync(long tenantId, long appId, string tournamentId, long playerId, CancellationToken cancellationToken = default) + public Task FindRegistrationAsync(string tournamentId, long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(_registrations.TryGetValue(BuildRegistrationKey(tenantId, appId, tournamentId, playerId), out var stored) ? stored.Copy() : null); + return Task.FromResult(_registrations.TryGetValue(BuildRegistrationKey(tournamentId, playerId), out var stored) ? stored.Copy() : null); } } @@ -201,16 +197,14 @@ public Task FindRegistrationAsync(long tenantId, l /// /// Lists all registrations of a tournament (in-memory implementation: scans the registration table by tournament-key prefix inside the global lock, copies each entry and sorts by registration time ascending). /// - /// 租户标识 / The tenant identifier - /// App 标识 / The app identifier /// 赛事标识 / The tournament identifier /// 取消令牌(内存实现忽略)/ The cancellation token (ignored by the in-memory implementation) /// 按报名时刻升序的登记副本列表;无报名时为空列表 / The list of registration copies sorted by registration time ascending; an empty list when none - public Task> ListRegistrationsAsync(long tenantId, long appId, string tournamentId, CancellationToken cancellationToken = default) + public Task> ListRegistrationsAsync(string tournamentId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - var prefix = BuildKey(tenantId, appId, tournamentId) + ":"; + var prefix = BuildKey(tournamentId) + ":"; var registrations = new List(); foreach (var pair in _registrations) { @@ -226,10 +220,10 @@ public Task> ListRegistrationsAsync(long tena } /// - /// 保存冻结成绩(内存实现:全局锁内按作用域 + 赛事标识覆盖写入成绩表的防御性副本,独立于赛事定义表)。 + /// 保存冻结成绩(内存实现:全局锁内按赛事标识覆盖写入成绩表的防御性副本,独立于赛事定义表)。 /// /// - /// Saves frozen standings (in-memory implementation: overwrites the standings table with a defensive copy keyed by scope plus tournament identifier inside the global lock, independently of the tournament table). + /// Saves frozen standings (in-memory implementation: overwrites the standings table with a defensive copy keyed by tournament identifier inside the global lock, independently of the tournament table). /// /// 冻结成绩 / The frozen standings /// 取消令牌(内存实现忽略)/ The cancellation token (ignored by the in-memory implementation) @@ -243,52 +237,46 @@ public Task SaveStandingsAsync(OnlineTournamentStandings standings, Cancellation lock (_syncRoot) { - _standings[BuildKey(standings.TenantId, standings.AppId, standings.TournamentId)] = standings.Copy(); + _standings[BuildKey(standings.TournamentId)] = standings.Copy(); return Task.CompletedTask; } } /// - /// 按作用域查找冻结成绩(内存实现:全局锁内查冻结成绩表,返回防御性副本;不存在返回 null)。 + /// 按赛事标识查找冻结成绩(内存实现:全局锁内查冻结成绩表,返回防御性副本;不存在返回 null)。 /// /// - /// Finds frozen standings by scope (in-memory implementation: looks up the frozen-standings table inside the global lock and returns a defensive copy; null when absent). + /// Finds frozen standings (in-memory implementation: looks up the frozen-standings table inside the global lock and returns a defensive copy; null when absent). /// - /// 租户标识 / The tenant identifier - /// App 标识 / The app identifier /// 赛事标识 / The tournament identifier /// 取消令牌(内存实现忽略)/ The cancellation token (ignored by the in-memory implementation) /// 成绩副本;不存在时为 null / A copy of the standings; null when absent - public Task FindStandingsAsync(long tenantId, long appId, string tournamentId, CancellationToken cancellationToken = default) + public Task FindStandingsAsync(string tournamentId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(_standings.TryGetValue(BuildKey(tenantId, appId, tournamentId), out var stored) ? stored.Copy() : null); + return Task.FromResult(_standings.TryGetValue(BuildKey(tournamentId), out var stored) ? stored.Copy() : null); } } /// - /// 构造赛事级存储键(作用域 + 赛事标识;跨作用域访问因键不同而自然隔离)。 + /// 构造赛事级存储键(赛事标识即键——全局域数据,同键即同赛)。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 存储键。 - private static string BuildKey(long tenantId, long appId, string tournamentId) + private static string BuildKey(string tournamentId) { - return tenantId.ToString(CultureInfo.InvariantCulture) + ":" + appId.ToString(CultureInfo.InvariantCulture) + ":" + (tournamentId ?? string.Empty); + return tournamentId ?? string.Empty; } /// /// 构造报名登记存储键(赛事键 + 玩家标识;同一玩家在同一赛事内只有一键)。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 玩家标识。 /// 存储键。 - private static string BuildRegistrationKey(long tenantId, long appId, string tournamentId, long playerId) + private static string BuildRegistrationKey(string tournamentId, long playerId) { - return BuildKey(tenantId, appId, tournamentId) + ":" + playerId.ToString(CultureInfo.InvariantCulture); + return BuildKey(tournamentId) + ":" + playerId.ToString(CultureInfo.InvariantCulture); } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournament.cs b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournament.cs index 2b7e40361..03b6efd10 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournament.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournament.cs @@ -35,8 +35,7 @@ namespace GameFrameX.Capability.Online.Competition.Tournament; /// 赛事定义(开始/结束时间、关联榜单、资格条件、赛事奖励与结算状态)。 /// /// 维护约束(红线): -/// (1) 作用域 = (TenantId, AppId),与榜单 / 赛季同口径(App 内跨区服聚合)——跨 App / 跨租户读写 -/// 一律查不到(ResourceNotFound 反预言,对齐既有先例); +/// (1) 赛事为全局域数据(与榜单 / 赛季同口径)——键即 TournamentId,无区服隔离位,同键即同赛; /// (2) 赛事本身**不承载分数与名次**:成绩只存在于冻结的 中, /// 赛事只描述周期、门槛与奖励口径; /// (3) 赛事**只读关联榜单、从不写入或重置**——榜单的写入归可信链路、重置归赛季域; @@ -49,20 +48,10 @@ namespace GameFrameX.Capability.Online.Competition.Tournament; public sealed class OnlineTournament { /// - /// 获取或设置赛事标识(App 内唯一,创建方提供)。 + /// 获取或设置赛事标识(全局唯一,创建方提供)。 /// public string TournamentId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置关联榜单标识(报名资格判定与结束成绩冻结的唯一数据来源;本赛事只读该榜)。 /// @@ -134,8 +123,6 @@ public OnlineTournament Copy() return new OnlineTournament { TournamentId = TournamentId, - TenantId = TenantId, - AppId = AppId, LeaderboardId = LeaderboardId, StartTime = StartTime, EndTime = EndTime, diff --git a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentEvents.cs b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentEvents.cs index b6e0f1f1d..cd96169dc 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentEvents.cs @@ -71,8 +71,6 @@ public static class OnlineTournamentEvents /// /// 构造赛事创建事件。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 关联榜单标识。 /// 排期开始时刻(UTC 毫秒)。 @@ -82,7 +80,7 @@ public static class OnlineTournamentEvents /// 创建后的状态名。 /// 创建时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateTournamentCreated(long tenantId, long appId, string tournamentId, string leaderboardId, long startTime, long endTime, int minLeaderboardRank, int rewardRuleCount, string state, long createdTime) + public static OnlineEvent CreateTournamentCreated(string tournamentId, string leaderboardId, long startTime, long endTime, int minLeaderboardRank, int rewardRuleCount, string state, long createdTime) { var payload = new TournamentCreatedPayload { @@ -110,8 +108,6 @@ public static OnlineEvent CreateTournamentCreated(long tenantId, long appId, str EventType = TournamentCreated, OccurredTime = createdTime > 0 ? createdTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -124,15 +120,13 @@ public static OnlineEvent CreateTournamentCreated(long tenantId, long appId, str /// /// 构造赛事开始事件。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 关联榜单标识。 /// 排期开始时刻(UTC 毫秒)。 /// 排期结束时刻(UTC 毫秒)。 /// 开始时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateTournamentStarted(long tenantId, long appId, string tournamentId, string leaderboardId, long startTime, long endTime, long startedTime) + public static OnlineEvent CreateTournamentStarted(string tournamentId, string leaderboardId, long startTime, long endTime, long startedTime) { var payload = new TournamentStartedPayload { @@ -154,8 +148,6 @@ public static OnlineEvent CreateTournamentStarted(long tenantId, long appId, str EventType = TournamentStarted, OccurredTime = startedTime > 0 ? startedTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -168,15 +160,13 @@ public static OnlineEvent CreateTournamentStarted(long tenantId, long appId, str /// /// 构造玩家报名事件(玩家维度;仅在**首次**落档报名时发布,重放报名不重发)。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 报名玩家标识。 /// 报名时刻(UTC 毫秒)。 /// 报名时刻的名次(无资格门槛未查榜时为 0)。 /// 报名时刻的分数(无资格门槛未查榜时为 0)。 /// 事件信封实例。 - public static OnlineEvent CreateTournamentRegistered(long tenantId, long appId, string tournamentId, long playerId, long registeredTime, int rankAtRegistration, long scoreAtRegistration) + public static OnlineEvent CreateTournamentRegistered(string tournamentId, long playerId, long registeredTime, int rankAtRegistration, long scoreAtRegistration) { var payload = new TournamentRegisteredPayload { @@ -200,8 +190,6 @@ public static OnlineEvent CreateTournamentRegistered(long tenantId, long appId, EventType = TournamentRegistered, OccurredTime = registeredTime > 0 ? registeredTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = playerId, Source = Source, @@ -214,15 +202,13 @@ public static OnlineEvent CreateTournamentRegistered(long tenantId, long appId, /// /// 构造赛事结束事件(成绩冻结先行已完成的落定点;关联榜单未被本流程修改)。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 关联榜单标识。 /// 冻结成绩的条目数(仅计已报名参赛者)。 /// 成绩冻结时刻(UTC 毫秒)。 /// 结束时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateTournamentEnded(long tenantId, long appId, string tournamentId, string leaderboardId, int standingsEntryCount, long frozenTime, long endedTime) + public static OnlineEvent CreateTournamentEnded(string tournamentId, string leaderboardId, int standingsEntryCount, long frozenTime, long endedTime) { var payload = new TournamentEndedPayload { @@ -244,8 +230,6 @@ public static OnlineEvent CreateTournamentEnded(long tenantId, long appId, strin EventType = TournamentEnded, OccurredTime = endedTime > 0 ? endedTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -258,15 +242,13 @@ public static OnlineEvent CreateTournamentEnded(long tenantId, long appId, strin /// /// 构造赛事结算事件(仅在全量发放成功、赛事推进到结算完成态时发布)。 /// - /// 租户标识。 - /// App 标识。 /// 赛事标识。 /// 本次首次发放成功玩家数。 /// 本次命中幂等回放玩家数。 /// 本次发放失败玩家数(正常路径恒为 0)。 /// 结算时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateTournamentSettled(long tenantId, long appId, string tournamentId, int grantedCount, int replayCount, int failedCount, long settledTime) + public static OnlineEvent CreateTournamentSettled(string tournamentId, int grantedCount, int replayCount, int failedCount, long settledTime) { var payload = new TournamentSettledPayload { @@ -288,8 +270,6 @@ public static OnlineEvent CreateTournamentSettled(long tenantId, long appId, str EventType = TournamentSettled, OccurredTime = settledTime > 0 ? settledTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentRegistration.cs b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentRegistration.cs index 389e629b0..84b6a231b 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentRegistration.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentRegistration.cs @@ -46,16 +46,6 @@ public sealed class OnlineTournamentRegistration /// public string TournamentId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置报名玩家标识。 /// @@ -85,8 +75,6 @@ public OnlineTournamentRegistration Copy() return new OnlineTournamentRegistration { TournamentId = TournamentId, - TenantId = TenantId, - AppId = AppId, PlayerId = PlayerId, RegisteredTime = RegisteredTime, RankAtRegistration = RankAtRegistration, diff --git a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentService.cs b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentService.cs index c716db5ca..856c8f201 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentService.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentService.cs @@ -53,7 +53,7 @@ namespace GameFrameX.Capability.Online.Competition.Tournament; /// tournament-{TournamentId}-{PlayerId},重复触发命中回放返回首次结果,不重复发奖; /// (5) **逐玩家失败隔离**——单玩家发放失败只计入回执明细,不阻塞其余玩家;仅当无失败玩家才把赛事推进到 /// 结算完成态(部分发奖不得标记完成); -/// (6) 跨 App / 跨租户读写与「赛事不存在」同构返回 ResourceNotFound(反预言,对齐既有先例)。 +/// (6) 作用域校验失败与「赛事不存在」同构返回 ResourceNotFound(反预言,对齐既有先例)。 /// /// /// 运行时边界:StartTime/EndTime 只是排期元数据,到点驱动 / @@ -63,7 +63,7 @@ namespace GameFrameX.Capability.Online.Competition.Tournament; public sealed class OnlineTournamentService { /// - /// 赛事奖励发放使用的区服位(恒为 0):赛事与榜单同为 (TenantId, AppId) 作用域,**没有归属服**。 + /// 赛事奖励发放使用的区服位(恒为 0):赛事与榜单同为全局域数据,**没有归属服**。 /// 若改取调用方作用域的区服,同一赛事从不同区服触发结算会落到不同的幂等绑定键上,重试将不再回放首次结果 /// 而重复发奖。 /// @@ -97,9 +97,9 @@ public OnlineTournamentService(IOnlineTournamentStore tournamentStore, OnlineLea } /// - /// 创建赛事(同作用域同标识赛事已存在时拒绝;关联榜单必须已存在;奖励规则区间必须互不重叠)。 + /// 创建赛事(同标识赛事已存在时拒绝;关联榜单必须已存在;奖励规则区间必须互不重叠)。 /// - /// 生效作用域(赛事归属取其 TenantId / AppId)。 + /// 生效作用域。 /// 创建请求。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -150,8 +150,6 @@ public async Task> CreateAsync(OnlineScope scope, var tournament = new OnlineTournament { TournamentId = request.TournamentId, - TenantId = scope.TenantId, - AppId = scope.AppId, LeaderboardId = request.LeaderboardId, StartTime = request.StartTime, EndTime = request.EndTime, @@ -167,14 +165,14 @@ public async Task> CreateAsync(OnlineScope scope, return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "赛事标识已存在"); } - await PublishAsync(OnlineTournamentEvents.CreateTournamentCreated(created.TenantId, created.AppId, created.TournamentId, created.LeaderboardId, created.StartTime, created.EndTime, created.Eligibility == null ? 0 : created.Eligibility.MinLeaderboardRank, created.RewardRules == null ? 0 : created.RewardRules.Count, created.State.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineTournamentEvents.CreateTournamentCreated(created.TournamentId, created.LeaderboardId, created.StartTime, created.EndTime, created.Eligibility == null ? 0 : created.Eligibility.MinLeaderboardRank, created.RewardRules == null ? 0 : created.RewardRules.Count, created.State.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(created); } /// /// 开始赛事( → ;**开始即关闭报名窗口**)。 /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛事标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -196,7 +194,7 @@ public async Task> StartAsync(OnlineScope scope, tournament.State = OnlineTournamentState.Active; tournament.StartedTime = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await _tournamentStore.SaveAsync(tournament, cancellationToken).ConfigureAwait(false); - await PublishAsync(OnlineTournamentEvents.CreateTournamentStarted(tournament.TenantId, tournament.AppId, tournament.TournamentId, tournament.LeaderboardId, tournament.StartTime, tournament.EndTime, tournament.StartedTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineTournamentEvents.CreateTournamentStarted(tournament.TournamentId, tournament.LeaderboardId, tournament.StartTime, tournament.EndTime, tournament.StartedTime), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(tournament); } @@ -209,7 +207,7 @@ public async Task> StartAsync(OnlineScope scope, /// 重复报名返回既有登记并置 ,不新增登记、不重发事件。 /// /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛事标识。 /// 报名玩家标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 @@ -270,8 +268,6 @@ public async Task> RegisterAsy var registration = new OnlineTournamentRegistration { TournamentId = tournament.TournamentId, - TenantId = tournament.TenantId, - AppId = tournament.AppId, PlayerId = playerId, RegisteredTime = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), RankAtRegistration = rank, @@ -284,7 +280,7 @@ public async Task> RegisterAsy if (!isReplay) { - await PublishAsync(OnlineTournamentEvents.CreateTournamentRegistered(tournament.TenantId, tournament.AppId, tournament.TournamentId, stored.PlayerId, stored.RegisteredTime, stored.RankAtRegistration, stored.ScoreAtRegistration), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineTournamentEvents.CreateTournamentRegistered(tournament.TournamentId, stored.PlayerId, stored.RegisteredTime, stored.RankAtRegistration, stored.ScoreAtRegistration), cancellationToken).ConfigureAwait(false); } return OnlineResult.Ok(new OnlineTournamentRegistrationOutcome @@ -304,7 +300,7 @@ public async Task> RegisterAsy /// 在参赛者集合内重新编号 1..N,使赛事名次是赛事内部的事实。**本流程不修改关联榜单**(只读)。 /// /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛事标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -330,7 +326,7 @@ public async Task> EndAsync(OnlineScope } var entries = await _leaderboardService.ListOrderedEntriesForSeasonAsync(boardResult.Data, cancellationToken).ConfigureAwait(false); - var registrations = await _tournamentStore.ListRegistrationsAsync(tournament.TenantId, tournament.AppId, tournament.TournamentId, cancellationToken).ConfigureAwait(false); + var registrations = await _tournamentStore.ListRegistrationsAsync(tournament.TournamentId, cancellationToken).ConfigureAwait(false); var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var standings = BuildStandings(tournament, entries, registrations, now); @@ -339,14 +335,14 @@ public async Task> EndAsync(OnlineScope tournament.State = OnlineTournamentState.Ended; tournament.EndedTime = now; await _tournamentStore.SaveAsync(tournament, cancellationToken).ConfigureAwait(false); - await PublishAsync(OnlineTournamentEvents.CreateTournamentEnded(tournament.TenantId, tournament.AppId, tournament.TournamentId, tournament.LeaderboardId, standings.Entries == null ? 0 : standings.Entries.Count, standings.FrozenTime, tournament.EndedTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineTournamentEvents.CreateTournamentEnded(tournament.TournamentId, tournament.LeaderboardId, standings.Entries == null ? 0 : standings.Entries.Count, standings.FrozenTime, tournament.EndedTime), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(standings); } /// /// 查询赛事冻结成绩(结果查询;冻结后不随关联榜单变化)。 /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛事标识。 /// 取消令牌。 /// 冻结成绩;失败返回对应错误码。 @@ -358,7 +354,7 @@ public async Task> GetStandingsAsync(Onl return OnlineResult.Fail(tournamentResult.Code, tournamentResult.Message); } - var standings = await _tournamentStore.FindStandingsAsync(scope.TenantId, scope.AppId, tournamentResult.Data.TournamentId, cancellationToken).ConfigureAwait(false); + var standings = await _tournamentStore.FindStandingsAsync(tournamentResult.Data.TournamentId, cancellationToken).ConfigureAwait(false); if (standings == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "赛事尚未结束,无冻结成绩"); @@ -370,7 +366,7 @@ public async Task> GetStandingsAsync(Onl /// /// 查询玩家报名登记(结果查询半边:报名事实与报名时刻冻结的资格判定输入)。 /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛事标识。 /// 玩家标识。 /// 取消令牌。 @@ -383,7 +379,7 @@ public async Task> GetRegistrationAsy return OnlineResult.Fail(tournamentResult.Code, tournamentResult.Message); } - var registration = await _tournamentStore.FindRegistrationAsync(scope.TenantId, scope.AppId, tournamentResult.Data.TournamentId, playerId, cancellationToken).ConfigureAwait(false); + var registration = await _tournamentStore.FindRegistrationAsync(tournamentResult.Data.TournamentId, playerId, cancellationToken).ConfigureAwait(false); if (registration == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "该玩家未报名本赛事"); @@ -401,7 +397,7 @@ public async Task> GetRegistrationAsy /// (同款装配依赖:默认 ReplayError 下失败键在保留期内原样回放)。 /// /// - /// 生效作用域(跨作用域与不存在同构拒绝)。 + /// 生效作用域(不存在同构拒绝)。 /// 赛事标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -421,7 +417,7 @@ public async Task> SettleAsync(O return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "赛事尚未结束,不能结算:" + tournament.State); } - var standings = await _tournamentStore.FindStandingsAsync(scope.TenantId, scope.AppId, tournament.TournamentId, cancellationToken).ConfigureAwait(false); + var standings = await _tournamentStore.FindStandingsAsync(tournament.TournamentId, cancellationToken).ConfigureAwait(false); if (standings == null) { return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "赛事冻结成绩缺失,拒绝结算"); @@ -440,7 +436,7 @@ public async Task> SettleAsync(O tournament.State = OnlineTournamentState.Settled; tournament.SettledTime = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await _tournamentStore.SaveAsync(tournament, cancellationToken).ConfigureAwait(false); - await PublishAsync(OnlineTournamentEvents.CreateTournamentSettled(tournament.TenantId, tournament.AppId, tournament.TournamentId, outcome.GrantedCount, outcome.ReplayCount, outcome.FailedPlayers == null ? 0 : outcome.FailedPlayers.Count, tournament.SettledTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineTournamentEvents.CreateTournamentSettled(tournament.TournamentId, outcome.GrantedCount, outcome.ReplayCount, outcome.FailedPlayers == null ? 0 : outcome.FailedPlayers.Count, tournament.SettledTime), cancellationToken).ConfigureAwait(false); } return OnlineResult.Ok(outcome); @@ -449,7 +445,7 @@ public async Task> SettleAsync(O /// /// 按冻结成绩逐条目结算奖励(跳过无效视图与名次未命中规则的条目;发放经 幂等执行)。 /// - /// 赛事定义(提供作用域与奖励规则)。 + /// 赛事定义(提供奖励规则)。 /// 结算依据的冻结成绩。 /// 累计回执。 /// 取消令牌。 @@ -481,7 +477,7 @@ private async Task SettleStandingsEntriesAsync(OnlineTournament tournament, Onli /// /// 结算单玩家:经统一资产入口发放(幂等键确定性派生,重试回放首次结果);失败逐玩家隔离。 /// - /// 赛事定义(提供作用域与结算标识)。 + /// 赛事定义(提供结算标识)。 /// 玩家标识。 /// 奖励变更行。 /// 累计回执。 @@ -490,7 +486,7 @@ private async Task SettleStandingsEntriesAsync(OnlineTournament tournament, Onli private async Task SettlePlayerAsync(OnlineTournament tournament, long playerId, IReadOnlyList rewards, OnlineTournamentSettlementOutcome outcome, CancellationToken cancellationToken) { var businessOrderId = BuildBusinessOrderId(tournament.TournamentId, playerId); - var playerScope = new OnlineScope(tournament.TenantId, tournament.AppId, TournamentScopeServerId, playerId); + var playerScope = new OnlineScope(TournamentScopeServerId, playerId); var request = new OnlineGrantRequest( playerScope, OnlineAssetChangeSource.MatchReward, @@ -526,7 +522,7 @@ private async Task SettlePlayerAsync(OnlineTournament tournament, long playerId, } /// - /// 按作用域解析赛事定义(跨作用域与不存在同构返回失败 ResourceNotFound)。 + /// 按标识解析赛事定义(不存在同构返回失败 ResourceNotFound)。 /// /// 生效作用域。 /// 赛事标识。 @@ -544,7 +540,7 @@ private async Task> ResolveTournamentAsync(Online return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "赛事标识不能为空"); } - var tournament = await _tournamentStore.FindAsync(scope.TenantId, scope.AppId, tournamentId, cancellationToken).ConfigureAwait(false); + var tournament = await _tournamentStore.FindAsync(tournamentId, cancellationToken).ConfigureAwait(false); if (tournament == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "赛事不存在"); @@ -566,8 +562,6 @@ private static OnlineTournamentStandings BuildStandings(OnlineTournament tournam var standings = new OnlineTournamentStandings { TournamentId = tournament.TournamentId, - TenantId = tournament.TenantId, - AppId = tournament.AppId, LeaderboardId = tournament.LeaderboardId, FrozenTime = frozenTime, Entries = new List(), diff --git a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentStandings.cs b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentStandings.cs index 07151d9df..5280c1151 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentStandings.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Tournament/OnlineTournamentStandings.cs @@ -52,16 +52,6 @@ public sealed class OnlineTournamentStandings /// public string TournamentId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置成绩来源的榜单标识。 /// @@ -98,8 +88,6 @@ public OnlineTournamentStandings Copy() return new OnlineTournamentStandings { TournamentId = TournamentId, - TenantId = TenantId, - AppId = AppId, LeaderboardId = LeaderboardId, FrozenTime = FrozenTime, Entries = entries, diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/IOnlineIdentityStore.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/IOnlineIdentityStore.cs index 4e53d1534..1b6a7239e 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/IOnlineIdentityStore.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/IOnlineIdentityStore.cs @@ -32,22 +32,20 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; /// /// 身份域存储接口(Identity/GameAccount/Player/Device 数据关系的持久化契约)。 /// -/// 维护约束:唯一性索引——Identity(TenantId, AppId, Kind, Identifier)、Device(GameAccountId, DeviceIdentifier); -/// 查询键——Player 按 (GameAccountId, AppId, ServerId) 归属检索; +/// 维护约束:唯一性索引——Identity(Kind, Identifier)、Device(GameAccountId, DeviceIdentifier); +/// 查询键——Player 按 (GameAccountId, ServerId) 归属检索; /// 生产装配以 Mongo 等持久化实现本接口(复用不 fork),本仓交付线程安全的内存默认实现; /// 实现方必须保证 AddOrUpdate 系列为幂等全量写(按主键覆盖)。 /// /// public interface IOnlineIdentityStore { - /// 按唯一键 (TenantId, AppId, Kind, Identifier) 查找身份。 - /// 租户标识。 - /// 应用标识。 + /// 按唯一键 (Kind, Identifier) 查找身份。 /// 身份类型。 /// 身份标识串。 /// 取消令牌。 /// 身份实体;不存在返回 null。 - Task FindIdentityAsync(long tenantId, long appId, OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default); + Task FindIdentityAsync(OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default); /// 写入或覆盖身份(按 Id 全量写;盲写面:既有行保留存量行版本号,新键建档为 1)。 /// 行版本推进仅经条件写面( / ); @@ -57,7 +55,7 @@ public interface IOnlineIdentityStore Task AddOrUpdateIdentityAsync(OnlineIdentity identity, CancellationToken cancellationToken = default); /// - /// 唯一插入身份(按唯一键 (TenantId, AppId, Kind, Identifier);键已存在返回 false 且零写入)。 + /// 唯一插入身份(按唯一键 (Kind, Identifier);键已存在返回 false 且零写入)。 /// /// 并发同键插入恰一胜者:败者返回 false,不产生覆盖写;成功建档行版本为 1。 /// @@ -108,15 +106,14 @@ public interface IOnlineIdentityStore /// 取消令牌。 Task AddOrUpdatePlayerAsync(OnlinePlayerProfile player, CancellationToken cancellationToken = default); - /// 列出账号在指定 App/Server 归属下的玩家档案。 + /// 列出账号在指定区服归属下的玩家档案。 /// 游戏账号标识。 - /// 应用标识。 /// 区服标识。 /// 取消令牌。 /// 玩家档案列表(按创建时间升序)。 - Task> ListPlayersAsync(long gameAccountId, long appId, long serverId, CancellationToken cancellationToken = default); + Task> ListPlayersAsync(long gameAccountId, long serverId, CancellationToken cancellationToken = default); - /// 列出账号下全部玩家档案(不限 App/Server 归属;合并迁移用)。 + /// 列出账号下全部玩家档案(不限区服归属;合并迁移用)。 /// 游戏账号标识。 /// 取消令牌。 /// 玩家档案列表(按创建时间升序)。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/InMemoryOnlineIdentityStore.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/InMemoryOnlineIdentityStore.cs index adca84c74..8d739538d 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/InMemoryOnlineIdentityStore.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/InMemoryOnlineIdentityStore.cs @@ -27,6 +27,8 @@ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== +using GameFrameX.Capability.Online.Abstractions.Keys; + namespace GameFrameX.Capability.Online.Foundation.Identity; /// @@ -42,7 +44,7 @@ public sealed class InMemoryOnlineIdentityStore : IOnlineIdentityStore /// 全局读写锁(身份域低频写入,粗粒度锁足够)。 private readonly object _syncRoot = new(); - /// 身份表:键 = (TenantId, AppId, Kind, Identifier)。 + /// 身份表:键 = OnlineRowKey.Identity(Kind, Identifier)。 private readonly Dictionary _identities = new(); /// 账号表:键 = GameAccountId。 @@ -61,17 +63,15 @@ public sealed class InMemoryOnlineIdentityStore : IOnlineIdentityStore private long _playerIdSequence; /// 按唯一键查找身份。 - /// 租户标识。 - /// 应用标识。 /// 身份类型。 /// 身份标识串。 /// 取消令牌。 /// 身份实体;不存在返回 null。 - public Task FindIdentityAsync(long tenantId, long appId, OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default) + public Task FindIdentityAsync(OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default) { lock (_syncRoot) { - _identities.TryGetValue(BuildIdentityKey(tenantId, appId, kind, identifier), out var identity); + _identities.TryGetValue(OnlineRowKey.Identity((int)kind, identifier), out var identity); return Task.FromResult(identity); } } @@ -88,7 +88,7 @@ public Task AddOrUpdateIdentityAsync(OnlineIdentity identity, CancellationToken lock (_syncRoot) { - var key = BuildIdentityKey(identity.TenantId, identity.AppId, identity.Kind, identity.Identifier); + var key = OnlineRowKey.Identity((int)identity.Kind, identity.Identifier); if (_identities.TryGetValue(key, out var existing)) { // 盲写不改版本(版本推进仅经条件写面):保留存量版本号,防盲写绕过 CAS 判定。 @@ -118,7 +118,7 @@ public Task TryAddIdentityAsync(OnlineIdentity identity, CancellationToken lock (_syncRoot) { - var key = BuildIdentityKey(identity.TenantId, identity.AppId, identity.Kind, identity.Identifier); + var key = OnlineRowKey.Identity((int)identity.Kind, identity.Identifier); if (_identities.ContainsKey(key)) { return Task.FromResult(false); @@ -144,7 +144,7 @@ public Task TryUpdateIdentityIfRowVersionAsync(OnlineIdentity identity, lo lock (_syncRoot) { - var key = BuildIdentityKey(identity.TenantId, identity.AppId, identity.Kind, identity.Identifier); + var key = OnlineRowKey.Identity((int)identity.Kind, identity.Identifier); if (!_identities.TryGetValue(key, out var existing) || existing.RowVersion != expectedRowVersion) { return Task.FromResult(false); @@ -239,20 +239,19 @@ public Task AddOrUpdatePlayerAsync(OnlinePlayerProfile player, CancellationToken return Task.CompletedTask; } - /// 列出账号在指定 App/Server 归属下的玩家档案(按创建时间升序)。 + /// 列出账号在指定区服归属下的玩家档案(按创建时间升序)。 /// 游戏账号标识。 - /// 应用标识。 /// 区服标识。 /// 取消令牌。 /// 玩家档案列表。 - public Task> ListPlayersAsync(long gameAccountId, long appId, long serverId, CancellationToken cancellationToken = default) + public Task> ListPlayersAsync(long gameAccountId, long serverId, CancellationToken cancellationToken = default) { lock (_syncRoot) { var result = new List(); foreach (var player in _players.Values) { - if (player.GameAccountId == gameAccountId && player.AppId == appId && player.ServerId == serverId) + if (player.GameAccountId == gameAccountId && player.ServerId == serverId) { result.Add(player); } @@ -263,7 +262,7 @@ public Task> ListPlayersAsync(long gameAccoun } } - /// 列出账号下全部玩家档案(不限 App/Server 归属;合并迁移用,按创建时间升序)。 + /// 列出账号下全部玩家档案(不限区服归属;合并迁移用,按创建时间升序)。 /// 游戏账号标识。 /// 取消令牌。 /// 玩家档案列表。 @@ -294,7 +293,7 @@ public Task FindDeviceAsync(long gameAccountId, string devic { lock (_syncRoot) { - _devices.TryGetValue(BuildDeviceKey(gameAccountId, deviceIdentifier), out var device); + _devices.TryGetValue(OnlineRowKey.PlayerDevice(gameAccountId, deviceIdentifier), out var device); return Task.FromResult(device); } } @@ -311,7 +310,7 @@ public Task AddOrUpdateDeviceAsync(OnlinePlayerDevice device, CancellationToken lock (_syncRoot) { - _devices[BuildDeviceKey(device.GameAccountId, device.DeviceIdentifier)] = device; + _devices[OnlineRowKey.PlayerDevice(device.GameAccountId, device.DeviceIdentifier)] = device; } return Task.CompletedTask; @@ -332,24 +331,4 @@ public Task NextPlayerIdAsync(CancellationToken cancellationToken = defaul { return Task.FromResult(Interlocked.Increment(ref _playerIdSequence)); } - - /// 构造身份唯一键。 - /// 租户标识。 - /// 应用标识。 - /// 身份类型。 - /// 身份标识串。 - /// 复合键字符串。 - private static string BuildIdentityKey(long tenantId, long appId, OnlineIdentityKind kind, string identifier) - { - return tenantId + ":" + appId + ":" + (int)kind + ":" + identifier; - } - - /// 构造设备唯一键。 - /// 游戏账号标识。 - /// 设备唯一标识串。 - /// 复合键字符串。 - private static string BuildDeviceKey(long gameAccountId, string deviceIdentifier) - { - return gameAccountId + ":" + deviceIdentifier; - } -} \ No newline at end of file +} diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineGameAccount.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineGameAccount.cs index 5e28208e7..d6317afd6 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineGameAccount.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineGameAccount.cs @@ -30,10 +30,10 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; /// -/// 游戏账号实体(Tenant → App → Identity / GameAccount → Player 层级中的账号层)。 +/// 游戏账号实体(Identity / GameAccount → Player 层级中的账号层)。 /// /// 维护约束:账号是身份与玩家的归属聚合根;一个 GameAccount 可拥有多个 Player, -/// 但每个 Player 必须有明确的 App/Server 归属;合并(Merged)与注销(Deactivated) +/// 但每个 Player 必须有明确的 Server 归属;合并(Merged)与注销(Deactivated) /// 为显式操作,注销后的数据保留期由 承载, /// 保留期内不得物理删除(数据保留红线)。 /// @@ -45,15 +45,6 @@ public sealed class OnlineGameAccount /// public long Id { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } /// /// 获取或设置账号生命周期状态。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentity.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentity.cs index c5085b3ad..8c031d9c5 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentity.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentity.cs @@ -30,9 +30,9 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; /// -/// 外源身份实体(邮箱/设备/渠道/第三方身份,绑定明确的 TenantId + AppId)。 +/// 外源身份实体(邮箱/设备/渠道/第三方身份,归玩家全局所有)。 /// -/// 维护约束:唯一性键 = (TenantId, AppId, Kind, Identifier),四元组重复即同一身份; +/// 维护约束:唯一性键 = (Kind, Identifier),二元组重复即同一身份; /// 凭证材料(口令散列、第三方 token)由装配层凭据组件持有,本实体只承载身份指向; /// 解绑后 置位,同一 Identifier 可被重新绑定(换绑显式操作)。 /// @@ -44,15 +44,6 @@ public sealed class OnlineIdentity /// public string Id { get; set; } - /// - /// 获取或设置租户标识(身份必须绑定明确租户)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识(身份必须绑定明确应用)。 - /// - public long AppId { get; set; } /// /// 获取或设置身份类型。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityKind.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityKind.cs index 4a4244f7f..1fb033fb6 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityKind.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityKind.cs @@ -30,7 +30,7 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; /// -/// 外源身份类型(外部身份必须绑定明确的 TenantId + AppId,按类型分道检索)。 +/// 外源身份类型(按类型分道检索)。 /// /// 维护约束:同一 Identifier 在不同 下视为不同身份; /// Device 类身份只用于识别设备与换绑判定,不得直接充当 PlayerId(身份模型红线)。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityRebindAuthorization.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityRebindAuthorization.cs index b1221b9b8..9e02af705 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityRebindAuthorization.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityRebindAuthorization.cs @@ -51,15 +51,6 @@ public sealed class OnlineIdentityRebindAuthorization /// public string TicketId { get; set; } - /// - /// 获取或设置租户标识(票据作用域:必须与被改绑身份一致)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识(票据作用域:必须与被改绑身份一致)。 - /// - public long AppId { get; set; } /// /// 获取或设置身份类型(票据作用域:必须与被改绑身份一致)。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityService.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityService.cs index 710f15df4..da4c22ff4 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityService.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineIdentityService.cs @@ -84,7 +84,7 @@ public OnlineIdentityService(IOnlineIdentityStore store, OnlineAuditService audi } /// - /// 解析一次登录:命中身份或自动注册,选定 App/Server 归属玩家,校验设备状态。 + /// 解析一次登录:命中身份或自动注册,选定区服归属玩家,校验设备状态。 /// /// 登录解析请求。 /// 取消令牌。 @@ -96,8 +96,6 @@ public async Task> ResolveLoginAsync(OnlineL throw new ArgumentNullException(nameof(request)); } - var tenantId = request.TenantId; - var appId = request.AppId; var serverId = request.ServerId; var kind = request.Kind; var identifier = request.Identifier; @@ -110,14 +108,14 @@ public async Task> ResolveLoginAsync(OnlineL } var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var identity = await _store.FindIdentityAsync(tenantId, appId, kind, identifier, cancellationToken); + var identity = await _store.FindIdentityAsync(kind, identifier, cancellationToken); OnlineGameAccount account; OnlinePlayerProfile player; if (identity == null) { // 新身份自动注册:账号 + 身份 + 首个玩家一次性建立(服务端生成,客户端不得拼接)。 - (identity, account, player) = await RegisterIdentityAsync(tenantId, appId, serverId, kind, identifier, playerName, now, cancellationToken); + (identity, account, player) = await RegisterIdentityAsync(serverId, kind, identifier, playerName, now, cancellationToken); } else if (identity.UnboundAtTime > 0) { @@ -130,7 +128,7 @@ public async Task> ResolveLoginAsync(OnlineL account = accountResult.Data; identity = await ReviveUnboundIdentityAsync(identity, account, now, cancellationToken); - player = await ResolvePlayerAsync(account, tenantId, appId, serverId, playerName, now, cancellationToken); + player = await ResolvePlayerAsync(account, serverId, playerName, now, cancellationToken); } else { @@ -141,7 +139,7 @@ public async Task> ResolveLoginAsync(OnlineL } account = accountResult.Data; - player = await ResolvePlayerAsync(account, tenantId, appId, serverId, playerName, now, cancellationToken); + player = await ResolvePlayerAsync(account, serverId, playerName, now, cancellationToken); } // 设备识别与换绑策略校验:已失效设备(换绑后旧设备)按策略拒绝登录。 @@ -160,8 +158,6 @@ public async Task> ResolveLoginAsync(OnlineL /// /// 新身份自动注册(红线):账号、身份与首个玩家由服务端一次性生成并落库,客户端不得拼接身份关系。 /// - /// 租户标识。 - /// 应用标识。 /// 区服标识。 /// 身份类型。 /// 身份标识串。 @@ -169,14 +165,12 @@ public async Task> ResolveLoginAsync(OnlineL /// 当前 Unix 毫秒时间。 /// 取消令牌。 /// 身份/账号/玩家三元组(均已写入存储)。 - private async Task<(OnlineIdentity Identity, OnlineGameAccount Account, OnlinePlayerProfile Player)> RegisterIdentityAsync(long tenantId, long appId, long serverId, OnlineIdentityKind kind, string identifier, string playerName, long now, CancellationToken cancellationToken) + private async Task<(OnlineIdentity Identity, OnlineGameAccount Account, OnlinePlayerProfile Player)> RegisterIdentityAsync(long serverId, OnlineIdentityKind kind, string identifier, string playerName, long now, CancellationToken cancellationToken) { var accountId = await _store.NextAccountIdAsync(cancellationToken); var account = new OnlineGameAccount { Id = accountId, - TenantId = tenantId, - AppId = appId, Status = OnlineGameAccountStatus.Active, CreatedAtTime = now, UpdatedAtTime = now, @@ -186,8 +180,6 @@ public async Task> ResolveLoginAsync(OnlineL { Id = playerId, GameAccountId = accountId, - TenantId = tenantId, - AppId = appId, ServerId = serverId, Name = string.IsNullOrEmpty(playerName) ? "Player-" + playerId : playerName, CreatedAtTime = now, @@ -196,8 +188,6 @@ public async Task> ResolveLoginAsync(OnlineL var identity = new OnlineIdentity { Id = "ident-" + Guid.NewGuid().ToString("N"), - TenantId = tenantId, - AppId = appId, Kind = kind, Identifier = identifier, GameAccountId = accountId, @@ -273,19 +263,17 @@ private async Task ReviveUnboundIdentityAsync(OnlineIdentity ide } /// - /// 解析账号在指定 App/Server 下的归属玩家:命中既有玩家则复用,否则新建并落库。 + /// 解析账号在指定区服下的归属玩家:命中既有玩家则复用,否则新建并落库。 /// /// 已解析的可登录账号。 - /// 租户标识。 - /// 应用标识。 /// 区服标识。 /// 新建玩家显示名(可空,缺省按玩家标识生成)。 /// 当前 Unix 毫秒时间。 /// 取消令牌。 /// 归属玩家实例。 - private async Task ResolvePlayerAsync(OnlineGameAccount account, long tenantId, long appId, long serverId, string playerName, long now, CancellationToken cancellationToken) + private async Task ResolvePlayerAsync(OnlineGameAccount account, long serverId, string playerName, long now, CancellationToken cancellationToken) { - var players = await _store.ListPlayersAsync(account.Id, appId, serverId, cancellationToken); + var players = await _store.ListPlayersAsync(account.Id, serverId, cancellationToken); if (players.Count > 0) { return players[0]; @@ -296,8 +284,6 @@ private async Task ResolvePlayerAsync(OnlineGameAccount acc { Id = playerId, GameAccountId = account.Id, - TenantId = tenantId, - AppId = appId, ServerId = serverId, Name = string.IsNullOrEmpty(playerName) ? "Player-" + playerId : playerName, CreatedAtTime = now, @@ -348,15 +334,13 @@ private async Task> TouchDeviceAsync(OnlineGameAccount accoun /// 为账号绑定外源身份(显式操作)。三分支:全新身份唯一插入;绑定中身份同账号幂等放行、他账号拒绝; /// 已解绑身份归原账号——原账号重绑自己放行,跨账号改绑必须携带原账号签发的一次性授权票据。 /// - /// 租户标识。 - /// 应用标识。 /// 目标游戏账号。 /// 身份类型。 /// 身份标识串。 /// 跨账号改绑授权票据秘密串(仅已解绑身份且原账号非本账号时必需)。 /// 取消令牌。 /// 成功返回 true;失败返回段位化错误码(并发冲突 )。 - public async Task> BindIdentityAsync(long tenantId, long appId, long gameAccountId, OnlineIdentityKind kind, string identifier, string rebindAuthorizationTicket = null, CancellationToken cancellationToken = default) + public async Task> BindIdentityAsync(long gameAccountId, OnlineIdentityKind kind, string identifier, string rebindAuthorizationTicket = null, CancellationToken cancellationToken = default) { if (!Enum.IsDefined(typeof(OnlineIdentityKind), kind) || string.IsNullOrEmpty(identifier)) { @@ -370,15 +354,13 @@ public async Task> BindIdentityAsync(long tenantId, long appI } var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var existing = await _store.FindIdentityAsync(tenantId, appId, kind, identifier, cancellationToken); + var existing = await _store.FindIdentityAsync(kind, identifier, cancellationToken); if (existing == null) { // 全新身份:上游完成第三方凭据校验后直接绑定;唯一插入保证并发恰一胜者(败者零写入)。 var identity = new OnlineIdentity { Id = "ident-" + Guid.NewGuid().ToString("N"), - TenantId = tenantId, - AppId = appId, Kind = kind, Identifier = identifier, GameAccountId = gameAccountId, @@ -429,7 +411,7 @@ private async Task> BindUnboundIdentityCrossAccountAsync(Onli return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "原账号不可用,跨账号改绑须走客服或管理后台流程。"); } - var authorizationResult = TryConsumeRebindAuthorization(rebindAuthorizationTicket, existing.TenantId, existing.AppId, existing.Kind, existing.Identifier, existing.GameAccountId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + var authorizationResult = TryConsumeRebindAuthorization(rebindAuthorizationTicket, existing.Kind, existing.Identifier, existing.GameAccountId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); if (!authorizationResult.IsSuccess) { return OnlineResult.Fail(authorizationResult.Code, authorizationResult.Message); @@ -448,14 +430,12 @@ private async Task> BindUnboundIdentityCrossAccountAsync(Onli /// /// 签发已解绑身份跨账号改绑的一次性授权票据(由原账号已登录会话调用;短有效期、消费式单次)。 /// - /// 租户标识。 - /// 应用标识。 /// 签发账号(原账号;身份须归属该账号,解绑前后均可)。 /// 身份类型。 /// 身份标识串。 /// 取消令牌。 /// 授权票据( 为秘密串,交由新账号持有方使用);失败返回段位化错误码。 - public async Task> IssueIdentityRebindAuthorizationAsync(long tenantId, long appId, long issuerGameAccountId, OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default) + public async Task> IssueIdentityRebindAuthorizationAsync(long issuerGameAccountId, OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default) { if (!Enum.IsDefined(typeof(OnlineIdentityKind), kind) || string.IsNullOrEmpty(identifier)) { @@ -473,7 +453,7 @@ public async Task> IssueIdentity return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "仅活跃账号可签发身份改绑授权。"); } - var identity = await _store.FindIdentityAsync(tenantId, appId, kind, identifier, cancellationToken); + var identity = await _store.FindIdentityAsync(kind, identifier, cancellationToken); if (identity == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "身份不存在。"); @@ -490,8 +470,6 @@ public async Task> IssueIdentity { Code = "rebind-" + Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), TicketId = "rebind-auth-" + Guid.NewGuid().ToString("N"), - TenantId = tenantId, - AppId = appId, Kind = kind, Identifier = identifier, IssuerGameAccountId = issuerGameAccountId, @@ -514,8 +492,6 @@ private async Task TryRebindIdentityCoreAsync(OnlineIdentity existing, lon var rebound = new OnlineIdentity { Id = existing.Id, - TenantId = existing.TenantId, - AppId = existing.AppId, Kind = existing.Kind, Identifier = existing.Identifier, GameAccountId = gameAccountId, @@ -527,17 +503,15 @@ private async Task TryRebindIdentityCoreAsync(OnlineIdentity existing, lon } /// - /// 消费式校验改绑授权票据(验证即移除,无论后续改绑是否成功):作用域四元组与签发账号必须与被改绑身份一致。 + /// 消费式校验改绑授权票据(验证即移除,无论后续改绑是否成功):作用域二元组与签发账号必须与被改绑身份一致。 /// /// 票据秘密串。 - /// 租户标识。 - /// 应用标识。 /// 身份类型。 /// 身份标识串。 /// 原账号标识。 /// 当前 Unix 毫秒时间。 /// 校验通过返回票据实体;失败返回段位化错误码。 - private OnlineResult TryConsumeRebindAuthorization(string ticketCode, long tenantId, long appId, OnlineIdentityKind kind, string identifier, long issuerGameAccountId, long now) + private OnlineResult TryConsumeRebindAuthorization(string ticketCode, OnlineIdentityKind kind, string identifier, long issuerGameAccountId, long now) { if (string.IsNullOrEmpty(ticketCode)) { @@ -549,7 +523,7 @@ private OnlineResult TryConsumeRebindAuthoriz return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "授权票据无效或已使用。"); } - if (authorization.TenantId != tenantId || authorization.AppId != appId || authorization.Kind != kind || authorization.Identifier != identifier || authorization.IssuerGameAccountId != issuerGameAccountId) + if (authorization.Kind != kind || authorization.Identifier != identifier || authorization.IssuerGameAccountId != issuerGameAccountId) { return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "授权票据与被改绑身份不匹配。"); } @@ -593,8 +567,6 @@ private async Task WriteRebindAuditAsync(OnlineIdentity original, long newGameAc EventId = "identity-rebind-" + Guid.NewGuid().ToString("N"), EventType = "online.identity.rebound", OccurredTime = now, - TenantId = original.TenantId, - AppId = original.AppId, ServerId = 0, PlayerId = 0, OperatorId = "game-account-" + original.GameAccountId, @@ -617,15 +589,13 @@ private async Task WriteRebindAuditAsync(OnlineIdentity original, long newGameAc /// /// 解绑外源身份(显式操作;账号必须保留至少一个绑定身份,否则拒绝)。 /// - /// 租户标识。 - /// 应用标识。 /// 身份类型。 /// 身份标识串。 /// 取消令牌。 /// 成功返回 true;失败返回段位化错误码。 - public async Task> UnbindIdentityAsync(long tenantId, long appId, OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default) + public async Task> UnbindIdentityAsync(OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default) { - var identity = await _store.FindIdentityAsync(tenantId, appId, kind, identifier, cancellationToken); + var identity = await _store.FindIdentityAsync(kind, identifier, cancellationToken); if (identity == null || identity.UnboundAtTime > 0) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "身份不存在或已解绑。"); diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineLoginRequest.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineLoginRequest.cs index c4deaff77..dede6c3ac 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineLoginRequest.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineLoginRequest.cs @@ -39,17 +39,6 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; /// public sealed class OnlineLoginRequest { - /// - /// 获取或设置租户标识。 - /// - /// Gets or sets the tenant id. - public long TenantId { get; init; } - - /// - /// 获取或设置应用标识。 - /// - /// Gets or sets the app id. - public long AppId { get; init; } /// /// 获取或设置区服标识。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineLoginResolution.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineLoginResolution.cs index 01cb880ef..7a97ae8bc 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineLoginResolution.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineLoginResolution.cs @@ -49,7 +49,7 @@ public sealed class OnlineLoginResolution public OnlineGameAccount GameAccount { get; } /// - /// 获取本次登录选定的玩家档案(App/Server 归属明确)。 + /// 获取本次登录选定的玩家档案(区服归属明确)。 /// public OnlinePlayerProfile Player { get; } diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineMultiDevicePolicy.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineMultiDevicePolicy.cs index 83ba6ceb7..9ebac741d 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineMultiDevicePolicy.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlineMultiDevicePolicy.cs @@ -32,9 +32,9 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; /// /// 同一账号多端登录策略(策略选项写入契约,默认策略待产品确认,代码可配不锁死)。 /// -/// 维护约束:策略按「租户 + App + 玩家」维度生效;切换策略只影响新登录会话, +/// 维护约束:策略按玩家维度生效;切换策略只影响新登录会话, /// 既有会话按签发时策略处理;在线计数随策略语义为 1 或 N。 -/// 本仓默认 (顶号),装配层可按租户覆盖。 +/// 本仓默认 (顶号),装配层可覆盖。 /// /// public enum OnlineMultiDevicePolicy diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlinePlayerContext.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlinePlayerContext.cs index 9f728440e..46fc97817 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlinePlayerContext.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlinePlayerContext.cs @@ -33,7 +33,7 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; using GameFrameX.Capability.Online.Abstractions.Scope; /// -/// 统一玩家上下文(PlayerId + AppId + ServerId + SessionId,后续模块不再各自解析身份)。 +/// 统一玩家上下文(PlayerId + ServerId + SessionId,后续模块不再各自解析身份)。 /// /// 维护约束:登录成功后由服务端生成,客户端不得自行拼接身份关系; /// 会话进入终态后本上下文即失效,调用方不得缓存复用; @@ -42,15 +42,6 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; /// public sealed class OnlinePlayerContext { - /// - /// 获取租户标识。 - /// - public long TenantId { get; } - - /// - /// 获取应用标识。 - /// - public long AppId { get; } /// /// 获取区服标识。 @@ -58,7 +49,7 @@ public sealed class OnlinePlayerContext public long ServerId { get; } /// - /// 获取玩家标识(GameAccount 下属、App/Server 归属明确)。 + /// 获取玩家标识(GameAccount 下属、区服归属明确)。 /// public long PlayerId { get; } @@ -75,16 +66,12 @@ public sealed class OnlinePlayerContext /// /// 初始化 。 /// - /// 租户标识。 - /// 应用标识。 /// 区服标识。 /// 玩家标识。 /// 游戏账号标识。 /// 会话标识。 - public OnlinePlayerContext(long tenantId, long appId, long serverId, long playerId, long gameAccountId, string sessionId) + public OnlinePlayerContext(long serverId, long playerId, long gameAccountId, string sessionId) { - TenantId = tenantId; - AppId = appId; ServerId = serverId; PlayerId = playerId; GameAccountId = gameAccountId; @@ -113,6 +100,6 @@ public static OnlinePlayerContext FromScope(OnlineScope scope, long gameAccountI throw new ArgumentException(LocalizationService.GetString(Localization.Keys.Online.Identity.ScopeMissingPlayerId), nameof(scope)); } - return new OnlinePlayerContext(scope.TenantId, scope.AppId, scope.ServerId, scope.PlayerId, gameAccountId, sessionId); + return new OnlinePlayerContext(scope.ServerId, scope.PlayerId, gameAccountId, sessionId); } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlinePlayerProfile.cs b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlinePlayerProfile.cs index 6c6c8ca02..2be00c1f7 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlinePlayerProfile.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Identity/OnlinePlayerProfile.cs @@ -32,7 +32,7 @@ namespace GameFrameX.Capability.Online.Foundation.Identity; /// /// 玩家档案实体(GameAccount 下属的 Server/玩法角色层,区别于 User/GameAccount/Device/Identity/Session)。 /// -/// 维护约束:每个 Player 必须有明确的 App/Server 归属((GameAccountId, AppId, ServerId) 下命名不重); +/// 维护约束:每个 Player 必须有明确的区服归属((GameAccountId, ServerId) 下命名不重); /// 设备标识只能用于识别设备,不得直接充当 ; /// 玩家核心属性、背包、钱包走强类型 CacheState + Actor(既定边界约束),本实体只承载身份层档案字段。 /// @@ -49,15 +49,6 @@ public sealed class OnlinePlayerProfile /// public long GameAccountId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识(玩家归属 App)。 - /// - public long AppId { get; set; } /// /// 获取或设置区服标识(玩家归属 Server)。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/OnlineFoundationCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Foundation/OnlineFoundationCapabilityModule.cs index 21bbd7ee3..ea3286529 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/OnlineFoundationCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/OnlineFoundationCapabilityModule.cs @@ -155,10 +155,10 @@ public void Register(CapabilityRegistrationContext context) context.AddService(new OnlineSocialPresenceProbe(_presence)); context.AddService(new OnlinePartyPresenceProbe(_presence)); - // 清扫滴答 job(归属地基域;作用域三元组经族预置的授权作用域解析——壳时代 host.AuthorizedScope 等价)。 + // 清扫滴答 job(归属地基域)。 context.AddTickJob("presence-timeout-sweep", async ct => { - await _presence.SweepTimeoutsAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _presence.SweepTimeoutsAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); context.AddTickJob("session-token-expiry-sweep", ct => _tokens.SweepExpiredAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct)); diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Presence/IOnlinePresenceStore.cs b/Capability/GameFrameX.Capability.Online.Foundation/Presence/IOnlinePresenceStore.cs index 717db71ee..8953048af 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Presence/IOnlinePresenceStore.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Presence/IOnlinePresenceStore.cs @@ -32,54 +32,44 @@ namespace GameFrameX.Capability.Online.Foundation.Presence; /// /// 在线状态存储接口(Presence 事实源的持久化契约)。 /// -/// 维护约束:键 = (TenantId, AppId, PlayerId)——玩家维度唯一(多端并存时以会话域为准,Presence 表达玩家事实); -/// 无记录即 Offline(RemoveAsync 即下线);查询按 (TenantId, AppId) 列举,在线计数在服务层过滤状态。 +/// 维护约束:键 = PlayerId——玩家维度唯一(多端并存时以会话域为准,Presence 表达玩家事实); +/// 无记录即 Offline(RemoveAsync 即下线);全量列举供在线计数,在线计数在服务层过滤状态。 /// /// public interface IOnlinePresenceStore { - /// 写入或覆盖在线状态记录(按 (TenantId, AppId, PlayerId) 全量写)。 + /// 写入或覆盖在线状态记录(按 PlayerId 全量写)。 /// 在线状态记录。 /// 取消令牌。 Task SetAsync(OnlinePresenceRecord record, CancellationToken cancellationToken = default); - /// 按 (TenantId, AppId, PlayerId) 查找在线状态记录。 - /// 租户标识。 - /// 应用标识。 + /// 按 PlayerId 查找在线状态记录。 /// 玩家标识。 /// 取消令牌。 /// 在线状态记录;无记录返回 null(即 Offline)。 - Task FindAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task FindAsync(long playerId, CancellationToken cancellationToken = default); /// 移除在线状态记录(即 Offline)。 - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 取消令牌。 - Task RemoveAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task RemoveAsync(long playerId, CancellationToken cancellationToken = default); - /// 列出 (TenantId, AppId) 下全部在线状态记录(在线计数与 Admin 查询输入)。 - /// 租户标识。 - /// 应用标识。 + /// 列出全部在线状态记录(在线计数与 Admin 查询输入)。 /// 取消令牌。 /// 在线状态记录列表。 - Task> ListByAppAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListAllAsync(CancellationToken cancellationToken = default); - /// 统计作用域 (TenantId, AppId, ServerId) 内的在线玩家数(聚合谓词下推:State 为 Blocked 的记录不计入,与在线总览口径一致)。 - /// 租户标识。 - /// 应用标识。 + /// 统计区服内的在线玩家数(聚合谓词下推:State 为 Blocked 的记录不计入,与在线总览口径一致)。 /// 区服标识。 /// 取消令牌。 /// 在线玩家数。 - Task CountOnlineByServerAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default); + Task CountOnlineByServerAsync(long serverId, CancellationToken cancellationToken = default); /// 列出已到期的清扫候选(Reconnecting 超重连窗 / Online 超空闲阈值),按到期时间升序取头部。 - /// 租户标识。 - /// 应用标识。 /// 判定基准时刻(Unix 毫秒)。 /// 空闲判定阈值(毫秒;Online 态心跳早于该阈值即到期)。 /// 最多返回条数(批量清扫的批次大小)。 /// 取消令牌。 /// 到期候选记录快照(服务层仍须逐条复核状态与到期条件);无候选返回空列表。 - Task> ListSweepCandidatesAsync(long tenantId, long appId, long nowUnixMilliseconds, long idleTimeoutMilliseconds, int maxCount, CancellationToken cancellationToken = default); + Task> ListSweepCandidatesAsync(long nowUnixMilliseconds, long idleTimeoutMilliseconds, int maxCount, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Presence/InMemoryOnlinePresenceStore.cs b/Capability/GameFrameX.Capability.Online.Foundation/Presence/InMemoryOnlinePresenceStore.cs index d7ac3ef8e..a3ec5fe59 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Presence/InMemoryOnlinePresenceStore.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Presence/InMemoryOnlinePresenceStore.cs @@ -41,7 +41,7 @@ public sealed class InMemoryOnlinePresenceStore : IOnlinePresenceStore /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 在线状态表:键 = (TenantId, AppId, PlayerId)。 + /// 在线状态表:键 = PlayerId。 private readonly Dictionary _records = new(); /// 清扫索引:Reconnecting 记录按重连截止时刻有序(索引项含记录键保证唯一)。 @@ -65,7 +65,7 @@ public Task SetAsync(OnlinePresenceRecord record, CancellationToken cancellation lock (_syncRoot) { - var recordKey = BuildKey(record.TenantId, record.AppId, record.PlayerId); + var recordKey = BuildKey(record.PlayerId); _records[recordKey] = record; RebuildSweepIndexEntry(recordKey, record); } @@ -73,73 +73,62 @@ public Task SetAsync(OnlinePresenceRecord record, CancellationToken cancellation return Task.CompletedTask; } - /// 按 (TenantId, AppId, PlayerId) 查找在线状态记录。 - /// 租户标识。 - /// 应用标识。 + /// 按 PlayerId 查找在线状态记录。 /// 玩家标识。 /// 取消令牌。 /// 在线状态记录;无记录返回 null。 - public Task FindAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task FindAsync(long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - _records.TryGetValue(BuildKey(tenantId, appId, playerId), out var record); + _records.TryGetValue(BuildKey(playerId), out var record); return Task.FromResult(record); } } /// 移除在线状态记录(即 Offline)。 - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 取消令牌。 - public Task RemoveAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task RemoveAsync(long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - var recordKey = BuildKey(tenantId, appId, playerId); + var recordKey = BuildKey(playerId); _records.Remove(recordKey); RemoveSweepIndexEntry(recordKey); } return Task.CompletedTask; } - /// 列出 (TenantId, AppId) 下全部在线状态记录。 - /// 租户标识。 - /// 应用标识。 + /// 列出全部在线状态记录。 /// 取消令牌。 /// 在线状态记录列表。 - public Task> ListByAppAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAllAsync(CancellationToken cancellationToken = default) { lock (_syncRoot) { var result = new List(); foreach (var record in _records.Values) { - if (record.TenantId == tenantId && record.AppId == appId) - { - result.Add(record); - } + result.Add(record); } return Task.FromResult>(result); } } - /// 统计作用域 (TenantId, AppId, ServerId) 内的在线玩家数(Blocked 不计入;表内扫描不产出实体副本)。 - /// 租户标识。 - /// 应用标识。 + /// 统计区服内的在线玩家数(Blocked 不计入;表内扫描不产出实体副本)。 /// 区服标识。 /// 取消令牌。 /// 在线玩家数。 - public Task CountOnlineByServerAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public Task CountOnlineByServerAsync(long serverId, CancellationToken cancellationToken = default) { lock (_syncRoot) { var count = 0; foreach (var record in _records.Values) { - if (record.TenantId == tenantId && record.AppId == appId && record.ServerId == serverId && record.State != OnlinePresenceState.Blocked) + if (record.ServerId == serverId && record.State != OnlinePresenceState.Blocked) { count++; } @@ -150,14 +139,12 @@ public Task CountOnlineByServerAsync(long tenantId, long appId, long server } /// 列出已到期的清扫候选,按到期时间升序取头部(两类到期合并快照返回)。 - /// 租户标识。 - /// 应用标识。 /// 判定基准时刻(Unix 毫秒)。 /// 空闲判定阈值(毫秒)。 /// 最多返回条数。 /// 取消令牌。 /// 到期候选记录快照;无候选返回空列表。 - public Task> ListSweepCandidatesAsync(long tenantId, long appId, long nowUnixMilliseconds, long idleTimeoutMilliseconds, int maxCount, CancellationToken cancellationToken = default) + public Task> ListSweepCandidatesAsync(long nowUnixMilliseconds, long idleTimeoutMilliseconds, int maxCount, CancellationToken cancellationToken = default) { var result = new List(maxCount); lock (_syncRoot) @@ -174,7 +161,7 @@ public Task> ListSweepCandidatesAsync(long t break; } - AppendSweepCandidate(result, tenantId, appId, entry.RecordKey); + AppendSweepCandidate(result, entry.RecordKey); } var heartbeatDeadline = nowUnixMilliseconds - idleTimeoutMilliseconds; @@ -185,22 +172,20 @@ public Task> ListSweepCandidatesAsync(long t break; } - AppendSweepCandidate(result, tenantId, appId, entry.RecordKey); + AppendSweepCandidate(result, entry.RecordKey); } } return Task.FromResult>(result); } - /// 向候选列表追加索引项对应的记录(记录不存在或租户/应用不匹配则跳过)。 + /// 向候选列表追加索引项对应的记录。 /// 候选输出列表。 - /// 租户标识。 - /// 应用标识。 /// 记录键。 - private void AppendSweepCandidate(List result, long tenantId, long appId, string recordKey) + private void AppendSweepCandidate(List result, string recordKey) { OnlinePresenceRecord record; - if (!_records.TryGetValue(recordKey, out record) || record.TenantId != tenantId || record.AppId != appId) + if (!_records.TryGetValue(recordKey, out record)) { return; } @@ -242,12 +227,10 @@ private void RemoveSweepIndexEntry(string recordKey) } /// 构造在线状态记录键。 - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 - /// 复合键字符串。 - private static string BuildKey(long tenantId, long appId, long playerId) + /// 玩家标识字符串键。 + private static string BuildKey(long playerId) { - return tenantId + ":" + appId + ":" + playerId; + return playerId.ToString(System.Globalization.CultureInfo.InvariantCulture); } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePartyPresenceProbe.cs b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePartyPresenceProbe.cs index 32b9a72c2..04da13ad6 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePartyPresenceProbe.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePartyPresenceProbe.cs @@ -61,21 +61,19 @@ public OnlinePartyPresenceProbe(OnlinePresenceService presence) } /// - /// 判定队伍成员是否在线:以租户、应用与成员玩家构造作用域(服务器位为 0)查询在线状态事实源;查询成功且状态既非离线也非封禁时返回 true,查询失败一律按离线返回 false。 + /// 判定队伍成员是否在线:以成员玩家构造作用域(服务器位为 0)查询在线状态事实源;查询成功且状态既非离线也非封禁时返回 true,查询失败一律按离线返回 false。 /// /// - /// Builds a scope from tenant, app and player (server id 0) and reads the presence service; returns true only when the + /// Builds a scope from the player (server id 0) and reads the presence service; returns true only when the /// lookup succeeds and the state is neither nor . /// A failed lookup is treated as offline. /// - /// 租户标识 / Tenant id - /// 应用标识 / App id /// 队伍成员玩家标识 / Party member player id /// 取消令牌 / Cancellation token /// 成员是否在线 / Whether the member is online - public async Task IsOnlineAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public async Task IsOnlineAsync(long playerId, CancellationToken cancellationToken = default) { - var scope = new OnlineScope(tenantId, appId, 0, playerId); + var scope = new OnlineScope(0, playerId); var result = await _presence.GetAsync(scope, cancellationToken).ConfigureAwait(false); return result.IsSuccess && result.Data != OnlinePresenceState.Offline diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceEvents.cs b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceEvents.cs index 311324573..a8ae2897f 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceEvents.cs @@ -50,8 +50,6 @@ public static class OnlinePresenceEvents /// /// 构造在线状态变更事件。 /// - /// 租户标识。 - /// 应用标识。 /// 区服标识。 /// 玩家标识。 /// 关联会话标识。 @@ -60,7 +58,7 @@ public static class OnlinePresenceEvents /// 变更原因描述。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent Create(long tenantId, long appId, long serverId, long playerId, string sessionId, string fromState, string toState, string reason, string correlationId = null) + public static OnlineEvent Create(long serverId, long playerId, string sessionId, string fromState, string toState, string reason, string correlationId = null) { var payload = new PresenceEventPayload { @@ -84,8 +82,6 @@ public static OnlineEvent Create(long tenantId, long appId, long serverId, long EventType = PresenceChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = playerId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceRecord.cs b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceRecord.cs index ef6d2144d..ea456e523 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceRecord.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceRecord.cs @@ -33,21 +33,12 @@ namespace GameFrameX.Capability.Online.Foundation.Presence; /// 在线状态记录(玩家在线事实源;无记录即 Offline)。 /// /// 维护约束:记录仅玩家会话可建立(Admin 管理员连接结构性排除); -/// 键 = (TenantId, AppId, PlayerId);状态写入前必须经 判定; +/// 键 = PlayerId;状态写入前必须经 判定; /// 清理边界——Reconnecting 超窗或会话关闭即移除记录(Offline = 无记录),不得遗留永久 Reconnecting。 /// /// public sealed class OnlinePresenceRecord { - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } /// /// 获取或设置区服标识(事件归属透出用;Presence 键不含区服位)。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceService.cs b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceService.cs index c081450fb..49f260e67 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceService.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlinePresenceService.cs @@ -96,7 +96,7 @@ public async Task> SetOnlineAsync(OnlineScope } var now = Now(); - var existing = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var existing = await _store.FindAsync(scope.PlayerId, cancellationToken); if (existing != null && existing.State == OnlinePresenceState.Online && existing.SessionId == sessionId) { existing.LastHeartbeatAtTime = now; @@ -112,8 +112,6 @@ public async Task> SetOnlineAsync(OnlineScope var record = new OnlinePresenceRecord { - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, PlayerId = scope.PlayerId, SessionId = sessionId ?? string.Empty, @@ -143,7 +141,7 @@ public async Task> HeartbeatAsync(OnlineScope return failure; } - var record = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var record = await _store.FindAsync(scope.PlayerId, cancellationToken); if (record == null) { return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "玩家不在线,无心跳语义"); @@ -181,7 +179,7 @@ public async Task> MarkDisconnectedAsync(Onlin return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "重连窗口必须为正数(秒)"); } - var record = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var record = await _store.FindAsync(scope.PlayerId, cancellationToken); if (record == null) { return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "玩家不在线,无断线语义"); @@ -219,7 +217,7 @@ public async Task> MarkReconnectedAsync(Online return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "重连落点仅允许 Online / InMatch"); } - var record = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var record = await _store.FindAsync(scope.PlayerId, cancellationToken); if (record == null) { return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "玩家不在线,无重连语义"); @@ -245,7 +243,7 @@ public async Task> MarkClosedAsync(OnlineScope scope, string return OnlineResult.Fail(failure.Code, failure.Message); } - var record = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var record = await _store.FindAsync(scope.PlayerId, cancellationToken); if (record == null) { return OnlineResult.Ok(true); @@ -256,7 +254,7 @@ public async Task> MarkClosedAsync(OnlineScope scope, string return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "风控限制中的玩家不受会话关闭影响,须先解除限制"); } - await _store.RemoveAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + await _store.RemoveAsync(scope.PlayerId, cancellationToken); await PublishChangeAsync(record, record.State, OnlinePresenceState.Offline, OnlinePresenceChangeReason.Closed, correlationId, cancellationToken); return OnlineResult.Ok(true); } @@ -277,7 +275,7 @@ public async Task> SetActivityStateAsync(Onlin return failure; } - var record = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var record = await _store.FindAsync(scope.PlayerId, cancellationToken); if (record == null) { return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "玩家不在线,须先上线登记"); @@ -302,13 +300,11 @@ public async Task> MarkBlockedAsync(OnlineScope scope, string } var now = Now(); - var record = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var record = await _store.FindAsync(scope.PlayerId, cancellationToken); if (record == null) { var blockedRecord = new OnlinePresenceRecord { - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, PlayerId = scope.PlayerId, SessionId = string.Empty, @@ -342,7 +338,7 @@ public async Task> ReleaseBlockedAsync(OnlineScope scope, str return OnlineResult.Fail(failure.Code, failure.Message); } - var record = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var record = await _store.FindAsync(scope.PlayerId, cancellationToken); if (record == null) { return OnlineResult.Ok(true); @@ -353,7 +349,7 @@ public async Task> ReleaseBlockedAsync(OnlineScope scope, str return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "玩家未处于风控限制中"); } - await _store.RemoveAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + await _store.RemoveAsync(scope.PlayerId, cancellationToken); await PublishChangeAsync(record, record.State, OnlinePresenceState.Offline, OnlinePresenceChangeReason.RiskReleased, correlationId, cancellationToken); return OnlineResult.Ok(true); } @@ -365,12 +361,10 @@ public async Task> ReleaseBlockedAsync(OnlineScope scope, str /// 单轮处理不超过 maxRecordsPerSweep 条,剩余候选由下一次清扫继续。 /// /// - /// 租户标识。 - /// 应用标识。 /// 判定基准时刻(Unix 毫秒;0 = 当前时刻,测试可注入)。 /// 取消令牌。 /// 本次清理的记录数。 - public async Task SweepTimeoutsAsync(long tenantId, long appId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task SweepTimeoutsAsync(long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : Now(); var swept = 0; @@ -378,7 +372,7 @@ public async Task SweepTimeoutsAsync(long tenantId, long appId, long nowUni { var remaining = _maxRecordsPerSweep - swept; var batchCount = remaining < _sweepBatchSize ? remaining : _sweepBatchSize; - var candidates = await _store.ListSweepCandidatesAsync(tenantId, appId, now, _idleTimeoutSeconds * 1000L, batchCount, cancellationToken); + var candidates = await _store.ListSweepCandidatesAsync(now, _idleTimeoutSeconds * 1000L, batchCount, cancellationToken); if (candidates.Count == 0) { break; @@ -421,20 +415,18 @@ public async Task> GetAsync(OnlineScope scope, return failure; } - var record = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var record = await _store.FindAsync(scope.PlayerId, cancellationToken); return OnlineResult.Ok(record != null ? record.State : OnlinePresenceState.Offline); } /// - /// 统计 (TenantId, AppId) 在线人数(Blocked 不计入在线;Admin 查询口径)。 + /// 统计全部在线人数(Blocked 不计入在线;Admin 查询口径)。 /// - /// 租户标识。 - /// 应用标识。 /// 取消令牌。 /// 在线人数(不含 Blocked)。 - public async Task CountOnlineAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public async Task CountOnlineAsync(CancellationToken cancellationToken = default) { - var records = await _store.ListByAppAsync(tenantId, appId, cancellationToken); + var records = await _store.ListAllAsync(cancellationToken); var count = 0; foreach (var record in records) { @@ -448,15 +440,13 @@ public async Task CountOnlineAsync(long tenantId, long appId, CancellationT } /// - /// 列出 (TenantId, AppId) 全部在线状态记录(Admin 查询输入)。 + /// 列出全部在线状态记录(Admin 查询输入)。 /// - /// 租户标识。 - /// 应用标识。 /// 取消令牌。 /// 在线状态记录列表。 - public Task> ListByAppAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAllAsync(CancellationToken cancellationToken = default) { - return _store.ListByAppAsync(tenantId, appId, cancellationToken); + return _store.ListAllAsync(cancellationToken); } /// @@ -536,7 +526,7 @@ private async Task TrySweepRecordAsync(OnlinePresenceRecord record, long n { if (record.State == OnlinePresenceState.Reconnecting && record.ReconnectDeadlineAtTime > 0 && now > record.ReconnectDeadlineAtTime) { - await _store.RemoveAsync(record.TenantId, record.AppId, record.PlayerId, cancellationToken); + await _store.RemoveAsync(record.PlayerId, cancellationToken); await PublishChangeAsync(record, record.State, OnlinePresenceState.Offline, OnlinePresenceChangeReason.ReconnectWindowExpired, null, cancellationToken); return true; } @@ -561,7 +551,7 @@ private async Task TrySweepRecordAsync(OnlinePresenceRecord record, long n /// 取消令牌。 private Task PublishChangeAsync(OnlinePresenceRecord record, OnlinePresenceState fromState, OnlinePresenceState toState, OnlinePresenceChangeReason reason, string correlationId, CancellationToken cancellationToken) { - var changeEvent = OnlinePresenceEvents.Create(record.TenantId, record.AppId, record.ServerId, record.PlayerId, record.SessionId, fromState.ToString(), toState.ToString(), reason.ToString(), correlationId); + var changeEvent = OnlinePresenceEvents.Create(record.ServerId, record.PlayerId, record.SessionId, fromState.ToString(), toState.ToString(), reason.ToString(), correlationId); return _eventPublisher.PublishAsync(changeEvent, cancellationToken); } diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlineSocialPresenceProbe.cs b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlineSocialPresenceProbe.cs index dd781abfe..ce94b2230 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlineSocialPresenceProbe.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Presence/OnlineSocialPresenceProbe.cs @@ -60,21 +60,19 @@ public OnlineSocialPresenceProbe(OnlinePresenceService presence) } /// - /// 以租户、应用与玩家构造作用域(服务器位为 0)查询在线状态事实源;查询成功且状态既非离线也非封禁时返回 true,查询失败一律按离线返回 false。 + /// 以玩家构造作用域(服务器位为 0)查询在线状态事实源;查询成功且状态既非离线也非封禁时返回 true,查询失败一律按离线返回 false。 /// /// - /// Builds a scope from tenant, app and player (server id 0) and reads the presence service; returns true only when the + /// Builds a scope from the player (server id 0) and reads the presence service; returns true only when the /// lookup succeeds and the state is neither nor . /// A failed lookup is treated as offline. /// - /// 租户标识 / Tenant id - /// 应用标识 / App id /// 玩家标识 / Player id /// 取消令牌 / Cancellation token /// 玩家是否在线 / Whether the player is online - public async Task IsOnlineAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public async Task IsOnlineAsync(long playerId, CancellationToken cancellationToken = default) { - var scope = new OnlineScope(tenantId, appId, 0, playerId); + var scope = new OnlineScope(0, playerId); var result = await _presence.GetAsync(scope, cancellationToken).ConfigureAwait(false); return result.IsSuccess && result.Data != OnlinePresenceState.Offline diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Session/IOnlineSessionStore.cs b/Capability/GameFrameX.Capability.Online.Foundation/Session/IOnlineSessionStore.cs index 07677aa55..8ebdbc30a 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Session/IOnlineSessionStore.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Session/IOnlineSessionStore.cs @@ -33,7 +33,7 @@ namespace GameFrameX.Capability.Online.Foundation.Session; /// 会话域存储接口(会话与 Token 指纹索引的持久化契约)。 /// /// 维护约束:索引——Token 指纹唯一(FindByTokenHashAsync 命中至多一条活跃会话); -/// 会话按 (TenantId, AppId, PlayerId) 检索活跃集合(多端策略裁决输入); +/// 会话按 PlayerId 检索活跃集合(多端策略裁决输入); /// 生产装配以持久化实现(含 Token 指纹索引与 TTL 清理)替换内存默认实现。 /// /// @@ -56,26 +56,22 @@ public interface IOnlineSessionStore /// 会话实体;不存在返回 null。 Task FindByTokenHashAsync(string tokenHash, CancellationToken cancellationToken = default); - /// 列出玩家在 (TenantId, AppId) 下的非终态会话(多端策略裁决输入)。 - /// 租户标识。 - /// 应用标识。 + /// 列出玩家的非终态会话(多端策略裁决输入)。 /// 玩家标识。 /// 取消令牌。 /// 非终态会话列表。 - Task> ListActiveByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task> ListActiveByPlayerAsync(long playerId, CancellationToken cancellationToken = default); /// 列出全部非终态会话(过期/重连超窗清理任务的扫描输入)。 /// 取消令牌。 /// 全部非终态会话列表。 Task> ListNonTerminalAsync(CancellationToken cancellationToken = default); - /// 统计作用域 (TenantId, AppId, ServerId) 内非终态会话的按状态分组计数(聚合谓词下推:终态判定同 ,与在线总览口径一致;键按状态枚举值升序)。 - /// 租户标识。 - /// 应用标识。 + /// 统计区服内非终态会话的按状态分组计数(聚合谓词下推:终态判定同 ,与在线总览口径一致;键按状态枚举值升序)。 /// 区服标识。 /// 取消令牌。 /// 状态 → 会话数(只含非终态状态;无非终态会话时为空表)。 - Task> CountNonTerminalByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default); + Task> CountNonTerminalByScopeAsync(long serverId, CancellationToken cancellationToken = default); /// 移除会话(测试与物理清理用;正常流程走终态不删除)。 /// 会话标识。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Session/InMemoryOnlineSessionStore.cs b/Capability/GameFrameX.Capability.Online.Foundation/Session/InMemoryOnlineSessionStore.cs index aeaa282ef..8da75a631 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Session/InMemoryOnlineSessionStore.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Session/InMemoryOnlineSessionStore.cs @@ -114,20 +114,18 @@ public Task FindByTokenHashAsync(string tokenHash, CancellationTo } } - /// 列出玩家在 (TenantId, AppId) 下的非终态会话。 - /// 租户标识。 - /// 应用标识。 + /// 列出玩家的非终态会话。 /// 玩家标识。 /// 取消令牌。 /// 非终态会话列表。 - public Task> ListActiveByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListActiveByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { var result = new List(); foreach (var session in _sessions.Values) { - if (session.TenantId == tenantId && session.AppId == appId && session.PlayerId == playerId && !session.State.IsTerminal()) + if (session.PlayerId == playerId && !session.State.IsTerminal()) { result.Add(session); } @@ -157,20 +155,18 @@ public Task> ListNonTerminalAsync(CancellationToken } } - /// 统计作用域 (TenantId, AppId, ServerId) 内非终态会话的按状态分组计数(表内扫描不产出实体副本;键按状态枚举值升序)。 - /// 租户标识。 - /// 应用标识。 + /// 统计区服内非终态会话的按状态分组计数(表内扫描不产出实体副本;键按状态枚举值升序)。 /// 区服标识。 /// 取消令牌。 /// 状态 → 会话数(只含非终态状态;无非终态会话时为空表)。 - public Task> CountNonTerminalByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public Task> CountNonTerminalByScopeAsync(long serverId, CancellationToken cancellationToken = default) { lock (_syncRoot) { var counts = new SortedDictionary(); foreach (var session in _sessions.Values) { - if (session.TenantId == tenantId && session.AppId == appId && session.ServerId == serverId && !session.State.IsTerminal()) + if (session.ServerId == serverId && !session.State.IsTerminal()) { counts.TryGetValue(session.State, out var current); counts[session.State] = current + 1; diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSession.cs b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSession.cs index ba4d89040..ca62e3545 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSession.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSession.cs @@ -46,15 +46,6 @@ public sealed class OnlineSession /// public string Id { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } /// /// 获取或设置区服标识(会话与 Token 的作用域含 Server 位)。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionEvents.cs b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionEvents.cs index 13ca92cb3..e8d32af00 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionEvents.cs @@ -79,8 +79,6 @@ public static class OnlineSessionEvents /// /// 事件类型(本类常量)。 /// 会话标识。 - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 玩家标识。 /// 会话状态码( 数值)。 @@ -89,7 +87,7 @@ public static class OnlineSessionEvents /// 原因描述(审计承载;踢下线事件由装配层写入操作者)。 /// 关联标识(可空;接续请求上下文)。 /// 事件信封实例。 - public static OnlineEvent Create(string eventType, string sessionId, long tenantId, long appId, long serverId, long playerId, int state, int closeReason, int tokenGeneration, string reason, string correlationId = null) + public static OnlineEvent Create(string eventType, string sessionId, long serverId, long playerId, int state, int closeReason, int tokenGeneration, string reason, string correlationId = null) { var payload = new SessionEventPayload { @@ -112,8 +110,6 @@ public static OnlineEvent Create(string eventType, string sessionId, long tenant EventType = eventType, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = playerId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionManager.cs b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionManager.cs index 8d5cf1c5e..e3365d4fc 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionManager.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionManager.cs @@ -118,7 +118,7 @@ private async Task> MarkConnectedCoreAsync(string sessionId, session.ConnectionId = connectionId; session.ConnectedAtTime = Now(); await _store.AddOrUpdateAsync(session, cancellationToken); - await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionConnected, session.Id, session.TenantId, session.AppId, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "connection established"), cancellationToken); + await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionConnected, session.Id, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "connection established"), cancellationToken); return OnlineResult.Ok(true); } @@ -165,7 +165,7 @@ private async Task> MarkActiveCoreAsync(string sessionId, Can session.State = OnlineSessionState.Active; await _store.AddOrUpdateAsync(session, cancellationToken); - await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionActive, session.Id, session.TenantId, session.AppId, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "session active"), cancellationToken); + await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionActive, session.Id, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "session active"), cancellationToken); return OnlineResult.Ok(true); } @@ -265,7 +265,7 @@ private async Task> MarkDisconnectedCoreAsync(string sessionI session.ReconnectDeadlineAtTime = now + reconnectWindowSeconds * 1000L; session.ConnectionId = string.Empty; await _store.AddOrUpdateAsync(session, cancellationToken); - await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionReconnecting, session.Id, session.TenantId, session.AppId, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "connection lost, reconnect window opened"), cancellationToken); + await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionReconnecting, session.Id, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "connection lost, reconnect window opened"), cancellationToken); return OnlineResult.Ok(true); } @@ -315,7 +315,7 @@ private async Task> MarkReconnectedCoreAsync(string sessionId session.ConnectionId = connectionId; session.ReconnectDeadlineAtTime = 0; await _store.AddOrUpdateAsync(session, cancellationToken); - await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionConnected, session.Id, session.TenantId, session.AppId, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "reconnected"), cancellationToken); + await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionConnected, session.Id, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "reconnected"), cancellationToken); return OnlineResult.Ok(true); } @@ -372,7 +372,7 @@ private async Task> MarkResumedCoreAsync(string sessionId, st session.ConnectionId = connectionId; session.ReconnectDeadlineAtTime = 0; await _store.AddOrUpdateAsync(session, cancellationToken); - await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionConnected, session.Id, session.TenantId, session.AppId, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "session resumed"), cancellationToken); + await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionConnected, session.Id, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "session resumed"), cancellationToken); return OnlineResult.Ok(true); } @@ -449,7 +449,7 @@ internal async Task> CloseGateHeldAsync(string sessionId, Onl session.CurrentTokenHash = string.Empty; session.ConnectionId = string.Empty; await _store.AddOrUpdateAsync(session, cancellationToken); - await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(eventType, session.Id, session.TenantId, session.AppId, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, reason ?? string.Empty, correlationId), cancellationToken); + await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(eventType, session.Id, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, reason ?? string.Empty, correlationId), cancellationToken); return OnlineResult.Ok(true); } diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionReconnectService.cs b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionReconnectService.cs index d9258c812..cf7eae46b 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionReconnectService.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionReconnectService.cs @@ -232,7 +232,7 @@ public async Task> NotifyPlayerDisconnectedAsync(OnlineScope return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "重连窗口必须为正数(秒)"); } - var active = await _store.ListActiveByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var active = await _store.ListActiveByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); foreach (var session in active) { if (session == null) @@ -273,22 +273,13 @@ private static (OnlineErrorCode Code, string Message)? ValidateScopeAndConnectio } /// - /// 校验作用域与会话一致(跨租户 / 跨 App / 跨服 / 跨玩家一律拒绝)。 + /// 校验作用域与会话一致(跨服 / 跨玩家一律拒绝)。 /// /// 目标会话。 /// 生效作用域。 /// 失败结果;一致返回 null。 private static (OnlineErrorCode Code, string Message)? EnsureScopeMatch(OnlineSession session, OnlineScope scope) { - if (session.TenantId != scope.TenantId) - { - return (OnlineErrorCode.CrossTenantDenied, "会话不属于当前租户"); - } - - if (session.AppId != scope.AppId) - { - return (OnlineErrorCode.CrossAppDenied, "会话不属于当前应用"); - } if (session.ServerId != scope.ServerId) { diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionTokenService.cs b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionTokenService.cs index c30b04d44..0e574f887 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionTokenService.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Session/OnlineSessionTokenService.cs @@ -241,7 +241,7 @@ public async Task> IssueSessionAsync(Onli try { var replacedSessionIds = new List(); - var activeSessions = await _store.ListActiveByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var activeSessions = await _store.ListActiveByPlayerAsync(scope.PlayerId, cancellationToken); if (activeSessions.Count > 0) { switch (multiDevicePolicy) @@ -279,8 +279,6 @@ public async Task> IssueSessionAsync(Onli var session = new OnlineSession { Id = "sess-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, PlayerId = scope.PlayerId, DeviceId = deviceId ?? string.Empty, @@ -296,7 +294,7 @@ public async Task> IssueSessionAsync(Onli CloseReason = OnlineSessionCloseReason.None, }; await _store.AddOrUpdateAsync(session, cancellationToken); - await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionAuthenticated, session.Id, session.TenantId, session.AppId, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "token issued", correlationId), cancellationToken); + await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionAuthenticated, session.Id, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "token issued", correlationId), cancellationToken); return OnlineResult.Ok(new OnlineSessionStartResult { @@ -349,7 +347,7 @@ public async Task> RefreshSessionTokenAsy session.CurrentTokenHash = HashToken(newToken); session.TokenExpiresAtTime = now + session.TokenTimeToLiveSeconds * 1000L; await _store.AddOrUpdateAsync(session, cancellationToken); - await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionTokenRefreshed, session.Id, session.TenantId, session.AppId, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "token rotated", correlationId), cancellationToken); + await _eventPublisher.PublishAsync(OnlineSessionEvents.Create(OnlineSessionEvents.SessionTokenRefreshed, session.Id, session.ServerId, session.PlayerId, (int)session.State, (int)session.CloseReason, session.TokenGeneration, "token rotated", correlationId), cancellationToken); return OnlineResult.Ok(new OnlineTokenRefreshResult { @@ -459,22 +457,13 @@ private async Task FindLiveBySessionIdAsync(string sessionId, Onl } /// - /// 校验作用域与会话一致(跨租户/跨 App/跨服一律拒绝)。 + /// 校验作用域与会话一致(跨服一律拒绝)。 /// /// 目标会话。 /// 生效作用域。 /// 失败结果;一致返回 null。 private static OnlineResult EnsureScopeMatch(OnlineSession session, OnlineScope scope) { - if (session.TenantId != scope.TenantId) - { - return OnlineResult.Fail(OnlineErrorCode.CrossTenantDenied, "会话不属于当前租户"); - } - - if (session.AppId != scope.AppId) - { - return OnlineResult.Fail(OnlineErrorCode.CrossAppDenied, "会话不属于当前应用"); - } if (session.ServerId != scope.ServerId) { diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Storage/IOnlinePlayerStorageStore.cs b/Capability/GameFrameX.Capability.Online.Foundation/Storage/IOnlinePlayerStorageStore.cs index fa5f2f6e7..8cd95a897 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Storage/IOnlinePlayerStorageStore.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Storage/IOnlinePlayerStorageStore.cs @@ -35,7 +35,7 @@ namespace GameFrameX.Capability.Online.Foundation.Storage; /// /// 玩家云存储接口(CAS 乐观锁内建于存储层—— 为原子比较交换)。 /// -/// 维护约束:键 = (TenantId, AppId, PlayerId, Collection, Key); 的 +/// 维护约束:键 = (PlayerId, Collection, Key); 的 /// expectedVersion == 0 表示仅创建(已存在即失败),> 0 表示版本必须匹配;软删条目对列举不可见 /// 但物理保留(复活按 CAS 版本接管);列举按键字典序稳定排序(游标分页的基础)。 /// @@ -43,7 +43,7 @@ namespace GameFrameX.Capability.Online.Foundation.Storage; public interface IOnlinePlayerStorageStore { /// 按键查找条目(含软删条目;可见性判定归服务层)。 - /// 条目键载荷(租户 + App + 玩家 + 集合名 + 条目键)。 + /// 条目键载荷(玩家 + 集合名 + 条目键)。 /// 取消令牌。 /// 条目;不存在返回 null。 Task FindAsync(OnlineStorageEntryKey key, CancellationToken cancellationToken = default); @@ -62,13 +62,11 @@ public interface IOnlinePlayerStorageStore Task> ListAsync(OnlineStorageListQuery query, CancellationToken cancellationToken = default); /// 统计集合内活跃(非软删)键数(键数上限 enforcement 输入)。 - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 集合名。 /// 取消令牌。 /// 活跃键数。 - Task CountActiveKeysAsync(long tenantId, long appId, long playerId, string collection, CancellationToken cancellationToken = default); + Task CountActiveKeysAsync(long playerId, string collection, CancellationToken cancellationToken = default); /// 列出全部条目(含软删;过期清理任务的扫描输入)。 /// 取消令牌。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Storage/InMemoryOnlinePlayerStorageStore.cs b/Capability/GameFrameX.Capability.Online.Foundation/Storage/InMemoryOnlinePlayerStorageStore.cs index c2aa3319d..ed49dab12 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Storage/InMemoryOnlinePlayerStorageStore.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Storage/InMemoryOnlinePlayerStorageStore.cs @@ -27,6 +27,8 @@ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== +using GameFrameX.Capability.Online.Abstractions.Keys; + namespace GameFrameX.Capability.Online.Foundation.Storage; using System.Threading; @@ -45,7 +47,7 @@ public sealed class InMemoryOnlinePlayerStorageStore : IOnlinePlayerStorageStore /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 条目表:键 = (TenantId, AppId, PlayerId, Collection, Key) 复合字符串。 + /// 条目表:键 = OnlineRowKey.PlayerStorage(PlayerId, Collection, Key)。 private readonly Dictionary _entries = new(); /// @@ -60,14 +62,12 @@ public sealed class InMemoryOnlinePlayerStorageStore : IOnlinePlayerStorageStore /// 条目;不存在返回 null。 public Task FindAsync(OnlineStorageEntryKey key, CancellationToken cancellationToken = default) { - var tenantId = key.TenantId; - var appId = key.AppId; var playerId = key.PlayerId; var collection = key.Collection; var entryKey = key.Key; lock (_syncRoot) { - _entries.TryGetValue(BuildKey(tenantId, appId, playerId, collection, entryKey), out var entry); + _entries.TryGetValue(OnlineRowKey.PlayerStorage(playerId, collection, entryKey), out var entry); return Task.FromResult(entry); } } @@ -83,7 +83,7 @@ public Task UpsertAsync(OnlinePlayerStorageEntry entry, long expectedVersi lock (_syncRoot) { - var storageKey = BuildKey(entry.TenantId, entry.AppId, entry.PlayerId, entry.Collection, entry.Key); + var storageKey = OnlineRowKey.PlayerStorage(entry.PlayerId, entry.Collection, entry.Key); var exists = _entries.ContainsKey(storageKey); if (expectedVersion == 0) { @@ -113,15 +113,13 @@ public Task UpsertAsync(OnlinePlayerStorageEntry entry, long expectedVersi /// 非软删条目列表(按键字典序)。 public Task> ListAsync(OnlineStorageListQuery query, CancellationToken cancellationToken = default) { - var tenantId = query.TenantId; - var appId = query.AppId; var playerId = query.PlayerId; var collection = query.Collection; var afterKey = query.AfterKey; var maxCount = query.MaxCount; lock (_syncRoot) { - var prefix = BuildPrefix(tenantId, appId, playerId, collection); + var prefix = OnlineRowKey.PlayerStorage(playerId, collection, string.Empty); var matches = new List(); foreach (var pair in _entries) { @@ -149,19 +147,16 @@ public Task> ListAsync(OnlineStorageList return Task.FromResult>(result); } } - /// 统计集合内活跃(非软删)键数。 - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 集合名。 /// 取消令牌。 /// 活跃键数。 - public Task CountActiveKeysAsync(long tenantId, long appId, long playerId, string collection, CancellationToken cancellationToken = default) + public Task CountActiveKeysAsync(long playerId, string collection, CancellationToken cancellationToken = default) { lock (_syncRoot) { - var prefix = BuildPrefix(tenantId, appId, playerId, collection); + var prefix = OnlineRowKey.PlayerStorage(playerId, collection, string.Empty); var count = 0; foreach (var pair in _entries) { @@ -185,27 +180,4 @@ public Task> ListAllAsync(CancellationTo return Task.FromResult>(new List(_entries.Values)); } } - - /// 构造条目完整键。 - /// 租户标识。 - /// 应用标识。 - /// 玩家标识。 - /// 集合名。 - /// 条目键。 - /// 复合键字符串。 - private static string BuildKey(long tenantId, long appId, long playerId, string collection, string key) - { - return tenantId + ":" + appId + ":" + playerId + ":" + collection + ":" + key; - } - - /// 构造集合前缀键(列举与计数用)。 - /// 租户标识。 - /// 应用标识。 - /// 玩家标识。 - /// 集合名。 - /// 前缀字符串。 - private static string BuildPrefix(long tenantId, long appId, long playerId, string collection) - { - return tenantId + ":" + appId + ":" + playerId + ":" + collection + ":"; - } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlinePlayerStorageEntry.cs b/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlinePlayerStorageEntry.cs index 57c2a5d96..fbc54979b 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlinePlayerStorageEntry.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlinePlayerStorageEntry.cs @@ -30,24 +30,15 @@ namespace GameFrameX.Capability.Online.Foundation.Storage; /// -/// 玩家云存储条目(玩家 + App 作用域的 KV 实体;区服不参与隔离——换服数据随身)。 +/// 玩家云存储条目(玩家作用域的 KV 实体;区服不参与隔离——换服数据随身)。 /// -/// 维护约束:键 = (TenantId, AppId, PlayerId, Collection, Key),跨作用域读写结构性不可达; +/// 维护约束:键 = (PlayerId, Collection, Key),跨作用域读写结构性不可达; /// 为乐观锁版本(创建为 1,每次写递增,CAS 失败映射 6xxx); /// 删除为软删(,读取与列举即不可见); 到期后由清理任务软删。 /// /// public sealed class OnlinePlayerStorageEntry { - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } /// /// 获取或设置玩家标识。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlinePlayerStorageService.cs b/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlinePlayerStorageService.cs index de00c32da..357a03168 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlinePlayerStorageService.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlinePlayerStorageService.cs @@ -35,9 +35,9 @@ namespace GameFrameX.Capability.Online.Foundation.Storage; using GameFrameX.Capability.Online.Abstractions.Scope; /// -/// 玩家云存储服务(玩家 + App 作用域隔离的 KV 读写/分页/软删/过期清理)。 +/// 玩家云存储服务(玩家作用域隔离的 KV 读写/分页/软删/过期清理)。 /// -/// 维护约束(红线):作用域 = (TenantId, AppId, PlayerId)——区服不参与隔离(换服数据随身), +/// 维护约束(红线):作用域 = PlayerId——区服不参与隔离(换服数据随身), /// 跨作用域读写在存储键层结构性不可达,查无记录一律 /// (同构错误,防存在性探测);写入走存储层 CAS 乐观锁——expectedVersion=0 为创建、 /// >0 为版本匹配更新,冲突映射 ; @@ -80,7 +80,7 @@ public async Task> ReadAsync(OnlineScope return failure; } - var entry = await _store.FindAsync(new OnlineStorageEntryKey { TenantId = scope.TenantId, AppId = scope.AppId, PlayerId = scope.PlayerId, Collection = collection, Key = key, }, cancellationToken); + var entry = await _store.FindAsync(new OnlineStorageEntryKey { PlayerId = scope.PlayerId, Collection = collection, Key = key, }, cancellationToken); if (entry == null || entry.DeletedAtTime > 0 || IsExpired(entry)) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "存储条目不存在"); @@ -124,7 +124,7 @@ public async Task> WriteAsync(OnlineScope } var now = Now(); - var existing = await _store.FindAsync(new OnlineStorageEntryKey { TenantId = scope.TenantId, AppId = scope.AppId, PlayerId = scope.PlayerId, Collection = collection, Key = key, }, cancellationToken); + var existing = await _store.FindAsync(new OnlineStorageEntryKey { PlayerId = scope.PlayerId, Collection = collection, Key = key, }, cancellationToken); var casVersion = expectedVersion; var isResurrecting = false; if (existing != null && existing.DeletedAtTime > 0 && expectedVersion == 0) @@ -136,7 +136,7 @@ public async Task> WriteAsync(OnlineScope if (expectedVersion == 0) { - var activeKeys = await _store.CountActiveKeysAsync(scope.TenantId, scope.AppId, scope.PlayerId, collection, cancellationToken); + var activeKeys = await _store.CountActiveKeysAsync(scope.PlayerId, collection, cancellationToken); if (activeKeys >= _options.MaxKeysPerCollection) { return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "单集合键数已达上限(" + _options.MaxKeysPerCollection + ")"); @@ -150,8 +150,6 @@ public async Task> WriteAsync(OnlineScope var keepCreated = !isResurrecting && existing != null && existing.DeletedAtTime == 0; var entry = new OnlinePlayerStorageEntry { - TenantId = scope.TenantId, - AppId = scope.AppId, PlayerId = scope.PlayerId, Collection = collection, Key = key, @@ -196,7 +194,7 @@ public async Task> ListAsync(OnlineScope scope, } var effectivePageSize = pageSize == 0 ? _options.MaxPageSize : Math.Min(pageSize, _options.MaxPageSize); - var fetch = await _store.ListAsync(new OnlineStorageListQuery { TenantId = scope.TenantId, AppId = scope.AppId, PlayerId = scope.PlayerId, Collection = collection, AfterKey = cursor ?? string.Empty, MaxCount = effectivePageSize + 1, }, cancellationToken); + var fetch = await _store.ListAsync(new OnlineStorageListQuery { PlayerId = scope.PlayerId, Collection = collection, AfterKey = cursor ?? string.Empty, MaxCount = effectivePageSize + 1, }, cancellationToken); var hasMore = fetch.Count > effectivePageSize; var pageEntries = hasMore ? fetch.Take(effectivePageSize).ToList() : fetch.ToList(); var now = Now(); @@ -233,7 +231,7 @@ public async Task> DeleteAsync(OnlineScope scope, string coll return OnlineResult.Fail(failure.Code, failure.Message); } - var entry = await _store.FindAsync(new OnlineStorageEntryKey { TenantId = scope.TenantId, AppId = scope.AppId, PlayerId = scope.PlayerId, Collection = collection, Key = key, }, cancellationToken); + var entry = await _store.FindAsync(new OnlineStorageEntryKey { PlayerId = scope.PlayerId, Collection = collection, Key = key, }, cancellationToken); if (entry == null || entry.DeletedAtTime > 0 || IsExpired(entry)) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "存储条目不存在"); diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlineStorageEntryKey.cs b/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlineStorageEntryKey.cs index 815cd2671..d203622ae 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlineStorageEntryKey.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlineStorageEntryKey.cs @@ -31,21 +31,10 @@ namespace GameFrameX.Capability.Online.Foundation.Storage; /// /// 玩家云存储条目键( 的唯一提交形态; -/// 键 = 租户 + App + 玩家 + 集合名 + 条目键)。 +/// 键 = 玩家 + 集合名 + 条目键)。 /// public sealed class OnlineStorageEntryKey { - /// - /// 获取或设置租户标识。 - /// - /// Gets or sets the tenant id. - public long TenantId { get; init; } - - /// - /// 获取或设置应用标识。 - /// - /// Gets or sets the app id. - public long AppId { get; init; } /// /// 获取或设置玩家标识。 diff --git a/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlineStorageListQuery.cs b/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlineStorageListQuery.cs index b505ef9e4..77bcf0c71 100644 --- a/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlineStorageListQuery.cs +++ b/Capability/GameFrameX.Capability.Online.Foundation/Storage/OnlineStorageListQuery.cs @@ -38,17 +38,6 @@ namespace GameFrameX.Capability.Online.Foundation.Storage; /// public sealed class OnlineStorageListQuery { - /// - /// 获取或设置租户标识。 - /// - /// Gets or sets the tenant id. - public long TenantId { get; init; } - - /// - /// 获取或设置应用标识。 - /// - /// Gets or sets the app id. - public long AppId { get; init; } /// /// 获取或设置玩家标识。 diff --git a/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchActorStore.cs b/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchActorStore.cs index a2e142693..e1ea972ab 100644 --- a/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchActorStore.cs +++ b/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchActorStore.cs @@ -58,12 +58,10 @@ public interface IOnlineMatchActorStore /// /// 按标识查找对局。 /// - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 取消令牌。 /// 对局副本;不存在返回 null。 - Task FindAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default); + Task FindAsync(string matchId, CancellationToken cancellationToken = default); /// /// 以期望版本递增更新对局(CAS 语义)。 @@ -76,29 +74,23 @@ public interface IOnlineMatchActorStore /// /// 删除对局(Actor 释放;仅 允许)。 /// - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 取消令牌。 /// 删除成功返回 true。 - Task DeleteAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default); + Task DeleteAsync(string matchId, CancellationToken cancellationToken = default); /// - /// 列出作用域内全部对局(Tick 扫描与可观测性用)。 + /// 列出全部对局(Tick 扫描与可观测性用)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 对局副本列表。 - Task> ListAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListAsync(CancellationToken cancellationToken = default); /// - /// 统计作用域 (TenantId, AppId, ServerId) 内存活对局的按状态分组计数(聚合谓词下推: 即已释放、不计入,与在线总览口径一致;键按状态枚举值升序)。 + /// 统计作用域 (ServerId) 内存活对局的按状态分组计数(聚合谓词下推: 即已释放、不计入,与在线总览口径一致;键按状态枚举值升序)。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// 状态 → 对局数(不含 Closed;无存活对局时为空表)。 - Task> CountActiveByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default); + Task> CountActiveByScopeAsync(long serverId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchResultStore.cs b/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchResultStore.cs index 361c090e4..edc739ab1 100644 --- a/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchResultStore.cs +++ b/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchResultStore.cs @@ -46,12 +46,10 @@ public interface IOnlineMatchResultStore /// /// 按对局标识查找结算结果。 /// - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 取消令牌。 /// 结果副本;未结算返回 null。 - Task FindByMatchAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default); + Task FindByMatchAsync(string matchId, CancellationToken cancellationToken = default); /// /// 落定结算结果(首次胜出:已存在则返回既有结果,不覆盖)。 diff --git a/Capability/GameFrameX.Capability.Online.Match/InMemoryOnlineMatchActorStore.cs b/Capability/GameFrameX.Capability.Online.Match/InMemoryOnlineMatchActorStore.cs index 12fcb3342..e7edc2d3b 100644 --- a/Capability/GameFrameX.Capability.Online.Match/InMemoryOnlineMatchActorStore.cs +++ b/Capability/GameFrameX.Capability.Online.Match/InMemoryOnlineMatchActorStore.cs @@ -29,7 +29,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Threading; using System.Threading.Tasks; @@ -43,8 +42,7 @@ namespace GameFrameX.Capability.Online.Match; /// 都会重新打开两个 Actor 同时推进同一对局的竞态窗口。 /// /// -/// 天花板(ponytail):单锁全串行,对局基数上万后 Tick 扫描会成为热点; -/// 升级路径是按 (TenantId, AppId) 分片加锁并保留同样的 CAS 语义,调用方无感。 +/// 升级路径是按区服分片加锁并保留同样的 CAS 语义,调用方无感。 /// /// public sealed class InMemoryOnlineMatchActorStore : IOnlineMatchActorStore @@ -52,7 +50,7 @@ public sealed class InMemoryOnlineMatchActorStore : IOnlineMatchActorStore /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 对局表:键 = (TenantId, AppId, MatchId)。 + /// 对局表:键 = MatchId。 private readonly Dictionary _matches = new(); /// @@ -74,7 +72,7 @@ public Task CreateAsync(OnlineMatch match, CancellationToken cancel lock (_syncRoot) { - var key = BuildKey(match.TenantId, match.AppId, match.MatchId); + var key = match.MatchId ?? string.Empty; if (_matches.ContainsKey(key)) { return Task.FromResult(null); @@ -88,21 +86,19 @@ public Task CreateAsync(OnlineMatch match, CancellationToken cancel } /// - /// 在全局锁内按作用域与对局标识查找对局并返回副本。 + /// 在全局锁内按对局标识查找对局并返回副本。 /// /// - /// Finds the match by scope and match id under the global lock and returns a copy. + /// Finds the match by match id under the global lock and returns a copy. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 对局标识 / The match id /// 取消令牌 / Cancellation token /// 对局副本;不存在或标识为空返回 null / The match copy; null when not found or the id is empty - public Task FindAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default) + public Task FindAsync(string matchId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(FindInternal(tenantId, appId, matchId)); + return Task.FromResult(FindInternal(matchId)); } } @@ -125,7 +121,7 @@ public Task UpdateAsync(OnlineMatch match, CancellationToken cancel lock (_syncRoot) { - var key = BuildKey(match.TenantId, match.AppId, match.MatchId); + var key = match.MatchId ?? string.Empty; if (!_matches.TryGetValue(key, out var current)) { return Task.FromResult(null); @@ -149,16 +145,14 @@ public Task UpdateAsync(OnlineMatch match, CancellationToken cancel /// /// Deletes the match (actor release) under the global lock: only a Closed match can be deleted; every other case is refused with false. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 对局标识 / The match id /// 取消令牌 / Cancellation token /// 删除成功返回 true;不存在或未关闭返回 false / True when deleted; false when not found or not closed - public Task DeleteAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default) + public Task DeleteAsync(string matchId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - var key = BuildKey(tenantId, appId, matchId); + var key = matchId ?? string.Empty; if (!_matches.TryGetValue(key, out var current)) { return Task.FromResult(false); @@ -175,26 +169,21 @@ public Task DeleteAsync(long tenantId, long appId, string matchId, Cancell } /// - /// 在全局锁内列出作用域内全部对局的副本(Tick 扫描与可观测性用)。 + /// 在全局锁内列出全部对局的副本(Tick 扫描与可观测性用)。 /// /// - /// Lists copies of every match in the scope under the global lock (for tick scanning and observability). + /// Lists copies of every match under the global lock (for tick scanning and observability). /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 取消令牌 / Cancellation token /// 对局副本列表 / The list of match copies - public Task> ListAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAsync(CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) { foreach (var pair in _matches) { - if (pair.Value.TenantId == tenantId && pair.Value.AppId == appId) - { - result.Add(pair.Value.Copy()); - } + result.Add(pair.Value.Copy()); } } @@ -202,17 +191,15 @@ public Task> ListAsync(long tenantId, long appId, Can } /// - /// 在全局锁内统计作用域 (TenantId, AppId, ServerId) 内存活对局的按状态分组计数(Closed 不计入;表内扫描不产出实体副本;键按状态枚举值升序)。 + /// 在全局锁内统计作用域 (ServerId) 内存活对局的按状态分组计数(Closed 不计入;表内扫描不产出实体副本;键按状态枚举值升序)。 /// /// /// Counts live matches grouped by state under the global lock (excluding Closed), without producing entity copies. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 区服标识 / The server id /// 取消令牌 / Cancellation token /// 状态 → 对局数(不含 Closed)/ State to match count (Closed excluded) - public Task> CountActiveByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public Task> CountActiveByScopeAsync(long serverId, CancellationToken cancellationToken = default) { var counts = new SortedDictionary(); lock (_syncRoot) @@ -220,7 +207,7 @@ public Task> CountActiveByScopeAsync( foreach (var pair in _matches) { var match = pair.Value; - if (match.TenantId == tenantId && match.AppId == appId && match.ServerId == serverId && match.State != OnlineMatchState.Closed) + if (match.ServerId == serverId && match.State != OnlineMatchState.Closed) { counts.TryGetValue(match.State, out var current); counts[match.State] = current + 1; @@ -234,34 +221,15 @@ public Task> CountActiveByScopeAsync( /// /// 按标识查找并返回副本(须在锁内调用)。 /// - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 对局副本;不存在返回 null。 - private OnlineMatch FindInternal(long tenantId, long appId, string matchId) + private OnlineMatch FindInternal(string matchId) { if (string.IsNullOrEmpty(matchId)) { return null; } - return _matches.TryGetValue(BuildKey(tenantId, appId, matchId), out var match) ? match.Copy() : null; - } - - /// - /// 构造作用域隔离键。 - /// - /// 租户标识。 - /// App 标识。 - /// 对局标识。 - /// 复合键。 - private static string BuildKey(long tenantId, long appId, string matchId) - { - return string.Concat( - tenantId.ToString(CultureInfo.InvariantCulture), - ":", - appId.ToString(CultureInfo.InvariantCulture), - ":", - matchId ?? string.Empty); + return _matches.TryGetValue(matchId, out var match) ? match.Copy() : null; } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Match/InMemoryOnlineMatchSettlementStore.cs b/Capability/GameFrameX.Capability.Online.Match/InMemoryOnlineMatchSettlementStore.cs index f446a3c2c..5a7a3bd55 100644 --- a/Capability/GameFrameX.Capability.Online.Match/InMemoryOnlineMatchSettlementStore.cs +++ b/Capability/GameFrameX.Capability.Online.Match/InMemoryOnlineMatchSettlementStore.cs @@ -15,9 +15,9 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Threading; using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; namespace GameFrameX.Capability.Online.Match; @@ -40,21 +40,19 @@ public sealed class InMemoryOnlineMatchSettlementStore : IOnlineMatchSettlementS /// 全局读写锁(结果表与 outbox 表共用,保证跨表原子性)。 private readonly object _syncRoot = new(); - /// 结果表:键 = (TenantId, AppId, MatchId)。 + /// 结果表:键 = MatchId()。 private readonly Dictionary _results = new(); /// 待发奖记录表:键 = MatchResultId。 private readonly Dictionary _outboxes = new(); /// - /// 在全局锁内按作用域与对局标识查找结算结果并返回副本;标识为空直接返回 null。 + /// 在全局锁内按对局标识查找结算结果并返回副本;标识为空直接返回 null。 /// - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 取消令牌。 /// 结果副本;未结算返回 null。 - public Task FindByMatchAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default) + public Task FindByMatchAsync(string matchId, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(matchId)) { @@ -63,7 +61,7 @@ public Task FindByMatchAsync(long tenantId, long appId, strin lock (_syncRoot) { - return Task.FromResult(_results.TryGetValue(BuildResultKey(tenantId, appId, matchId), out var result) ? result.Copy() : null); + return Task.FromResult(_results.TryGetValue(OnlineRowKey.MatchResult(matchId), out var result) ? result.Copy() : null); } } @@ -82,7 +80,7 @@ public Task CommitAsync(OnlineMatchResult result, Cancellatio lock (_syncRoot) { - var key = BuildResultKey(result.TenantId, result.AppId, result.MatchId); + var key = OnlineRowKey.MatchResult(result.MatchId); if (_results.TryGetValue(key, out var existing)) { return Task.FromResult(existing.Copy()); @@ -109,7 +107,7 @@ public Task CommitWithOutboxAsync(OnlineMatchResult result, C lock (_syncRoot) { - var key = BuildResultKey(result.TenantId, result.AppId, result.MatchId); + var key = OnlineRowKey.MatchResult(result.MatchId); if (_results.TryGetValue(key, out var existing)) { return Task.FromResult(existing.Copy()); @@ -284,8 +282,6 @@ private static OnlineMatchRewardOutboxRecord BuildInitialOutbox(OnlineMatchResul { MatchResultId = result.MatchResultId, MatchId = result.MatchId, - TenantId = result.TenantId, - AppId = result.AppId, Result = result.Copy(), RowVersion = 1, }; @@ -341,20 +337,4 @@ private static OnlineMatchSettlementRetryEntry ToRetryEntry(OnlineMatchRewardOut }; } - /// - /// 构造结果作用域隔离键。 - /// - /// 租户标识。 - /// App 标识。 - /// 对局标识。 - /// 复合键。 - private static string BuildResultKey(long tenantId, long appId, string matchId) - { - return string.Concat( - tenantId.ToString(CultureInfo.InvariantCulture), - ":", - appId.ToString(CultureInfo.InvariantCulture), - ":", - matchId ?? string.Empty); - } } diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatch.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatch.cs index 914e9da4e..b83d0758f 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatch.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatch.cs @@ -46,16 +46,6 @@ namespace GameFrameX.Capability.Online.Match; /// public sealed class OnlineMatch { - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置区服标识(作用域隔离键)。 /// @@ -213,8 +203,6 @@ public OnlineMatch Copy() return new OnlineMatch { - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, MatchId = MatchId, AssignmentId = AssignmentId, diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchActor.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchActor.cs index 127eea0b1..7e501304a 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchActor.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchActor.cs @@ -44,7 +44,7 @@ namespace GameFrameX.Capability.Online.Match; /// 三段式,CAS 失败即表示本 Actor 已失去所有权(另一 Actor 推进过同一对局),此时**不得**保留任何 /// 本地改写(无串局);② 客户端只能提交 意图, /// 胜负与奖励一律由玩法实现依服务端状态裁决;③ 每个入口都校验 -/// ,跨租户/App/Server 一律 。 +/// ,跨区服一律 。 /// /// /// 输入校验顺序固定为:成员身份 → 成员在线状态 → 对局阶段 → 重复包 → 乱序包 → 玩法裁决。 @@ -103,19 +103,11 @@ public string MatchId } /// - /// 获取租户标识。 + /// 获取区服标识。 /// - public long TenantId + public long ServerId { - get { return _match.TenantId; } - } - - /// - /// 获取 App 标识。 - /// - public long AppId - { - get { return _match.AppId; } + get { return _match.ServerId; } } /// @@ -536,8 +528,6 @@ public Task> BuildResultAsync(long nowUnixMillis result.MatchResultId = "mrs-" + Guid.NewGuid().ToString("N"); result.MatchId = match.MatchId; - result.TenantId = match.TenantId; - result.AppId = match.AppId; result.ServerId = match.ServerId; result.Mode = match.Mode; result.Region = match.Region; @@ -868,7 +858,7 @@ private Task> MutateAsync(OnlineScope scope, long /// 对局自身隔离键构成的作用域。 private OnlineScope SystemScope() { - return new OnlineScope(_match.TenantId, _match.AppId, _match.ServerId); + return new OnlineScope(_match.ServerId); } /// @@ -945,20 +935,17 @@ private async Task PublishStateChangedAsync(OnlineMatchState fromState, OnlineMa } var memberCount = _match.Members == null ? 0 : _match.Members.Count; - await _eventPublisher.PublishAsync(OnlineMatchRuntimeEvents.CreateMatchStateChanged(_match.TenantId, _match.AppId, _match.ServerId, _match.MatchId, _match.AssignmentId, fromState.ToString(), toState.ToString(), _match.ServerSequence, memberCount), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineMatchRuntimeEvents.CreateMatchStateChanged(_match.ServerId, _match.MatchId, _match.AssignmentId, fromState.ToString(), toState.ToString(), _match.ServerSequence, memberCount), cancellationToken).ConfigureAwait(false); } /// - /// 校验作用域与对局的三元隔离键一致。 + /// 校验作用域与对局的区服隔离键一致。 /// - /// 请求作用域。 /// 对局。 /// 一致返回 true。 private static bool ScopeMatches(OnlineScope scope, OnlineMatch match) { - return scope.TenantId == match.TenantId - && scope.AppId == match.AppId - && scope.ServerId == match.ServerId; + return scope.ServerId == match.ServerId; } /// diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs index e1b0216be..103fe76af 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs @@ -167,8 +167,11 @@ public void Register(CapabilityRegistrationContext context) var eventPublisher = context.GetService(); context.AddService(static _ => new InMemoryOnlineMatchActorStore()); var matchActorStore = context.GetService(); - context.AddService(static _ => new InMemoryOnlineMatchSettlementStore()); - context.AddService(static _ => new InMemoryOnlineMatchSettlementStore()); + // 同一实例注册两接口键(C460):结算写入与投影读取必须看到同一份事实——分别 new 会造成 + // 「结算落库 / 投影读空」的分裂脑(默认内存形态下黄金路径静默断链);族 / 宿主覆盖仍逐键恒胜出。 + var settlementStoreInstance = new InMemoryOnlineMatchSettlementStore(); + context.AddService(_ => settlementStoreInstance); + context.AddService(_ => settlementStoreInstance); var matchSettlementStore = context.GetService(); var rpsGame = new OnlineRockPaperScissorsGame(); @@ -404,7 +407,7 @@ private async Task DispatchAssignmentNotificationAsync(OnlineEvent onlineEvent, return; } - var resolved = await _matchDomain.ResolveAssignmentAsync(onlineEvent.TenantId, onlineEvent.AppId, payload.AssignmentId, cancellationToken).ConfigureAwait(false); + var resolved = await _matchDomain.ResolveAssignmentAsync(payload.AssignmentId, cancellationToken).ConfigureAwait(false); if (!resolved.IsSuccess || resolved.Data == null || resolved.Data.MatchId == 0) { return; diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchDomainService.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchDomainService.cs index 2f5256ff7..c4d93d462 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchDomainService.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchDomainService.cs @@ -204,7 +204,7 @@ public async Task> CancelAsync(OnlineScope return OnlineResult.Fail(failureCode.Value.Code, failureCode.Value.Message); } - var active = await _store.FindActiveByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var active = await _store.FindActiveByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); if (active == null) { // 无排队票据 = 终态回执(未在排队),不算失败——协议面映射旧 420003。 @@ -242,7 +242,7 @@ public async Task> GetStatusAsync(OnlineSc return OnlineResult.Fail(failureCode.Value.Code, failureCode.Value.Message); } - var latest = await _store.FindLatestByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var latest = await _store.FindLatestByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); if (latest == null) { return OnlineResult.Ok(new OnlineMatchDomainStatus { Queuing = false, Matched = false, MatchId = 0 }); @@ -330,12 +330,10 @@ public async Task> EnterAsync(OnlineScope s /// Resolves an assignment id to numeric match id, mode and players. Empty id fails with ParameterInvalid; /// the in-memory registration is preferred, otherwise the assignment is loaded from the ticket store and registered; a missing assignment fails with ResourceNotFound. /// - /// 租户标识 / Tenant id - /// 应用标识 / Application id /// 撮合分配标识 / Matchmaking assignment id /// 取消令牌 / Cancellation token /// 分配解析结果 / Assignment resolution result - public async Task> ResolveAssignmentAsync(long tenantId, long appId, string assignmentId, CancellationToken cancellationToken = default) + public async Task> ResolveAssignmentAsync(string assignmentId, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(assignmentId)) { @@ -345,7 +343,7 @@ public async Task> ResolveAssignmentAs var registration = FindRegistration(assignmentId); if (registration == null) { - var assignment = await _store.FindAssignmentAsync(tenantId, appId, assignmentId, cancellationToken).ConfigureAwait(false); + var assignment = await _store.FindAssignmentAsync(assignmentId, cancellationToken).ConfigureAwait(false); if (assignment == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "分配不存在"); @@ -567,13 +565,11 @@ private OnlineResult ValidateEntry(OnlineScope scope, lo /// 对局 Actor 结果(失败携带错误码与描述)。 private async Task> ResolveOrCreateActorAsync(OnlineScope scope, AssignmentRegistration registration, string runtimeMatchId, long now, CancellationToken cancellationToken) { - var actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, runtimeMatchId, cancellationToken).ConfigureAwait(false); + var actor = await _runtime.ResolveActorAsync(runtimeMatchId, cancellationToken).ConfigureAwait(false); if (actor == null) { var assignment = new OnlineMatchAssignment { - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, MatchId = runtimeMatchId, AssignmentId = registration.AssignmentId, @@ -591,7 +587,7 @@ private async Task> ResolveOrCreateActorAsync(Onl } // 并发同键创建:store 唯一约束裁决后重解析一次(幂等并发路径)。 - actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, runtimeMatchId, cancellationToken).ConfigureAwait(false); + actor = await _runtime.ResolveActorAsync(runtimeMatchId, cancellationToken).ConfigureAwait(false); if (actor == null) { return OnlineResult.Fail(created.IsSuccess ? OnlineErrorCode.InternalError : created.Code, created.Message); @@ -654,7 +650,7 @@ private static async Task> MarkMembersReady /// (数值对局标识, Actor, 成员);无归属返回 null。 private async Task<(long NumericMatchId, OnlineMatchActor Actor, OnlineMatchMember Member)?> LocatePlayerMatchAsync(OnlineScope scope, CancellationToken cancellationToken) { - var latest = await _store.FindLatestByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var latest = await _store.FindLatestByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); if (latest == null || latest.State != OnlineMatchTicketState.Matched || string.IsNullOrEmpty(latest.AssignmentId)) { return null; @@ -667,7 +663,7 @@ private static async Task> MarkMembersReady } var runtimeMatchId = DeriveRuntimeMatchId(scope.ServerId, registration.NumericMatchId); - var actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, runtimeMatchId, cancellationToken).ConfigureAwait(false); + var actor = await _runtime.ResolveActorAsync(runtimeMatchId, cancellationToken).ConfigureAwait(false); if (actor == null) { return null; @@ -720,7 +716,7 @@ private async Task ResolveMatchedNumericAsync(OnlineMatchTicket ticket, Ca } // 懒登记:撮合可能发生在后台 tick(等待方首次查询 / 通知推送前于此收敛为同一数值标识)。 - var assignment = await _store.FindAssignmentAsync(ticket.TenantId, ticket.AppId, ticket.AssignmentId, cancellationToken).ConfigureAwait(false); + var assignment = await _store.FindAssignmentAsync(ticket.AssignmentId, cancellationToken).ConfigureAwait(false); return assignment == null ? 0 : RegisterAssignment(assignment).NumericMatchId; } @@ -885,14 +881,14 @@ private static bool MembersMatch(OnlineMatchSnapshot snapshot, IReadOnlyList - /// 以既有作用域三元组派生玩家位作用域。 + /// 以既有作用域派生玩家位作用域。 /// /// 请求作用域。 /// 玩家标识。 /// 玩家级作用域。 private static OnlineScope WithPlayer(OnlineScope scope, long playerId) { - return new OnlineScope(scope.TenantId, scope.AppId, scope.ServerId, playerId); + return new OnlineScope(scope.ServerId, playerId); } /// diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchGameBridgeService.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchGameBridgeService.cs index 84cafa677..79441b393 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchGameBridgeService.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchGameBridgeService.cs @@ -155,7 +155,7 @@ public async Task> SubmitGestureAsync(On } var matchId = DeriveMatchId(scope.ServerId, roomId, round); - var actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, matchId, cancellationToken).ConfigureAwait(false); + var actor = await _runtime.ResolveActorAsync(matchId, cancellationToken).ConfigureAwait(false); if (actor == null) { return Fail(OnlineErrorCode.ResourceNotFound, "对局不存在"); @@ -222,7 +222,7 @@ public async Task> GetGameInfoAsync(Onli } var matchId = DeriveMatchId(scope.ServerId, roomId, round); - var actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, matchId, cancellationToken).ConfigureAwait(false); + var actor = await _runtime.ResolveActorAsync(matchId, cancellationToken).ConfigureAwait(false); if (actor == null) { return Fail(OnlineErrorCode.ResourceNotFound, "对局不存在"); @@ -287,13 +287,11 @@ private OnlineResult ValidateStartRequest(OnlineScope /// 对局 Actor 结果(失败携带错误码与描述)。 private async Task> ResolveOrCreateActorAsync(OnlineScope scope, long roomId, string matchId, IReadOnlyList playerIds, long now, CancellationToken cancellationToken) { - var actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, matchId, cancellationToken).ConfigureAwait(false); + var actor = await _runtime.ResolveActorAsync(matchId, cancellationToken).ConfigureAwait(false); if (actor == null) { var assignment = new OnlineMatchAssignment { - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, MatchId = matchId, AssignmentId = BuildAssignmentId(scope.ServerId, roomId), @@ -314,7 +312,7 @@ private async Task> ResolveOrCreateActorAsync(Onl } } - actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, matchId, cancellationToken).ConfigureAwait(false); + actor = await _runtime.ResolveActorAsync(matchId, cancellationToken).ConfigureAwait(false); if (actor == null) { return OnlineResult.Fail(created.IsSuccess ? OnlineErrorCode.InternalError : created.Code, created.Message); @@ -459,14 +457,14 @@ private static string BuildAssignmentId(long serverId, long roomId) } /// - /// 以既有作用域三元组派生玩家位作用域。 + /// 以既有作用域派生玩家位作用域。 /// /// 请求作用域。 /// 玩家标识。 /// 玩家级作用域。 private static OnlineScope WithPlayer(OnlineScope scope, long playerId) { - return new OnlineScope(scope.TenantId, scope.AppId, scope.ServerId, playerId); + return new OnlineScope(scope.ServerId, playerId); } /// diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchInputRejection.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchInputRejection.cs index e12bb84cb..0912927e5 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchInputRejection.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchInputRejection.cs @@ -67,6 +67,6 @@ public enum OnlineMatchInputRejection /// 玩法级非法输入(越权回合、非本回合玩家、动作不可识别等)。 IllegalAction = 8, - /// 作用域不匹配(跨租户/App/Server)。 + /// 作用域不匹配(跨区服)。 ScopeDenied = 9, } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchReconnectService.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchReconnectService.cs index bdc86fad6..c3fa26b6c 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchReconnectService.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchReconnectService.cs @@ -72,7 +72,7 @@ public async Task> DisconnectAsync(Onlin return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "断线操作必须带玩家主体位"); } - var actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, matchId, cancellationToken).ConfigureAwait(false); + var actor = await _runtime.ResolveActorAsync(matchId, cancellationToken).ConfigureAwait(false); if (actor == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "对局不存在"); @@ -115,7 +115,7 @@ public async Task> ReconnectAsync(Onlin return OnlineResult.Fail(OnlineErrorCode.ScopeDenied, "重连上下文的玩家与作用域不一致"); } - var actor = await _runtime.ResolveActorAsync(scope.TenantId, scope.AppId, context.MatchId, cancellationToken).ConfigureAwait(false); + var actor = await _runtime.ResolveActorAsync(context.MatchId, cancellationToken).ConfigureAwait(false); if (actor == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "对局不存在"); diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchResult.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchResult.cs index d3ebc9de6..2759a32ba 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchResult.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchResult.cs @@ -57,17 +57,7 @@ public sealed class OnlineMatchResult public string MatchId { get; set; } /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - - /// - /// 获取或设置区服标识(作用域隔离键)。 + /// 获取或设置区服标识(作用域隔离键;结算结果归属区服快照)。 /// public long ServerId { get; set; } @@ -121,8 +111,6 @@ public OnlineMatchResult Copy() { MatchResultId = MatchResultId, MatchId = MatchId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Mode = Mode, Region = Region, diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchResultDispatcher.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchResultDispatcher.cs index b02e94677..32ccd787e 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchResultDispatcher.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchResultDispatcher.cs @@ -97,7 +97,7 @@ public async Task> DispatchAsync(Online } var businessOrderId = BuildBusinessOrderId(result.MatchResultId, entry.PlayerId); - var scope = new OnlineScope(result.TenantId, result.AppId, result.ServerId, entry.PlayerId); + var scope = new OnlineScope(result.ServerId, entry.PlayerId); var request = new OnlineGrantRequest( scope, OnlineAssetChangeSource.MatchReward, diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRewardOutboxRecord.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRewardOutboxRecord.cs index a1df81f57..73b1b37ce 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRewardOutboxRecord.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRewardOutboxRecord.cs @@ -41,15 +41,6 @@ public sealed class OnlineMatchRewardOutboxRecord /// public string MatchId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置结果快照(重投时的发奖数据源;按失败玩家收窄后投递)。 @@ -109,8 +100,6 @@ public OnlineMatchRewardOutboxRecord Copy() { MatchResultId = MatchResultId, MatchId = MatchId, - TenantId = TenantId, - AppId = AppId, Result = Result == null ? null : Result.Copy(), Attempts = Attempts, NextAttemptTimeUnixMilliseconds = NextAttemptTimeUnixMilliseconds, diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntime.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntime.cs index 2cae4a37e..498248523 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntime.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntime.cs @@ -30,7 +30,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Globalization; using System.Threading; using System.Threading.Tasks; using GameFrameX.Capability.Online.Abstractions.Contracts; @@ -47,7 +46,7 @@ namespace GameFrameX.Capability.Online.Match; /// 且单个 Actor 的失败不会让其他对局状态不一致。 /// /// -/// 登记表单实例约束(红线):同一 (TenantId, AppId, MatchId) 至多一个 Actor 实例—— +/// 登记表单实例约束(红线):同一 MatchId 至多一个 Actor 实例—— /// 注册一律 GetOrAdd 收敛(并发装载/建局冲突时后到者复用在册实例), /// 保证同一对局的所有请求方与 Tick 快照共享同一引用,杜绝双实例写入冲突。 /// @@ -75,7 +74,7 @@ public sealed class OnlineMatchRuntime private readonly Dictionary _games = new(); /// - /// Actor 登记表:键 = (TenantId, AppId, MatchId)。 + /// Actor 登记表:键 = MatchId。 /// /// 单实例不变量(红线):同一键至多一个 Actor 实例。注册一律走 GetOrAdd—— /// 并发装载/建局冲突时先到者胜出,后到者放弃本次构造的实例并复用在册实例; @@ -180,8 +179,6 @@ public async Task> CreateFromAssignmentAsync(O var match = new OnlineMatch { - TenantId = assignment.TenantId, - AppId = assignment.AppId, ServerId = assignment.ServerId, MatchId = assignment.MatchId, AssignmentId = assignment.AssignmentId ?? string.Empty, @@ -225,7 +222,7 @@ public async Task> CreateFromAssignmentAsync(O var actor = new OnlineMatchActor(persisted, game, _store, _eventPublisher, _options); // GetOrAdd 单实例收敛:并发解析可能已装载同键 Actor(本方落库后、注册前), // 此时放弃本次构造的实例、回执走复用路径,严禁盲写覆盖产生孤儿。 - var registered = _actors.GetOrAdd(BuildKey(persisted.TenantId, persisted.AppId, persisted.MatchId), actor); + var registered = _actors.GetOrAdd(persisted.MatchId ?? string.Empty, actor); return OnlineResult.Ok(registered.GetSnapshot()); } @@ -233,25 +230,23 @@ public async Task> CreateFromAssignmentAsync(O /// /// 取得(必要时装载)指定对局的 Actor。 /// - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 取消令牌。 /// 对局 Actor;不存在或未注册玩法返回 null。 - public async Task ResolveActorAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default) + public async Task ResolveActorAsync(string matchId, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(matchId)) { return null; } - var key = BuildKey(tenantId, appId, matchId); + var key = matchId; if (_actors.TryGetValue(key, out var cached)) { return cached; } - var match = await _store.FindAsync(tenantId, appId, matchId, cancellationToken).ConfigureAwait(false); + var match = await _store.FindAsync(matchId, cancellationToken).ConfigureAwait(false); if (match == null) { return null; @@ -294,7 +289,7 @@ public async Task> TickAllAsync(long nowUni continue; } - var key = BuildKey(actor.TenantId, actor.AppId, actor.MatchId); + var key = actor.MatchId; // 原子条件移除:仅当在册实例仍是本快照实例时摘除(并发 Tick / 重装载竞争下不误删他人)。 if (_actors.TryRemove(new KeyValuePair(key, actor))) @@ -302,26 +297,10 @@ public async Task> TickAllAsync(long nowUni Interlocked.Increment(ref _releasedActorCount); } - await _store.DeleteAsync(actor.TenantId, actor.AppId, actor.MatchId, cancellationToken).ConfigureAwait(false); + await _store.DeleteAsync(actor.MatchId, cancellationToken).ConfigureAwait(false); } return results; } - /// - /// 构造作用域隔离键。 - /// - /// 租户标识。 - /// App 标识。 - /// 对局标识。 - /// 复合键。 - private static string BuildKey(long tenantId, long appId, string matchId) - { - return string.Concat( - tenantId.ToString(CultureInfo.InvariantCulture), - ":", - appId.ToString(CultureInfo.InvariantCulture), - ":", - matchId ?? string.Empty); - } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntimeEvents.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntimeEvents.cs index 759750d18..c85db9933 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntimeEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntimeEvents.cs @@ -61,8 +61,6 @@ public static class OnlineMatchRuntimeEvents /// /// 构造对局生命周期状态变更事件。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 对局标识(可空;载荷落空字符串)。 /// 来源分配标识(可空;载荷落空字符串)。 @@ -71,7 +69,7 @@ public static class OnlineMatchRuntimeEvents /// 变更时的服务器序号。 /// 成员数(含断线成员)。 /// 事件信封实例。 - public static OnlineEvent CreateMatchStateChanged(long tenantId, long appId, long serverId, string matchId, string assignmentId, string fromState, string toState, long serverSequence, int memberCount) + public static OnlineEvent CreateMatchStateChanged(long serverId, string matchId, string assignmentId, string fromState, string toState, long serverSequence, int memberCount) { var payload = new MatchStateChangedPayload { @@ -97,8 +95,6 @@ public static OnlineEvent CreateMatchStateChanged(long tenantId, long appId, lon EventType = MatchStateChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = 0, Source = Source, @@ -111,8 +107,6 @@ public static OnlineEvent CreateMatchStateChanged(long tenantId, long appId, lon /// /// 构造对局结算完成事件(可信结果事件)。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 结果标识(可空;载荷落空字符串)。 /// 对局标识(可空;载荷落空字符串)。 @@ -123,7 +117,7 @@ public static OnlineEvent CreateMatchStateChanged(long tenantId, long appId, lon /// 玩家条目集合(标识 / 名次 / 是否胜方 / 得分 / 奖励条目数;空元素被跳过)。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateMatchSettled(long tenantId, long appId, long serverId, string matchResultId, string matchId, int mode, int region, string outcome, long settledTime, IReadOnlyList<(long PlayerId, int Rank, bool IsWinner, long Score, int RewardCount)> entries, string correlationId = null) + public static OnlineEvent CreateMatchSettled(long serverId, string matchResultId, string matchId, int mode, int region, string outcome, long settledTime, IReadOnlyList<(long PlayerId, int Rank, bool IsWinner, long Score, int RewardCount)> entries, string correlationId = null) { var entryPayloads = new List(); var winnerCount = 0; @@ -173,8 +167,6 @@ public static OnlineEvent CreateMatchSettled(long tenantId, long appId, long ser EventType = MatchSettled, OccurredTime = settledTime > 0 ? settledTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = 0, Source = Source, @@ -191,8 +183,6 @@ public static OnlineEvent CreateMatchSettled(long tenantId, long appId, long ser /// 消费端(风控)据此告警或画像,不得回写对局。 /// /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 结果标识(可空;载荷落空字符串)。 /// 对局标识(可空;载荷落空字符串)。 @@ -202,7 +192,7 @@ public static OnlineEvent CreateMatchSettled(long tenantId, long appId, long ser /// 结算时刻(UTC 毫秒)。 /// 玩家条目集合(标识 / 名次 / 是否胜方 / 得分 / 奖励条目数;空元素被跳过)。 /// 事件信封实例。 - public static OnlineEvent CreateMatchParticipationRewardsSuppressed(long tenantId, long appId, long serverId, string matchResultId, string matchId, int mode, int region, string outcome, long settledTime, IReadOnlyList<(long PlayerId, int Rank, bool IsWinner, long Score, int RewardCount)> entries) + public static OnlineEvent CreateMatchParticipationRewardsSuppressed(long serverId, string matchResultId, string matchId, int mode, int region, string outcome, long settledTime, IReadOnlyList<(long PlayerId, int Rank, bool IsWinner, long Score, int RewardCount)> entries) { var entryPayloads = new List(); if (entries != null) @@ -245,8 +235,6 @@ public static OnlineEvent CreateMatchParticipationRewardsSuppressed(long tenantI EventType = MatchParticipationRewardsSuppressed, OccurredTime = settledTime > 0 ? settledTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = 0, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchSettlementPipeline.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchSettlementPipeline.cs index 05ea13c6b..641c9fcbc 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchSettlementPipeline.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchSettlementPipeline.cs @@ -129,7 +129,7 @@ public async Task TickAsync(long nowUnixMilliseconds, CancellationToken cancella // 逐对局异常隔离(GFX-1116):单对局结算异常不得中断同轮其他对局。 try { - await _settlementService.SettleAsync(actor.TenantId, actor.AppId, actor.MatchId, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false); + await _settlementService.SettleAsync(actor.MatchId, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchSettlementService.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchSettlementService.cs index 291c985bf..c1041a0dd 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchSettlementService.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchSettlementService.cs @@ -82,20 +82,18 @@ public OnlineMatchSettlementService(OnlineMatchRuntime runtime, IOnlineMatchSett /// /// 对指定对局执行结算(幂等)。 /// - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 当前时刻(UTC 毫秒)。 /// 取消令牌。 /// 结算执行结果;失败返回对应错误码。 - public async Task> SettleAsync(long tenantId, long appId, string matchId, long nowUnixMilliseconds, CancellationToken cancellationToken = default) + public async Task> SettleAsync(string matchId, long nowUnixMilliseconds, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(matchId)) { return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "对局标识不能为空"); } - var existing = await _settlementStore.FindByMatchAsync(tenantId, appId, matchId, cancellationToken).ConfigureAwait(false); + var existing = await _settlementStore.FindByMatchAsync(matchId, cancellationToken).ConfigureAwait(false); if (existing != null) { return OnlineResult.Ok(new OnlineMatchSettlementOutcome @@ -106,7 +104,7 @@ public async Task> SettleAsync(long t }); } - var actor = await _runtime.ResolveActorAsync(tenantId, appId, matchId, cancellationToken).ConfigureAwait(false); + var actor = await _runtime.ResolveActorAsync(matchId, cancellationToken).ConfigureAwait(false); if (actor == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "对局不存在"); @@ -160,11 +158,11 @@ private async Task CompleteAndPublishAsync(OnlineMatchActor actor, OnlineMatchRe var entries = committed.Entries == null ? null : committed.Entries.Where(entry => entry != null).Select(entry => (entry.PlayerId, entry.Rank, entry.IsWinner, entry.Score, entry.Rewards == null ? 0 : entry.Rewards.Count)).ToList(); - await PublishAsync(OnlineMatchRuntimeEvents.CreateMatchSettled(committed.TenantId, committed.AppId, committed.ServerId, committed.MatchResultId, committed.MatchId, committed.Mode, committed.Region, committed.Outcome.ToString(), committed.SettledTime, entries), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineMatchRuntimeEvents.CreateMatchSettled(committed.ServerId, committed.MatchResultId, committed.MatchId, committed.Mode, committed.Region, committed.Outcome.ToString(), committed.SettledTime, entries), cancellationToken).ConfigureAwait(false); if (committed.ParticipationRewardsSuppressed) { // 挂机刷奖可疑信号:存在零有效出拳玩家的结算,外发风控事件(发布失败不改变已落定的结算事实)。 - await PublishAsync(OnlineMatchRuntimeEvents.CreateMatchParticipationRewardsSuppressed(committed.TenantId, committed.AppId, committed.ServerId, committed.MatchResultId, committed.MatchId, committed.Mode, committed.Region, committed.Outcome.ToString(), committed.SettledTime, entries), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineMatchRuntimeEvents.CreateMatchParticipationRewardsSuppressed(committed.ServerId, committed.MatchResultId, committed.MatchId, committed.Mode, committed.Region, committed.Outcome.ToString(), committed.SettledTime, entries), cancellationToken).ConfigureAwait(false); } } diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/AdminApi/OnlineAdminMatchmakingHandlers.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/AdminApi/OnlineAdminMatchmakingHandlers.cs index c024f87be..d60965e6c 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/AdminApi/OnlineAdminMatchmakingHandlers.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/AdminApi/OnlineAdminMatchmakingHandlers.cs @@ -92,7 +92,7 @@ public async Task QueryMatchQueueOverviewAsync(AdminApiRequest request, { var modeFilter = OnlineAdminApiContract.ReadOptionalString(request, "Mode"); var regionFilter = OnlineAdminApiContract.ReadOptionalString(request, "Region"); - var snapshot = OnlineAdminApiContract.Unwrap(await _matchQueueObserver.ObserveAsync(scope.TenantId, scope.AppId, 0, cancellationToken).ConfigureAwait(false)); + var snapshot = OnlineAdminApiContract.Unwrap(await _matchQueueObserver.ObserveAsync(0, cancellationToken).ConfigureAwait(false)); var nowMilliseconds = OnlineAdminApiContract.NowSeconds() * 1000; var queues = new List(); if (snapshot.Tickets != null) @@ -144,7 +144,7 @@ public async Task QueryMatchTicketFailuresAsync(AdminApiRequest request, var endTime = OnlineAdminApiContract.ReadOptionalInt64(request, "EndTime"); var pageSize = OnlineAdminApiContract.ReadPageSize(request); var cursor = OnlineAdminApiContract.ReadCursor(request); - var tickets = await _matchTicketStore.ListAllAsync(scope.TenantId, scope.AppId, cancellationToken).ConfigureAwait(false); + var tickets = await _matchTicketStore.ListAllAsync(cancellationToken).ConfigureAwait(false); var failed = tickets .Where(ticket => ticket.FailureReason != OnlineMatchFailureReason.None || ticket.State == OnlineMatchTicketState.Expired @@ -218,7 +218,7 @@ public async Task QueryMatchAbnormalTicketsAsync(AdminApiRequest request var pageSize = OnlineAdminApiContract.ReadPageSize(request); var cursor = OnlineAdminApiContract.ReadCursor(request); - var tickets = await _matchTicketStore.ListAllAsync(scope.TenantId, scope.AppId, cancellationToken).ConfigureAwait(false); + var tickets = await _matchTicketStore.ListAllAsync(cancellationToken).ConfigureAwait(false); var nowMilliseconds = OnlineAdminApiContract.NowSeconds() * 1000; List abnormal; if (abnormalKind.Value == 2) @@ -286,7 +286,7 @@ public async Task CancelMatchTicketAsync(AdminApiRequest request, Online { var ticketId = OnlineAdminApiContract.RequireString(request, "TicketId"); var reason = OnlineAdminApiContract.RequireString(request, "Reason"); - var ticket = await _matchTicketStore.FindAsync(scope.TenantId, scope.AppId, ticketId, cancellationToken).ConfigureAwait(false); + var ticket = await _matchTicketStore.FindAsync(ticketId, cancellationToken).ConfigureAwait(false); if (ticket == null) { // Localization: Online.AdminApi.MatchTicketNotFound - 匹配票据不存在:{0} @@ -294,7 +294,7 @@ public async Task CancelMatchTicketAsync(AdminApiRequest request, Online } var ticketScope = ticket.PlayerIds != null && ticket.PlayerIds.Count > 0 - ? new OnlineScope(scope.TenantId, scope.AppId, scope.ServerId, ticket.PlayerIds[0]) + ? new OnlineScope(scope.ServerId, ticket.PlayerIds[0]) : scope; OnlineAdminApiContract.Unwrap(await _matchTickets.CancelAsync(ticketScope, ticketId, cancellationToken).ConfigureAwait(false)); return OnlineAdminApiContract.BuildControlledAck(request, ticketId, "Ticket cancelled. Reason: " + reason); @@ -405,7 +405,7 @@ private async Task> CollectOrphanViewsAsync(IReadOnlyLi continue; } - var assignment = await _matchTicketStore.FindAssignmentAsync(scope.TenantId, scope.AppId, ticket.AssignmentId, cancellationToken).ConfigureAwait(false); + var assignment = await _matchTicketStore.FindAssignmentAsync(ticket.AssignmentId, cancellationToken).ConfigureAwait(false); if (assignment == null) { views.Add(new AbnormalTicketView(ticket, null, null)); diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchEventOutbox.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchEventOutbox.cs index 2549e736a..2b8343bb3 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchEventOutbox.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchEventOutbox.cs @@ -53,22 +53,18 @@ public interface IOnlineMatchEventOutbox Task AppendAsync(IReadOnlyList events, CancellationToken cancellationToken = default); /// - /// 列出作用域内全部待投递条目(按写入顺序)。 + /// 列出全部待投递条目(按写入顺序)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 待投递条目列表;无则空列表。 - Task> ListPendingAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListPendingAsync(CancellationToken cancellationToken = default); /// /// 标记条目已投递(条目不存在时静默返回——重投竞态下对端可能已标记)。 /// - /// 租户标识。 - /// App 标识。 /// 事件标识。 /// 取消令牌。 /// 完成通知。 - Task MarkDeliveredAsync(long tenantId, long appId, string eventId, CancellationToken cancellationToken = default); + Task MarkDeliveredAsync(string eventId, CancellationToken cancellationToken = default); } diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchListingStore.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchListingStore.cs index c9048a76e..a1aaf5017 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchListingStore.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchListingStore.cs @@ -69,19 +69,15 @@ public interface IOnlineMatchListingStore /// /// 按标识查找列表项。 /// - /// 租户标识。 - /// App 标识。 /// 列表项标识。 /// 取消令牌。 /// 列表项副本;不存在返回 null。 - Task FindAsync(long tenantId, long appId, string listingId, CancellationToken cancellationToken = default); + Task FindAsync(string listingId, CancellationToken cancellationToken = default); /// /// 列出作用域内全部列表项(过滤与封顶由服务层执行)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 列表项副本列表。 - Task> ListAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListAsync(CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchTicketStore.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchTicketStore.cs index 48750629d..429cb23c7 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchTicketStore.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/IOnlineMatchTicketStore.cs @@ -58,7 +58,7 @@ public interface IOnlineMatchTicketStore /// 原子入队:在同一临界区内检查队伍和每个成员是否已有排队中票据; /// 没有冲突就写入票据和反查索引并返回入参副本,有冲突就不写入,返回已存在的活跃票据。 /// - /// 未来接持久化存储时,以(租户、应用、玩家、活跃)唯一索引承接同一约束; + /// 未来接持久化存储时,以(玩家、活跃)唯一索引承接同一约束; /// 冲突路径不得留下任何写入痕迹(包括玩家反查索引)。 /// /// @@ -70,32 +70,26 @@ public interface IOnlineMatchTicketStore /// /// 按标识查找票据(含终态历史)。 /// - /// 租户标识。 - /// App 标识。 /// 票据标识。 /// 取消令牌。 /// 票据副本;不存在返回 null。 - Task FindAsync(long tenantId, long appId, string ticketId, CancellationToken cancellationToken = default); + Task FindAsync(string ticketId, CancellationToken cancellationToken = default); /// /// 查找队伍/玩家当前处于排队中的票据(唯一性:同一队伍至多一张活跃票据)。 /// - /// 租户标识。 - /// App 标识。 /// 队伍标识。 /// 取消令牌。 /// 排队中的票据副本;无则返回 null。 - Task FindActiveByPartyAsync(long tenantId, long appId, string partyId, CancellationToken cancellationToken = default); + Task FindActiveByPartyAsync(string partyId, CancellationToken cancellationToken = default); /// /// 查找玩家当前处于排队中的票据(用于重复排队拦截与「我的匹配状态」查询)。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 排队中的票据副本;无则返回 null。 - Task FindActiveByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task FindActiveByPlayerAsync(long playerId, CancellationToken cancellationToken = default); /// /// 查找玩家最近一张票据(任意状态;匹配域桥状态面读)。 @@ -104,40 +98,32 @@ public interface IOnlineMatchTicketStore /// 排队中为 Queued 票据,已撮合为 Matched 终态票据(承载 AssignmentId),取消 / 过期为对应终态。 /// /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 最近票据副本;从未入队返回 null。 - Task FindLatestByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task FindLatestByPlayerAsync(long playerId, CancellationToken cancellationToken = default); /// /// 列出作用域内排队中的全部票据(成组与过期扫描的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 排队中的票据副本列表。 - Task> ListQueuedAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListQueuedAsync(CancellationToken cancellationToken = default); /// /// 列出作用域内全部票据(含终态历史;可观测性要求各状态计数可核对)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 票据副本列表。 - Task> ListAllAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListAllAsync(CancellationToken cancellationToken = default); /// /// 以 CAS 语义更新单张票据状态(取消 / 过期 / 失败走此入口)。 /// - /// 租户标识。 - /// App 标识。 /// 状态迁移载荷(票据定位 + 期望/目标状态 + 失败原因与分配标识)。 /// 取消令牌。 /// 更新后的票据副本;CAS 失败或票据不存在返回 null。 - Task UpdateStateAsync(long tenantId, long appId, MatchTicketStateTransition transition, CancellationToken cancellationToken = default); + Task UpdateStateAsync(MatchTicketStateTransition transition, CancellationToken cancellationToken = default); /// /// 原子提交一次成组:校验全部票据仍处于期望状态,是则一次性全部置为 @@ -154,44 +140,36 @@ public interface IOnlineMatchTicketStore /// /// 按标识查找对局分配。 /// - /// 租户标识。 - /// App 标识。 /// 分配标识。 /// 取消令牌。 /// 分配副本;不存在返回 null。 - Task FindAssignmentAsync(long tenantId, long appId, string assignmentId, CancellationToken cancellationToken = default); + Task FindAssignmentAsync(string assignmentId, CancellationToken cancellationToken = default); /// /// 列出作用域内全部对局分配(可观测性与对账用)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 分配副本列表。 - Task> ListAssignmentsAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListAssignmentsAsync(CancellationToken cancellationToken = default); /// - /// 聚合作用域 (TenantId, AppId, ServerId) 内排队态票据,按 (Mode, Region) 槽位产出队列深度与等待时长合计 + /// 聚合作用域 (ServerId) 内排队态票据,按 (Mode, Region) 槽位产出队列深度与等待时长合计 /// (聚合谓词下推:排队态判定与等待秒来源 均与在线总览口径一致)。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 观测时刻(UTC 毫秒;等待时长按该时刻计算)。 /// 取消令牌。 /// 槽位聚合列表(无排队票据时为空表)。 - Task> AggregateQueuedBySlotAsync(long tenantId, long appId, long serverId, long nowUnixMilliseconds, CancellationToken cancellationToken = default); + Task> AggregateQueuedBySlotAsync(long serverId, long nowUnixMilliseconds, CancellationToken cancellationToken = default); /// /// 统计时间窗 (windowStartExclusiveUnixMilliseconds, windowEndInclusiveUnixMilliseconds] 内落档的匹配分配所消费的票据数, /// 按 (Mode, Region) 槽位聚合(聚合谓词下推:窗口左开右闭边界与在线总览吞吐口径一致)。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 窗口起点(UTC 毫秒;不含)。 /// 窗口终点(UTC 毫秒;含)。 /// 取消令牌。 /// 槽位聚合列表(TotalWaitSeconds 恒为 0;窗口内无分配时为空表)。 - Task> CountAssignmentTicketsBySlotAsync(long tenantId, long appId, long serverId, long windowStartExclusiveUnixMilliseconds, long windowEndInclusiveUnixMilliseconds, CancellationToken cancellationToken = default); + Task> CountAssignmentTicketsBySlotAsync(long serverId, long windowStartExclusiveUnixMilliseconds, long windowEndInclusiveUnixMilliseconds, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchEventOutbox.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchEventOutbox.cs index bea340f04..6351a59f5 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchEventOutbox.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchEventOutbox.cs @@ -36,7 +36,7 @@ namespace GameFrameX.Capability.Online.Matchmaking; using GameFrameX.Capability.Online.Abstractions.Events; /// -/// 匹配事件发件箱内存实现(C374;单锁串行,条目以 (TenantId, AppId, EventId) 为主键幂等追加)。 +/// 匹配事件发件箱内存实现(C374;单锁串行,条目以 EventId 为主键幂等追加)。 /// /// 维护约束:条目一旦投递成功即标记 Delivered 且不再出现在 结果中; /// 追加按 EventId 幂等(重复标识跳过不覆盖),保证重放写入不产生重复投递义务。 @@ -49,9 +49,8 @@ public sealed class InMemoryOnlineMatchEventOutbox : IOnlineMatchEventOutbox /// 并发保护锁(追加 / 查询 / 标记共用一个临界区)。 private readonly object _syncRoot = new object(); - /// 发件箱条目表(键 = TenantId:AppId:EventId)。 + /// 发件箱条目表(键 = EventId)。 private readonly Dictionary _entries = new Dictionary(); - /// 追加序号(同刻写入的稳定排序兜底)。 private long _sequence; @@ -77,7 +76,7 @@ public Task AppendAsync(IReadOnlyList events, CancellationToken can continue; } - var key = BuildKey(onlineEvent.TenantId, onlineEvent.AppId, onlineEvent.EventId); + var key = onlineEvent.EventId; if (_entries.ContainsKey(key)) { continue; @@ -86,8 +85,6 @@ public Task AppendAsync(IReadOnlyList events, CancellationToken can _entries[key] = new OnlineMatchEventOutboxEntry { EventId = onlineEvent.EventId, - TenantId = onlineEvent.TenantId, - AppId = onlineEvent.AppId, Event = onlineEvent, Delivered = false, SequenceNumber = Interlocked.Increment(ref _sequence), @@ -99,13 +96,11 @@ public Task AppendAsync(IReadOnlyList events, CancellationToken can } /// - /// 列出作用域内全部待投递条目(按登记顺序;不含已投递条目)。 + /// 列出全部待投递条目(按登记顺序;不含已投递条目)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 待投递条目列表。 - public Task> ListPendingAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListPendingAsync(CancellationToken cancellationToken = default) { var pending = new List(); @@ -113,7 +108,7 @@ public Task> ListPendingAsync(long te { foreach (var entry in _entries.Values) { - if (entry.TenantId == tenantId && entry.AppId == appId && !entry.Delivered) + if (!entry.Delivered) { pending.Add(entry); } @@ -128,12 +123,10 @@ public Task> ListPendingAsync(long te /// /// 标记条目已投递;条目不存在时静默返回(重投竞态下对端可能已标记/清理)。 /// - /// 租户标识。 - /// App 标识。 /// 事件标识。 /// 取消令牌。 /// 完成通知。 - public Task MarkDeliveredAsync(long tenantId, long appId, string eventId, CancellationToken cancellationToken = default) + public Task MarkDeliveredAsync(string eventId, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(eventId)) { @@ -142,7 +135,7 @@ public Task MarkDeliveredAsync(long tenantId, long appId, string eventId, Cancel lock (_syncRoot) { - var key = BuildKey(tenantId, appId, eventId); + var key = eventId; if (_entries.TryGetValue(key, out var entry)) { entry.Delivered = true; @@ -152,15 +145,4 @@ public Task MarkDeliveredAsync(long tenantId, long appId, string eventId, Cancel return Task.CompletedTask; } - /// - /// 构造条目主键(TenantId:AppId:EventId)。 - /// - /// 租户标识。 - /// App 标识。 - /// 事件标识。 - /// 条目主键。 - private static string BuildKey(long tenantId, long appId, string eventId) - { - return tenantId.ToString() + ":" + appId.ToString() + ":" + eventId; - } } diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchListingStore.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchListingStore.cs index f1fc3e03e..c45f59878 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchListingStore.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchListingStore.cs @@ -40,7 +40,7 @@ public sealed class InMemoryOnlineMatchListingStore : IOnlineMatchListingStore /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 列表项表:键 = (TenantId, AppId, ListingId)。 + /// 列表项表:键 = ListingId。 private readonly Dictionary _listings = new(); /// 保存列表项(深拷贝入库)。 @@ -55,7 +55,7 @@ public Task SaveAsync(OnlineMatchListing listing, CancellationToken cancellation lock (_syncRoot) { - _listings[BuildKey(listing.TenantId, listing.AppId, listing.ListingId)] = listing.Copy(); + _listings[listing.ListingId] = listing.Copy(); } return Task.CompletedTask; @@ -75,7 +75,7 @@ public Task UpdateIfRowVersionAsync(OnlineMatchListing listing, long expec lock (_syncRoot) { - var key = BuildKey(listing.TenantId, listing.AppId, listing.ListingId); + var key = listing.ListingId; if (!_listings.TryGetValue(key, out var existing) || existing.RowVersion != expectedRowVersion) { return Task.FromResult(false); @@ -89,49 +89,32 @@ public Task UpdateIfRowVersionAsync(OnlineMatchListing listing, long expec } /// 按标识查找列表项。 - /// 租户标识。 - /// App 标识。 /// 列表项标识。 /// 取消令牌。 /// 列表项副本;不存在返回 null。 - public Task FindAsync(long tenantId, long appId, string listingId, CancellationToken cancellationToken = default) + public Task FindAsync(string listingId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - _listings.TryGetValue(BuildKey(tenantId, appId, listingId), out var listing); + _listings.TryGetValue(listingId, out var listing); return Task.FromResult(listing == null ? null : listing.Copy()); } } - /// 列出作用域内全部列表项。 - /// 租户标识。 - /// App 标识。 + /// 列出全部列表项。 /// 取消令牌。 /// 列表项副本列表。 - public Task> ListAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAsync(CancellationToken cancellationToken = default) { lock (_syncRoot) { var result = new List(); foreach (var listing in _listings.Values) { - if (listing.TenantId == tenantId && listing.AppId == appId) - { - result.Add(listing.Copy()); - } + result.Add(listing.Copy()); } return Task.FromResult>(result); } } - - /// 构造存储键。 - /// 租户标识。 - /// App 标识。 - /// 列表项标识。 - /// 复合键字符串。 - private static string BuildKey(long tenantId, long appId, string listingId) - { - return tenantId + ":" + appId + ":" + listingId; - } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchTicketStore.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchTicketStore.cs index ba55b17a0..ace44f80c 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchTicketStore.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/InMemoryOnlineMatchTicketStore.cs @@ -39,7 +39,7 @@ namespace GameFrameX.Capability.Online.Matchmaking; /// /// /// 天花板:单锁全串行,票据基数上万后成组扫描会成为热点; -/// 升级路径是按 (TenantId, AppId) 分片加锁并保留同样的 CAS 语义,调用方无感。 +/// 升级路径是按键前缀分片加锁并保留同样的 CAS 语义,调用方无感。 /// /// public sealed class InMemoryOnlineMatchTicketStore : IOnlineMatchTicketStore @@ -47,13 +47,13 @@ public sealed class InMemoryOnlineMatchTicketStore : IOnlineMatchTicketStore /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 票据表:键 = (TenantId, AppId, TicketId)。 + /// 票据表:键 = TicketId。 private readonly Dictionary _tickets = new(); - /// 玩家反查索引:键 = (TenantId, AppId, PlayerId),值 = 其排队中票据标识。 + /// 玩家反查索引:键 = PlayerId,值 = 其排队中票据标识。 private readonly Dictionary _playerIndex = new(); - /// 对局分配表:键 = (TenantId, AppId, AssignmentId)。 + /// 对局分配表:键 = AssignmentId。 private readonly Dictionary _assignments = new(); /// @@ -75,7 +75,7 @@ public Task SaveAsync(OnlineMatchTicket ticket, CancellationToken cancellationTo lock (_syncRoot) { - _tickets[BuildKey(ticket.TenantId, ticket.AppId, ticket.TicketId)] = ticket.Copy(); + _tickets[ticket.TicketId] = ticket.Copy(); if (ticket.State == OnlineMatchTicketState.Queued) { IndexPlayers(ticket); @@ -109,7 +109,7 @@ public Task TryEnqueueIfAbsentAsync(OnlineMatchTicket ticket, // 队伍维度先查:同一队伍至多一张活跃票据,命中即整体拒绝。 if (!string.IsNullOrEmpty(ticket.PartyId)) { - var conflictingParty = FindActiveByPartyInternal(ticket.TenantId, ticket.AppId, ticket.PartyId); + var conflictingParty = FindActiveByPartyInternal(ticket.PartyId); if (conflictingParty != null) { return Task.FromResult(conflictingParty); @@ -121,7 +121,7 @@ public Task TryEnqueueIfAbsentAsync(OnlineMatchTicket ticket, { foreach (var playerId in ticket.PlayerIds) { - var conflictingPlayer = FindActiveByPlayerInternal(ticket.TenantId, ticket.AppId, playerId); + var conflictingPlayer = FindActiveByPlayerInternal(playerId); if (conflictingPlayer != null) { return Task.FromResult(conflictingPlayer); @@ -131,7 +131,7 @@ public Task TryEnqueueIfAbsentAsync(OnlineMatchTicket ticket, // 存档存副本而非调用方实例(调用方复用该实例不会回写库内记录)。 var stored = ticket.Copy(); - _tickets[BuildKey(stored.TenantId, stored.AppId, stored.TicketId)] = stored; + _tickets[stored.TicketId] = stored; if (stored.State == OnlineMatchTicketState.Queued) { IndexPlayers(stored); @@ -147,16 +147,14 @@ public Task TryEnqueueIfAbsentAsync(OnlineMatchTicket ticket, /// /// Reads a copy of the ticket from the in-memory ticket table by scope and ticket id, including terminal-state history. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 票据标识 / Ticket id /// 取消令牌 / Cancellation token /// 票据副本;不存在返回 null / A copy of the ticket, or null when not found - public Task FindAsync(long tenantId, long appId, string ticketId, CancellationToken cancellationToken = default) + public Task FindAsync(string ticketId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(FindInternal(tenantId, appId, ticketId)); + return Task.FromResult(FindInternal(ticketId)); } } @@ -166,12 +164,10 @@ public Task FindAsync(long tenantId, long appId, string ticke /// /// Scans the in-memory ticket table and returns a copy of the first queued ticket whose party id matches within the scope; returns null immediately when is empty. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 队伍标识 / Party id /// 取消令牌 / Cancellation token /// 排队中的票据副本;无则返回 null / A copy of the queued ticket, or null when none exists - public Task FindActiveByPartyAsync(long tenantId, long appId, string partyId, CancellationToken cancellationToken = default) + public Task FindActiveByPartyAsync(string partyId, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(partyId)) { @@ -180,7 +176,7 @@ public Task FindActiveByPartyAsync(long tenantId, long appId, lock (_syncRoot) { - return Task.FromResult(FindActiveByPartyInternal(tenantId, appId, partyId)); + return Task.FromResult(FindActiveByPartyInternal(partyId)); } } @@ -190,16 +186,14 @@ public Task FindActiveByPartyAsync(long tenantId, long appId, /// /// Locates the ticket id through the player reverse-lookup index, verifies the ticket is still queued, and returns its copy. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌 / Cancellation token /// 排队中的票据副本;无则返回 null / A copy of the queued ticket, or null when none exists - public Task FindActiveByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task FindActiveByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(FindActiveByPlayerInternal(tenantId, appId, playerId)); + return Task.FromResult(FindActiveByPlayerInternal(playerId)); } } @@ -210,19 +204,17 @@ public Task FindActiveByPlayerAsync(long tenantId, long appId /// Locates the ticket id through the player reverse-lookup index and returns its copy regardless of state /// (the latest matching attempt; the match-domain bridge status face). /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌 / Cancellation token /// 最近票据副本;从未入队返回 null / A copy of the latest ticket, or null when the player never enqueued - public Task FindLatestByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task FindLatestByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { OnlineMatchTicket latest = null; foreach (var ticket in _tickets.Values) { - if (ticket.TenantId != tenantId || ticket.AppId != appId || ticket.PlayerIds == null || !ticket.PlayerIds.Contains(playerId)) + if (ticket.PlayerIds == null || !ticket.PlayerIds.Contains(playerId)) { continue; } @@ -246,11 +238,9 @@ public Task FindLatestByPlayerAsync(long tenantId, long appId /// /// Iterates the in-memory ticket table and collects copies of all queued tickets within the scope. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 取消令牌 / Cancellation token /// 排队中的票据副本列表 / The list of queued ticket copies - public Task> ListQueuedAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListQueuedAsync(CancellationToken cancellationToken = default) { var queued = new List(); @@ -258,7 +248,7 @@ public Task> ListQueuedAsync(long tenantId, lon { foreach (var ticket in _tickets.Values) { - if (ticket.TenantId == tenantId && ticket.AppId == appId && ticket.State == OnlineMatchTicketState.Queued) + if (ticket.State == OnlineMatchTicketState.Queued) { queued.Add(ticket.Copy()); } @@ -274,11 +264,9 @@ public Task> ListQueuedAsync(long tenantId, lon /// /// Iterates the in-memory ticket table and collects copies of all tickets within the scope, including terminal-state history. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 取消令牌 / Cancellation token /// 票据副本列表 / The list of ticket copies - public Task> ListAllAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAllAsync(CancellationToken cancellationToken = default) { var tickets = new List(); @@ -286,10 +274,7 @@ public Task> ListAllAsync(long tenantId, long a { foreach (var ticket in _tickets.Values) { - if (ticket.TenantId == tenantId && ticket.AppId == appId) - { - tickets.Add(ticket.Copy()); - } + tickets.Add(ticket.Copy()); } } @@ -302,12 +287,10 @@ public Task> ListAllAsync(long tenantId, long a /// /// Updates a single ticket state with CAS semantics: returns null without leaving any write trace when the ticket is missing or its current state does not match the expected one; on success writes the new state, failure reason and assignment id, and releases the player reverse-lookup index when leaving the queued state. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 状态 CAS 迁移载荷(票据标识 / 期望状态 / 目标状态 / 失败原因 / 分配标识)/ The ticket state CAS transition payload (ticket id, expected state, target state, failure reason, assignment id) /// 取消令牌 / Cancellation token /// 更新后的票据副本;CAS 失败或票据不存在返回 null / A copy of the updated ticket, or null when the CAS fails or the ticket does not exist - public Task UpdateStateAsync(long tenantId, long appId, MatchTicketStateTransition transition, CancellationToken cancellationToken = default) + public Task UpdateStateAsync(MatchTicketStateTransition transition, CancellationToken cancellationToken = default) { var ticketId = transition.TicketId; var expectedState = transition.ExpectedState; @@ -316,13 +299,13 @@ public Task UpdateStateAsync(long tenantId, long appId, Match var assignmentId = transition.AssignmentId; lock (_syncRoot) { - var current = FindInternal(tenantId, appId, ticketId); + var current = FindInternal(ticketId); if (current == null || current.State != expectedState) { return Task.FromResult(null); } - var stored = _tickets[BuildKey(tenantId, appId, ticketId)]; + var stored = _tickets[ticketId]; stored.State = newState; stored.FailureReason = failureReason; stored.AssignmentId = string.IsNullOrEmpty(assignmentId) ? stored.AssignmentId : assignmentId; @@ -372,13 +355,13 @@ public Task CommitMatchAsync(OnlineMatchAssignment assign return Task.FromResult(null); } - var current = FindInternal(assignment.TenantId, assignment.AppId, ticketId); + var current = FindInternal(ticketId); if (current == null || current.State != expectedState) { return Task.FromResult(null); } - resolved.Add(_tickets[BuildKey(assignment.TenantId, assignment.AppId, ticketId)]); + resolved.Add(_tickets[ticketId]); } var storedAssignment = assignment.Copy(); @@ -390,7 +373,7 @@ public Task CommitMatchAsync(OnlineMatchAssignment assign ReleasePlayers(stored); } - _assignments[BuildKey(assignment.TenantId, assignment.AppId, assignment.AssignmentId)] = storedAssignment; + _assignments[assignment.AssignmentId] = storedAssignment; return Task.FromResult(storedAssignment.Copy()); } @@ -402,12 +385,10 @@ public Task CommitMatchAsync(OnlineMatchAssignment assign /// /// Reads a copy of the assignment from the in-memory assignment table by scope and assignment id; returns null immediately when is empty. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 分配标识 / Assignment id /// 取消令牌 / Cancellation token /// 分配副本;不存在返回 null / A copy of the assignment, or null when not found - public Task FindAssignmentAsync(long tenantId, long appId, string assignmentId, CancellationToken cancellationToken = default) + public Task FindAssignmentAsync(string assignmentId, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(assignmentId)) { @@ -416,7 +397,7 @@ public Task FindAssignmentAsync(long tenantId, long appId lock (_syncRoot) { - if (_assignments.TryGetValue(BuildKey(tenantId, appId, assignmentId), out var assignment)) + if (_assignments.TryGetValue(assignmentId, out var assignment)) { return Task.FromResult(assignment.Copy()); } @@ -431,11 +412,9 @@ public Task FindAssignmentAsync(long tenantId, long appId /// /// Iterates the in-memory assignment table and collects copies of all match assignments within the scope. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 取消令牌 / Cancellation token /// 分配副本列表 / The list of assignment copies - public Task> ListAssignmentsAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAssignmentsAsync(CancellationToken cancellationToken = default) { var assignments = new List(); @@ -443,10 +422,7 @@ public Task> ListAssignmentsAsync(long tena { foreach (var assignment in _assignments.Values) { - if (assignment.TenantId == tenantId && assignment.AppId == appId) - { - assignments.Add(assignment.Copy()); - } + assignments.Add(assignment.Copy()); } } @@ -459,20 +435,18 @@ public Task> ListAssignmentsAsync(long tena /// /// Aggregates queued tickets by (Mode, Region) slot under the global lock, without producing entity copies. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 区服标识 / Server id /// 观测时刻(UTC 毫秒)/ Observation time (unix milliseconds) /// 取消令牌 / Cancellation token /// 槽位聚合列表 / The list of slot aggregates - public Task> AggregateQueuedBySlotAsync(long tenantId, long appId, long serverId, long nowUnixMilliseconds, CancellationToken cancellationToken = default) + public Task> AggregateQueuedBySlotAsync(long serverId, long nowUnixMilliseconds, CancellationToken cancellationToken = default) { var accumulator = new Dictionary(); lock (_syncRoot) { foreach (var ticket in _tickets.Values) { - if (ticket.TenantId != tenantId || ticket.AppId != appId || ticket.ServerId != serverId || ticket.State != OnlineMatchTicketState.Queued) + if (ticket.ServerId != serverId || ticket.State != OnlineMatchTicketState.Queued) { continue; } @@ -492,21 +466,19 @@ public Task> AggregateQueuedBySlotA /// /// Counts tickets consumed by assignments archived within the (start, end] window, grouped by (Mode, Region) slot under the global lock. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 区服标识 / Server id /// 窗口起点(UTC 毫秒;不含)/ Window start (unix milliseconds, exclusive) /// 窗口终点(UTC 毫秒;含)/ Window end (unix milliseconds, inclusive) /// 取消令牌 / Cancellation token /// 槽位聚合列表(TotalWaitSeconds 恒为 0)/ The list of slot aggregates (TotalWaitSeconds always 0) - public Task> CountAssignmentTicketsBySlotAsync(long tenantId, long appId, long serverId, long windowStartExclusiveUnixMilliseconds, long windowEndInclusiveUnixMilliseconds, CancellationToken cancellationToken = default) + public Task> CountAssignmentTicketsBySlotAsync(long serverId, long windowStartExclusiveUnixMilliseconds, long windowEndInclusiveUnixMilliseconds, CancellationToken cancellationToken = default) { var accumulator = new Dictionary(); lock (_syncRoot) { foreach (var assignment in _assignments.Values) { - if (assignment.TenantId != tenantId || assignment.AppId != appId || assignment.ServerId != serverId + if (assignment.ServerId != serverId || assignment.CreatedAtTime <= windowStartExclusiveUnixMilliseconds || assignment.CreatedAtTime > windowEndInclusiveUnixMilliseconds) { continue; @@ -542,18 +514,16 @@ private static OnlineMatchQueueSlotAggregate ResolveSlot(Dictionary /// 按标识读取票据副本(调用方必须已持有 )。 /// - /// 租户标识。 - /// App 标识。 /// 票据标识。 /// 票据副本;不存在返回 null。 - private OnlineMatchTicket FindInternal(long tenantId, long appId, string ticketId) + private OnlineMatchTicket FindInternal(string ticketId) { if (string.IsNullOrEmpty(ticketId)) { return null; } - if (_tickets.TryGetValue(BuildKey(tenantId, appId, ticketId), out var ticket)) + if (_tickets.TryGetValue(ticketId, out var ticket)) { return ticket.Copy(); } @@ -564,11 +534,9 @@ private OnlineMatchTicket FindInternal(long tenantId, long appId, string ticketI /// /// 按队伍标识读取其排队中票据副本(调用方必须已持有 ; 为空返回 null)。 /// - /// 租户标识。 - /// App 标识。 /// 队伍标识。 /// 票据副本;无则返回 null。 - private OnlineMatchTicket FindActiveByPartyInternal(long tenantId, long appId, string partyId) + private OnlineMatchTicket FindActiveByPartyInternal(string partyId) { if (string.IsNullOrEmpty(partyId)) { @@ -577,7 +545,7 @@ private OnlineMatchTicket FindActiveByPartyInternal(long tenantId, long appId, s foreach (var ticket in _tickets.Values) { - if (ticket.TenantId == tenantId && ticket.AppId == appId && ticket.State == OnlineMatchTicketState.Queued && ticket.PartyId == partyId) + if (ticket.State == OnlineMatchTicketState.Queued && ticket.PartyId == partyId) { return ticket.Copy(); } @@ -589,18 +557,16 @@ private OnlineMatchTicket FindActiveByPartyInternal(long tenantId, long appId, s /// /// 按玩家读取其排队中票据副本(调用方必须已持有 )。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 票据副本;无则返回 null。 - private OnlineMatchTicket FindActiveByPlayerInternal(long tenantId, long appId, long playerId) + private OnlineMatchTicket FindActiveByPlayerInternal(long playerId) { - if (!_playerIndex.TryGetValue(BuildKey(tenantId, appId, playerId.ToString()), out var ticketId)) + if (!_playerIndex.TryGetValue(playerId.ToString(System.Globalization.CultureInfo.InvariantCulture), out var ticketId)) { return null; } - var ticket = FindInternal(tenantId, appId, ticketId); + var ticket = FindInternal(ticketId); if (ticket == null || ticket.State != OnlineMatchTicketState.Queued) { return null; @@ -622,7 +588,7 @@ private void IndexPlayers(OnlineMatchTicket ticket) foreach (var playerId in ticket.PlayerIds) { - _playerIndex[BuildKey(ticket.TenantId, ticket.AppId, playerId.ToString())] = ticket.TicketId; + _playerIndex[playerId.ToString(System.Globalization.CultureInfo.InvariantCulture)] = ticket.TicketId; } } @@ -643,23 +609,11 @@ private void ReleasePlayers(OnlineMatchTicket ticket) foreach (var playerId in ticket.PlayerIds) { - var key = BuildKey(ticket.TenantId, ticket.AppId, playerId.ToString()); + var key = playerId.ToString(System.Globalization.CultureInfo.InvariantCulture); if (_playerIndex.TryGetValue(key, out var indexedTicketId) && indexedTicketId == ticket.TicketId) { _playerIndex.Remove(key); } } } - - /// - /// 构造存储键。 - /// - /// 租户标识。 - /// App 标识。 - /// 末段标识。 - /// 存储键。 - private static string BuildKey(long tenantId, long appId, string id) - { - return tenantId + ":" + appId + ":" + id; - } -} \ No newline at end of file +} diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchAssignment.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchAssignment.cs index 22518dd92..9bed90370 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchAssignment.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchAssignment.cs @@ -80,15 +80,6 @@ public sealed class OnlineMatchAssignment /// public List TicketIds { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } /// /// 获取或设置区服标识(作用域隔离键)。 @@ -123,8 +114,6 @@ public OnlineMatchAssignment Copy() RuleSnapshot = RuleSnapshot == null ? null : RuleSnapshot.Copy(), CreatedAtTime = CreatedAtTime, TicketIds = ticketIds, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, }; } diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchEventOutboxEntry.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchEventOutboxEntry.cs index 893b81e54..2f7bf0728 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchEventOutboxEntry.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchEventOutboxEntry.cs @@ -41,16 +41,6 @@ public sealed class OnlineMatchEventOutboxEntry /// public string EventId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置事件信封(追加时存档引用,投递时原样发布)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchEvents.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchEvents.cs index 20712e128..aa760d9ce 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchEvents.cs @@ -55,8 +55,6 @@ public static class OnlineMatchEvents /// /// 构造票据状态变更事件。 /// - /// 租户标识。 - /// App 标识。 /// 发起区服标识。 /// 票据标识(可空;载荷落空字符串)。 /// 来源队伍标识(可空;载荷落空字符串)。 @@ -68,7 +66,7 @@ public static class OnlineMatchEvents /// 目标状态名。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateTicketChanged(long tenantId, long appId, long serverId, string ticketId, string partyId, string failureReason, string assignmentId, int playerCount, long firstPlayerId, string fromState, string toState, string correlationId = null) + public static OnlineEvent CreateTicketChanged(long serverId, string ticketId, string partyId, string failureReason, string assignmentId, int playerCount, long firstPlayerId, string fromState, string toState, string correlationId = null) { var payload = new TicketChangedPayload { @@ -96,8 +94,6 @@ public static OnlineEvent CreateTicketChanged(long tenantId, long appId, long se EventType = TicketChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = firstPlayerId, Source = Source, @@ -110,8 +106,6 @@ public static OnlineEvent CreateTicketChanged(long tenantId, long appId, long se /// /// 构造对局分配事件。 /// - /// 租户标识。 - /// App 标识。 /// 发起区服标识。 /// 分配标识(可空;载荷落空字符串)。 /// 对局标识(可空;载荷落空字符串)。 @@ -122,7 +116,7 @@ public static OnlineEvent CreateTicketChanged(long tenantId, long appId, long se /// 消费的票据集合(可空;载荷落空集合)。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateAssignmentCreated(long tenantId, long appId, long serverId, string assignmentId, string matchId, int mode, int region, int playerCount, long firstPlayerId, IReadOnlyList ticketIds, string correlationId = null) + public static OnlineEvent CreateAssignmentCreated(long serverId, string assignmentId, string matchId, int mode, int region, int playerCount, long firstPlayerId, IReadOnlyList ticketIds, string correlationId = null) { var ticketCount = ticketIds == null ? 0 : ticketIds.Count; var payload = new AssignmentCreatedPayload @@ -149,8 +143,6 @@ public static OnlineEvent CreateAssignmentCreated(long tenantId, long appId, lon EventType = AssignmentCreated, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = firstPlayerId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchListing.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchListing.cs index 757469908..f40be0f80 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchListing.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchListing.cs @@ -45,16 +45,6 @@ public sealed class OnlineMatchListing /// public string ListingId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置区服标识(作用域隔离键)。 /// @@ -153,8 +143,6 @@ public OnlineMatchListing Copy() return new OnlineMatchListing { ListingId = ListingId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, PartyId = PartyId, OwnerPlayerId = OwnerPlayerId, diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchListingService.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchListingService.cs index d96182c89..58a5ea4f2 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchListingService.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchListingService.cs @@ -107,8 +107,6 @@ public async Task> PublishAsync(OnlineScope sco var listing = new OnlineMatchListing { ListingId = "lst-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, PartyId = request.PartyId ?? string.Empty, OwnerPlayerId = scope.PlayerId, @@ -145,7 +143,7 @@ public async Task>> QueryAsync(On var filter = query == null ? new OnlineMatchListingQuery() : query; var limit = filter.Limit > 0 ? filter.Limit : DefaultQueryLimit; - var all = await _store.ListAsync(scope.TenantId, scope.AppId, cancellationToken); + var all = await _store.ListAsync(cancellationToken); var result = new List(); foreach (var listing in all) { @@ -210,7 +208,7 @@ public async Task> GetAsync(OnlineScope scope, return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "缺少作用域"); } - var listing = await _store.FindAsync(scope.TenantId, scope.AppId, listingId, cancellationToken); + var listing = await _store.FindAsync(listingId, cancellationToken); if (listing == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "列表项不存在"); @@ -266,7 +264,7 @@ public async Task> JoinAsync(OnlineScope scope, /// 终态结果;返回 null 表示 CAS 版本冲突,调用方应重读重试。 private async Task> TryJoinOnceAsync(OnlineScope scope, string listingId, List members, string password, CancellationToken cancellationToken) { - var listing = await _store.FindAsync(scope.TenantId, scope.AppId, listingId, cancellationToken); + var listing = await _store.FindAsync(listingId, cancellationToken); if (listing == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "列表项不存在"); @@ -317,7 +315,7 @@ public async Task> CloseAsync(OnlineScope scope for (var attempt = 0; attempt < MaxWriteAttempts; attempt++) { - var listing = await _store.FindAsync(scope.TenantId, scope.AppId, listingId, cancellationToken); + var listing = await _store.FindAsync(listingId, cancellationToken); if (listing == null || listing.OwnerPlayerId != scope.PlayerId) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "列表项不存在"); diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchQueueObserver.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchQueueObserver.cs index 9081cd794..58e3b8de0 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchQueueObserver.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchQueueObserver.cs @@ -62,22 +62,18 @@ public OnlineMatchQueueObserver(IOnlineMatchTicketStore store) /// /// 观测指定作用域的匹配队列。 /// - /// 租户标识。 - /// App 标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟)。 /// 取消令牌。 /// 队列观测快照。 - public async Task> ObserveAsync(long tenantId, long appId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task> ObserveAsync(long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var tickets = await _store.ListAllAsync(tenantId, appId, cancellationToken).ConfigureAwait(false); - var assignments = await _store.ListAssignmentsAsync(tenantId, appId, cancellationToken).ConfigureAwait(false); + var tickets = await _store.ListAllAsync(cancellationToken).ConfigureAwait(false); + var assignments = await _store.ListAssignmentsAsync(cancellationToken).ConfigureAwait(false); var snapshot = new OnlineMatchQueueSnapshot { - TenantId = tenantId, - AppId = appId, ObservedAtTime = now, AssignmentCount = assignments.Count, Tickets = new List(tickets.Count), diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchQueueSnapshot.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchQueueSnapshot.cs index a3fcbf18a..b29c35717 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchQueueSnapshot.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchQueueSnapshot.cs @@ -40,16 +40,6 @@ namespace GameFrameX.Capability.Online.Matchmaking; /// public sealed class OnlineMatchQueueSnapshot { - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置观测时刻(UTC 毫秒)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchRateLimiter.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchRateLimiter.cs index 511dae9f5..486d6187f 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchRateLimiter.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchRateLimiter.cs @@ -32,7 +32,7 @@ namespace GameFrameX.Capability.Online.Matchmaking; /// /// 入队限流器(刷 Ticket 被限流,且正常玩家不受影响)。 /// -/// 维护约束(天花板):滑动窗口计数,按 (TenantId, AppId, PlayerId) 分桶——阈值与窗口可由 +/// 维护约束(天花板):滑动窗口计数,按 PlayerId 分桶——阈值与窗口可由 /// 覆盖,压测需同时验证「高频被拦」与「正常节奏不受影响」。 /// 桶在窗口过期后整桶重置(而非逐条出队),内存占用与玩家数同阶;进程重启即清零, /// 这是可接受的:限流是速率保护不是配额。生产多实例下需换成共享存储实现(归运行时装配)。 @@ -43,7 +43,7 @@ public sealed class OnlineMatchRateLimiter /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 窗口计数桶:键 = (TenantId, AppId, PlayerId)。 + /// 窗口计数桶:键 = PlayerId。 private readonly Dictionary _windows = new(); /// 上一次全量清扫时刻(UTC 毫秒)。 @@ -75,15 +75,13 @@ public OnlineMatchRateLimiter(int maxOperations, int windowSeconds) /// /// 尝试获取一次操作配额。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 允许返回 true;超限返回 false。 - public bool TryAcquire(long tenantId, long appId, long playerId, long nowUnixMilliseconds = 0) + public bool TryAcquire(long playerId, long nowUnixMilliseconds = 0) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var key = tenantId + ":" + appId + ":" + playerId; + var key = playerId.ToString(System.Globalization.CultureInfo.InvariantCulture); lock (_syncRoot) { diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchTicket.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchTicket.cs index 494aee93e..b276de745 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchTicket.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchTicket.cs @@ -30,8 +30,7 @@ namespace GameFrameX.Capability.Online.Matchmaking; /// -/// 匹配票据(冻结字段集:TicketId / PartyId / PlayerIds / AppId / Mode / Region / -/// SkillRange / TeamSize / LatencyRequirement / CustomProperties / CreatedAt / ExpiresAt / Status)。 +/// 匹配票据(冻结字段集:TicketId / PartyId / PlayerIds / Mode / Region / /// /// 维护约束(红线): 非空时 必须是**整队**成员—— /// 队伍完整性要求一张票据要么整队成组、要么整队留队,禁止部分成员先走。 @@ -56,16 +55,6 @@ public sealed class OnlineMatchTicket /// public List PlayerIds { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置区服标识(作用域隔离键)。 /// @@ -152,8 +141,6 @@ public OnlineMatchTicket Copy() TicketId = TicketId, PartyId = PartyId, PlayerIds = playerIds, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Mode = Mode, Region = Region, diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchTicketService.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchTicketService.cs index 1efe752ee..facdb8dad 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchTicketService.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchTicketService.cs @@ -114,7 +114,7 @@ public async Task> EnqueueAsync(OnlineScope scop return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "票据玩家集合非法"); } - if (!_rateLimiter.TryAcquire(scope.TenantId, scope.AppId, scope.PlayerId)) + if (!_rateLimiter.TryAcquire(scope.PlayerId)) { return OnlineResult.Fail(OnlineErrorCode.RateLimitExceeded, "操作过于频繁,请稍后重试"); } @@ -127,8 +127,6 @@ public async Task> EnqueueAsync(OnlineScope scop TicketId = "tkt-" + Guid.NewGuid().ToString("N"), PartyId = partyId, PlayerIds = members, - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, Mode = request.Mode, Region = request.Region, @@ -174,7 +172,7 @@ public async Task> CancelAsync(OnlineScope scope return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "缺少票据标识"); } - var ticket = await _store.FindAsync(scope.TenantId, scope.AppId, ticketId, cancellationToken).ConfigureAwait(false); + var ticket = await _store.FindAsync(ticketId, cancellationToken).ConfigureAwait(false); if (ticket == null || !IsReachable(scope, ticket) || !ContainsPlayer(ticket, scope.PlayerId)) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "票据不存在或不属于当前玩家"); @@ -185,15 +183,15 @@ public async Task> CancelAsync(OnlineScope scope return OnlineResult.Ok(ticket); } - if (!_rateLimiter.TryAcquire(scope.TenantId, scope.AppId, scope.PlayerId)) + if (!_rateLimiter.TryAcquire(scope.PlayerId)) { return OnlineResult.Fail(OnlineErrorCode.RateLimitExceeded, "操作过于频繁,请稍后重试"); } - var cancelled = await _store.UpdateStateAsync(scope.TenantId, scope.AppId, new MatchTicketStateTransition { TicketId = ticketId, ExpectedState = OnlineMatchTicketState.Queued, NewState = OnlineMatchTicketState.Cancelled, FailureReason = OnlineMatchFailureReason.CancelledByPlayer, AssignmentId = string.Empty, }, cancellationToken).ConfigureAwait(false); + var cancelled = await _store.UpdateStateAsync(new MatchTicketStateTransition { TicketId = ticketId, ExpectedState = OnlineMatchTicketState.Queued, NewState = OnlineMatchTicketState.Cancelled, FailureReason = OnlineMatchFailureReason.CancelledByPlayer, AssignmentId = string.Empty, }, cancellationToken).ConfigureAwait(false); if (cancelled == null) { - var receipt = await _store.FindAsync(scope.TenantId, scope.AppId, ticketId, cancellationToken).ConfigureAwait(false); + var receipt = await _store.FindAsync(ticketId, cancellationToken).ConfigureAwait(false); if (receipt == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "票据不存在或不属于当前玩家"); @@ -202,7 +200,7 @@ public async Task> CancelAsync(OnlineScope scope return OnlineResult.Ok(receipt); } - await _eventPublisher.PublishAsync(OnlineMatchEvents.CreateTicketChanged(cancelled.TenantId, cancelled.AppId, cancelled.ServerId, cancelled.TicketId, cancelled.PartyId, cancelled.FailureReason.ToString(), cancelled.AssignmentId, cancelled.PlayerIds == null ? 0 : cancelled.PlayerIds.Count, cancelled.PlayerIds != null && cancelled.PlayerIds.Count > 0 ? cancelled.PlayerIds[0] : 0, OnlineMatchTicketState.Queued.ToString(), OnlineMatchTicketState.Cancelled.ToString()), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineMatchEvents.CreateTicketChanged(cancelled.ServerId, cancelled.TicketId, cancelled.PartyId, cancelled.FailureReason.ToString(), cancelled.AssignmentId, cancelled.PlayerIds == null ? 0 : cancelled.PlayerIds.Count, cancelled.PlayerIds != null && cancelled.PlayerIds.Count > 0 ? cancelled.PlayerIds[0] : 0, OnlineMatchTicketState.Queued.ToString(), OnlineMatchTicketState.Cancelled.ToString()), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(cancelled); } @@ -227,7 +225,7 @@ public async Task> GetAsync(OnlineScope scope, s return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "缺少票据标识"); } - var ticket = await _store.FindAsync(scope.TenantId, scope.AppId, ticketId, cancellationToken).ConfigureAwait(false); + var ticket = await _store.FindAsync(ticketId, cancellationToken).ConfigureAwait(false); if (ticket == null || !IsReachable(scope, ticket) || !ContainsPlayer(ticket, scope.PlayerId)) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "票据不存在或不属于当前玩家"); @@ -250,22 +248,20 @@ public async Task> GetActiveAsync(OnlineScope sc return failure; } - var ticket = await _store.FindActiveByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var ticket = await _store.FindActiveByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(ticket); } /// /// 扫描并把超过存活时长的排队票据置为 。 /// - /// 租户标识。 - /// App 标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟)。 /// 取消令牌。 /// 本次过期的票据数。 - public async Task> SweepExpiredAsync(long tenantId, long appId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task> SweepExpiredAsync(long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : Now(); - var queued = await _store.ListQueuedAsync(tenantId, appId, cancellationToken).ConfigureAwait(false); + var queued = await _store.ListQueuedAsync(cancellationToken).ConfigureAwait(false); var expired = new List(); foreach (var ticket in queued) @@ -275,7 +271,7 @@ public async Task> SweepExpiredAsync(long tenantId, long appId continue; } - var updated = await _store.UpdateStateAsync(tenantId, appId, new MatchTicketStateTransition { TicketId = ticket.TicketId, ExpectedState = OnlineMatchTicketState.Queued, NewState = OnlineMatchTicketState.Expired, FailureReason = OnlineMatchFailureReason.WaitTimeout, AssignmentId = string.Empty, }, cancellationToken).ConfigureAwait(false); + var updated = await _store.UpdateStateAsync(new MatchTicketStateTransition { TicketId = ticket.TicketId, ExpectedState = OnlineMatchTicketState.Queued, NewState = OnlineMatchTicketState.Expired, FailureReason = OnlineMatchFailureReason.WaitTimeout, AssignmentId = string.Empty, }, cancellationToken).ConfigureAwait(false); if (updated != null) { expired.Add(updated); @@ -284,7 +280,7 @@ public async Task> SweepExpiredAsync(long tenantId, long appId foreach (var ticket in expired) { - await _eventPublisher.PublishAsync(OnlineMatchEvents.CreateTicketChanged(ticket.TenantId, ticket.AppId, ticket.ServerId, ticket.TicketId, ticket.PartyId, ticket.FailureReason.ToString(), ticket.AssignmentId, ticket.PlayerIds == null ? 0 : ticket.PlayerIds.Count, ticket.PlayerIds != null && ticket.PlayerIds.Count > 0 ? ticket.PlayerIds[0] : 0, OnlineMatchTicketState.Queued.ToString(), OnlineMatchTicketState.Expired.ToString()), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineMatchEvents.CreateTicketChanged(ticket.ServerId, ticket.TicketId, ticket.PartyId, ticket.FailureReason.ToString(), ticket.AssignmentId, ticket.PlayerIds == null ? 0 : ticket.PlayerIds.Count, ticket.PlayerIds != null && ticket.PlayerIds.Count > 0 ? ticket.PlayerIds[0] : 0, OnlineMatchTicketState.Queued.ToString(), OnlineMatchTicketState.Expired.ToString()), cancellationToken).ConfigureAwait(false); } return OnlineResult.Ok(expired.Count); diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakerCoordinator.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakerCoordinator.cs index 86cf481b5..054d161e5 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakerCoordinator.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakerCoordinator.cs @@ -91,31 +91,28 @@ public OnlineMatchmakerCoordinator(IOnlineMatchTicketStore store, OnlineMatchTic /// /// 执行一轮匹配:先扫描过期,再按 FIFO 逐张基准票据尝试成组并原子落档。 /// - /// 租户标识。 - /// App 标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 /// 本轮执行结果。 - public async Task> RunOnceAsync(long tenantId, long appId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task> RunOnceAsync(long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // C374 补偿:本轮撮合前先重投上一轮发布失败的待投递事件(至少一次投递;无发件箱时跳过)。 if (_eventOutbox != null) { - await DeliverPendingEventsAsync(tenantId, appId, cancellationToken).ConfigureAwait(false); + await DeliverPendingEventsAsync(cancellationToken).ConfigureAwait(false); } - var sweep = await _ticketService.SweepExpiredAsync(tenantId, appId, now, cancellationToken).ConfigureAwait(false); + var sweep = await _ticketService.SweepExpiredAsync(now, cancellationToken).ConfigureAwait(false); var result = new OnlineMatchmakingRunResult { - TenantId = tenantId, - AppId = appId, ExpiredTicketCount = sweep.Data, AssignmentIds = new List(), }; - var queued = await _store.ListQueuedAsync(tenantId, appId, cancellationToken).ConfigureAwait(false); + var queued = await _store.ListQueuedAsync(cancellationToken).ConfigureAwait(false); + result.ScannedTicketCount = queued.Count; var ordered = SortByArrival(queued); @@ -128,7 +125,7 @@ public async Task> RunOnceAsync(long te continue; } - var group = await SelectGroupAsync(anchor, ordered, consumed, now, tenantId, appId, cancellationToken).ConfigureAwait(false); + var group = await SelectGroupAsync(anchor, ordered, consumed, now, cancellationToken).ConfigureAwait(false); if (group == null) { continue; @@ -177,8 +174,6 @@ private async Task CommitAsync(OnlineMatchTicket anchor, RuleSnapshot = BuildSnapshot(group, nowUnixMilliseconds), CreatedAtTime = nowUnixMilliseconds, TicketIds = ticketIds, - TenantId = anchor.TenantId, - AppId = anchor.AppId, ServerId = anchor.ServerId, }; @@ -224,15 +219,15 @@ private async Task> BuildMatchEventsAsync(OnlineMatchAssignmen { var events = new List { - OnlineMatchEvents.CreateAssignmentCreated(committed.TenantId, committed.AppId, committed.ServerId, committed.AssignmentId, committed.MatchId, committed.Mode, committed.Region, committed.PlayerIds == null ? 0 : committed.PlayerIds.Count, committed.PlayerIds != null && committed.PlayerIds.Count > 0 ? committed.PlayerIds[0] : 0, committed.TicketIds), + OnlineMatchEvents.CreateAssignmentCreated(committed.ServerId, committed.AssignmentId, committed.MatchId, committed.Mode, committed.Region, committed.PlayerIds == null ? 0 : committed.PlayerIds.Count, committed.PlayerIds != null && committed.PlayerIds.Count > 0 ? committed.PlayerIds[0] : 0, committed.TicketIds), }; foreach (var ticketId in ticketIds) { - var matched = await _store.FindAsync(committed.TenantId, committed.AppId, ticketId, cancellationToken).ConfigureAwait(false); + var matched = await _store.FindAsync(ticketId, cancellationToken).ConfigureAwait(false); if (matched != null) { - events.Add(OnlineMatchEvents.CreateTicketChanged(matched.TenantId, matched.AppId, matched.ServerId, matched.TicketId, matched.PartyId, matched.FailureReason.ToString(), matched.AssignmentId, matched.PlayerIds == null ? 0 : matched.PlayerIds.Count, matched.PlayerIds != null && matched.PlayerIds.Count > 0 ? matched.PlayerIds[0] : 0, OnlineMatchTicketState.Queued.ToString(), OnlineMatchTicketState.Matched.ToString())); + events.Add(OnlineMatchEvents.CreateTicketChanged(matched.ServerId, matched.TicketId, matched.PartyId, matched.FailureReason.ToString(), matched.AssignmentId, matched.PlayerIds == null ? 0 : matched.PlayerIds.Count, matched.PlayerIds != null && matched.PlayerIds.Count > 0 ? matched.PlayerIds[0] : 0, OnlineMatchTicketState.Queued.ToString(), OnlineMatchTicketState.Matched.ToString())); } } @@ -263,20 +258,18 @@ private async Task PublishCommittedEventsAsync(OnlineMatchAssignment committed, } await _eventOutbox.AppendAsync(events, cancellationToken).ConfigureAwait(false); - await DeliverPendingEventsAsync(committed.TenantId, committed.AppId, cancellationToken).ConfigureAwait(false); + await DeliverPendingEventsAsync(cancellationToken).ConfigureAwait(false); } /// /// 重投作用域内全部待投递事件:逐条发布、成功即标记已投递;单条失败吞没异常并保留条目, /// 交由后续轮次继续重投(异常不外溢——撮合与重投互不拖垮)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 完成通知。 - private async Task DeliverPendingEventsAsync(long tenantId, long appId, CancellationToken cancellationToken) + private async Task DeliverPendingEventsAsync(CancellationToken cancellationToken) { - var pending = await _eventOutbox.ListPendingAsync(tenantId, appId, cancellationToken).ConfigureAwait(false); + var pending = await _eventOutbox.ListPendingAsync(cancellationToken).ConfigureAwait(false); foreach (var entry in pending) { @@ -289,7 +282,7 @@ private async Task DeliverPendingEventsAsync(long tenantId, long appId, Cancella continue; } - await _eventOutbox.MarkDeliveredAsync(tenantId, appId, entry.EventId, cancellationToken).ConfigureAwait(false); + await _eventOutbox.MarkDeliveredAsync(entry.EventId, cancellationToken).ConfigureAwait(false); } } @@ -311,11 +304,9 @@ private async Task DeliverPendingEventsAsync(long tenantId, long appId, Cancella /// 按入队顺序排列的候选票据。 /// 本轮已消费的票据标识(不得再次成组)。 /// 当前时刻(UTC 毫秒)。 - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 凑满目标规模的票据组;不足返回 null。 - private async Task> SelectGroupAsync(OnlineMatchTicket anchor, List ordered, HashSet consumed, long nowUnixMilliseconds, long tenantId, long appId, CancellationToken cancellationToken) + private async Task> SelectGroupAsync(OnlineMatchTicket anchor, List ordered, HashSet consumed, long nowUnixMilliseconds, CancellationToken cancellationToken) { if (anchor.TeamSize <= 0 || consumed.Contains(anchor.TicketId)) { @@ -336,7 +327,7 @@ private async Task> SelectGroupAsync(OnlineMatchTicket a foreach (var candidate in ordered) { - if (!await CanAddToGroupAsync(anchor, candidate, players, consumed, nowUnixMilliseconds, tenantId, appId, cancellationToken).ConfigureAwait(false)) + if (!await CanAddToGroupAsync(anchor, candidate, players, consumed, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false)) { continue; } @@ -380,11 +371,9 @@ private static HashSet BuildAnchorPlayerSet(OnlineMatchTicket anchor) /// 已累加玩家集合。 /// 本轮已消费的票据标识。 /// 当前时刻(UTC 毫秒)。 - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 可累加返回 true。 - private async Task CanAddToGroupAsync(OnlineMatchTicket anchor, OnlineMatchTicket candidate, HashSet players, HashSet consumed, long nowUnixMilliseconds, long tenantId, long appId, CancellationToken cancellationToken) + private async Task CanAddToGroupAsync(OnlineMatchTicket anchor, OnlineMatchTicket candidate, HashSet players, HashSet consumed, long nowUnixMilliseconds, CancellationToken cancellationToken) { if (candidate.TicketId == anchor.TicketId || consumed.Contains(candidate.TicketId)) { @@ -411,7 +400,7 @@ private async Task CanAddToGroupAsync(OnlineMatchTicket anchor, OnlineMatc return false; } - return await IsSociallyCompatibleAsync(players, candidate, tenantId, appId, cancellationToken).ConfigureAwait(false); + return await IsSociallyCompatibleAsync(players, candidate, cancellationToken).ConfigureAwait(false); } /// @@ -495,11 +484,9 @@ private static List SortByArrival(IReadOnlyList /// 已累加玩家集合。 /// 候选票据。 - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 可共处一局返回 true。 - private async Task IsSociallyCompatibleAsync(HashSet players, OnlineMatchTicket candidate, long tenantId, long appId, CancellationToken cancellationToken) + private async Task IsSociallyCompatibleAsync(HashSet players, OnlineMatchTicket candidate, CancellationToken cancellationToken) { if (_socialGate == null || players.Count == 0) { @@ -510,13 +497,13 @@ private async Task IsSociallyCompatibleAsync(HashSet players, Online { foreach (var candidatePlayerId in candidate.PlayerIds) { - var forward = await _socialGate.EvaluateAsync(tenantId, appId, existingPlayerId, candidatePlayerId, OnlineSocialInteractionPurpose.Matchmaking, cancellationToken).ConfigureAwait(false); + var forward = await _socialGate.EvaluateAsync(existingPlayerId, candidatePlayerId, OnlineSocialInteractionPurpose.Matchmaking, cancellationToken).ConfigureAwait(false); if (!forward.Allowed) { return false; } - var backward = await _socialGate.EvaluateAsync(tenantId, appId, candidatePlayerId, existingPlayerId, OnlineSocialInteractionPurpose.Matchmaking, cancellationToken).ConfigureAwait(false); + var backward = await _socialGate.EvaluateAsync(candidatePlayerId, existingPlayerId, OnlineSocialInteractionPurpose.Matchmaking, cancellationToken).ConfigureAwait(false); if (!backward.Allowed) { return false; diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakingCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakingCapabilityModule.cs index d4bc6cadb..2e0759683 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakingCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakingCapabilityModule.cs @@ -152,11 +152,11 @@ public void Register(CapabilityRegistrationContext context) context.AddTickJob("matchmaker-run", async ct => { - await _matchmaker.RunOnceAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _matchmaker.RunOnceAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); context.AddTickJob("match-ticket-expiry-sweep", async ct => { - await _matchTickets.SweepExpiredAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _matchTickets.SweepExpiredAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); } diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakingRunResult.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakingRunResult.cs index 2452d5243..127c09eb4 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakingRunResult.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/OnlineMatchmakingRunResult.cs @@ -39,16 +39,6 @@ namespace GameFrameX.Capability.Online.Matchmaking; /// public sealed class OnlineMatchmakingRunResult { - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置本轮开始时排队中的票据数。 /// diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/IOnlinePartyStore.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/IOnlinePartyStore.cs index 7209fd35e..8ad3f1660 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/IOnlinePartyStore.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/IOnlinePartyStore.cs @@ -51,51 +51,41 @@ public interface IOnlinePartyStore /// /// 按队伍标识查找队伍。 /// - /// 租户标识。 - /// App 标识。 /// 队伍标识。 /// 取消令牌。 /// 队伍副本;不存在返回 null。 - Task FindPartyAsync(long tenantId, long appId, string partyId, CancellationToken cancellationToken = default); + Task FindPartyAsync(string partyId, CancellationToken cancellationToken = default); /// /// 按玩家反查其所在队伍(跨作用域返回 null,避免反预言)。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 队伍副本;不在任何队伍返回 null。 - Task FindPartyByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task FindPartyByPlayerAsync(long playerId, CancellationToken cancellationToken = default); /// /// 移除队伍(解散/取消的清理动作)。 /// - /// 租户标识。 - /// App 标识。 /// 队伍标识。 /// 取消令牌。 /// 完成通知。 - Task RemovePartyAsync(long tenantId, long appId, string partyId, CancellationToken cancellationToken = default); + Task RemovePartyAsync(string partyId, CancellationToken cancellationToken = default); /// /// 列出作用域内全部队伍(空闲过期扫描用)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 队伍副本列表。 - Task> ListPartiesAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListPartiesAsync(CancellationToken cancellationToken = default); /// - /// 统计作用域 (TenantId, AppId, ServerId) 内非终态队伍的按状态分组计数(聚合谓词下推:终态判定同 ,与在线总览口径一致;键按状态枚举值升序)。 + /// 统计作用域 (ServerId) 内非终态队伍的按状态分组计数(聚合谓词下推:终态判定同 ,与在线总览口径一致;键按状态枚举值升序)。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// 状态 → 队伍数(只含非终态状态;无非终态队伍时为空表)。 - Task> CountNonTerminalByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default); + Task> CountNonTerminalByScopeAsync(long serverId, CancellationToken cancellationToken = default); /// /// 保存邀请。 @@ -108,30 +98,24 @@ public interface IOnlinePartyStore /// /// 按邀请标识查找邀请。 /// - /// 租户标识。 - /// App 标识。 /// 邀请标识。 /// 取消令牌。 /// 邀请副本;不存在返回 null。 - Task FindInviteAsync(long tenantId, long appId, string inviteId, CancellationToken cancellationToken = default); + Task FindInviteAsync(string inviteId, CancellationToken cancellationToken = default); /// /// 查找被邀请人的待答复邀请。 /// - /// 租户标识。 - /// App 标识。 /// 被邀请玩家标识。 /// 队伍标识(null 表示不限队伍)。 /// 取消令牌。 /// 待答复邀请副本;无则返回 null。 - Task FindPendingInviteAsync(long tenantId, long appId, long inviteeId, string partyId, CancellationToken cancellationToken = default); + Task FindPendingInviteAsync(long inviteeId, string partyId, CancellationToken cancellationToken = default); /// /// 列出作用域内全部邀请(邀请过期扫描用)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 邀请副本列表。 - Task> ListInvitesAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task> ListInvitesAsync(CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/InMemoryOnlinePartyStore.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/InMemoryOnlinePartyStore.cs index 319615a25..515452726 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/InMemoryOnlinePartyStore.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/InMemoryOnlinePartyStore.cs @@ -42,13 +42,13 @@ public sealed class InMemoryOnlinePartyStore : IOnlinePartyStore /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 队伍表:键 = (TenantId, AppId, PartyId)。 + /// 队伍表:键 = PartyId。 private readonly Dictionary _parties = new(); - /// 玩家 → 队伍索引:键 = (TenantId, AppId, PlayerId)。 + /// 玩家 → 队伍索引:键 = PlayerId。 private readonly Dictionary _partyIdByPlayer = new(); - /// 邀请表:键 = (TenantId, AppId, InviteId)。 + /// 邀请表:键 = InviteId。 private readonly Dictionary _invites = new(); /// 保存队伍(深拷贝入库并重建玩家索引)。 @@ -63,81 +63,69 @@ public Task SavePartyAsync(OnlineParty party, CancellationToken cancellationToke lock (_syncRoot) { - var key = BuildKey(party.TenantId, party.AppId, party.PartyId); - _parties[key] = party.Copy(); - RebuildPlayerIndex(party.TenantId, party.AppId, party.PartyId); + _parties[party.PartyId] = party.Copy(); + RebuildPlayerIndex(party.PartyId); } return Task.CompletedTask; } /// 按队伍标识查找队伍。 - /// 租户标识。 - /// App 标识。 /// 队伍标识。 /// 取消令牌。 /// 队伍副本;不存在返回 null。 - public Task FindPartyAsync(long tenantId, long appId, string partyId, CancellationToken cancellationToken = default) + public Task FindPartyAsync(string partyId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - _parties.TryGetValue(BuildKey(tenantId, appId, partyId), out var party); + _parties.TryGetValue(partyId, out var party); return Task.FromResult(party == null ? null : party.Copy()); } } /// 按玩家反查其所在队伍。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 队伍副本;不在任何队伍返回 null。 - public Task FindPartyByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task FindPartyByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - if (!_partyIdByPlayer.TryGetValue(BuildKey(tenantId, appId, playerId), out var partyId)) + if (!_partyIdByPlayer.TryGetValue(playerId.ToString(System.Globalization.CultureInfo.InvariantCulture), out var partyId)) { return Task.FromResult(null); } - _parties.TryGetValue(BuildKey(tenantId, appId, partyId), out var party); + _parties.TryGetValue(partyId, out var party); return Task.FromResult(party == null ? null : party.Copy()); } } /// 移除队伍并清理其玩家索引。 - /// 租户标识。 - /// App 标识。 /// 队伍标识。 /// 取消令牌。 - public Task RemovePartyAsync(long tenantId, long appId, string partyId, CancellationToken cancellationToken = default) + public Task RemovePartyAsync(string partyId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - _parties.Remove(BuildKey(tenantId, appId, partyId)); - RebuildPlayerIndex(tenantId, appId, partyId); + _parties.Remove(partyId); + RebuildPlayerIndex(partyId); } return Task.CompletedTask; } /// 列出作用域内全部队伍。 - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 队伍副本列表。 - public Task> ListPartiesAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListPartiesAsync(CancellationToken cancellationToken = default) { lock (_syncRoot) { var result = new List(); foreach (var party in _parties.Values) { - if (party.TenantId == tenantId && party.AppId == appId) - { - result.Add(party.Copy()); - } + result.Add(party.Copy()); } return Task.FromResult>(result); @@ -145,21 +133,19 @@ public Task> ListPartiesAsync(long tenantId, long app } /// - /// 统计作用域 (TenantId, AppId, ServerId) 内非终态队伍的按状态分组计数(表内扫描不产出实体副本;键按状态枚举值升序)。 + /// 统计作用域 (ServerId) 内非终态队伍的按状态分组计数(表内扫描不产出实体副本;键按状态枚举值升序)。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// 状态 → 队伍数(只含非终态状态;无非终态队伍时为空表)。 - public Task> CountNonTerminalByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public Task> CountNonTerminalByScopeAsync(long serverId, CancellationToken cancellationToken = default) { lock (_syncRoot) { var counts = new SortedDictionary(); foreach (var party in _parties.Values) { - if (party.TenantId == tenantId && party.AppId == appId && party.ServerId == serverId && !OnlinePartyStateMachine.IsTerminal(party.State)) + if (party.ServerId == serverId && !OnlinePartyStateMachine.IsTerminal(party.State)) { counts.TryGetValue(party.State, out var current); counts[party.State] = current + 1; @@ -182,41 +168,37 @@ public Task SaveInviteAsync(OnlinePartyInvite invite, CancellationToken cancella lock (_syncRoot) { - _invites[BuildKey(invite.TenantId, invite.AppId, invite.InviteId)] = invite.Copy(); + _invites[invite.InviteId] = invite.Copy(); } return Task.CompletedTask; } /// 按邀请标识查找邀请。 - /// 租户标识。 - /// App 标识。 /// 邀请标识。 /// 取消令牌。 /// 邀请副本;不存在返回 null。 - public Task FindInviteAsync(long tenantId, long appId, string inviteId, CancellationToken cancellationToken = default) + public Task FindInviteAsync(string inviteId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - _invites.TryGetValue(BuildKey(tenantId, appId, inviteId), out var invite); + _invites.TryGetValue(inviteId, out var invite); return Task.FromResult(invite == null ? null : invite.Copy()); } } /// 查找被邀请人的待答复邀请。 - /// 租户标识。 - /// App 标识。 /// 被邀请玩家标识。 /// 队伍标识(null 表示不限队伍)。 /// 取消令牌。 /// 待答复邀请副本;无则返回 null。 - public Task FindPendingInviteAsync(long tenantId, long appId, long inviteeId, string partyId, CancellationToken cancellationToken = default) + public Task FindPendingInviteAsync(long inviteeId, string partyId, CancellationToken cancellationToken = default) { lock (_syncRoot) { foreach (var invite in _invites.Values) { - if (invite.TenantId != tenantId || invite.AppId != appId || invite.InviteeId != inviteeId) + if (invite.InviteeId != inviteeId) { continue; } @@ -239,21 +221,16 @@ public Task FindPendingInviteAsync(long tenantId, long appId, } /// 列出作用域内全部邀请。 - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 邀请副本列表。 - public Task> ListInvitesAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListInvitesAsync(CancellationToken cancellationToken = default) { lock (_syncRoot) { var result = new List(); foreach (var invite in _invites.Values) { - if (invite.TenantId == tenantId && invite.AppId == appId) - { - result.Add(invite.Copy()); - } + result.Add(invite.Copy()); } return Task.FromResult>(result); @@ -261,15 +238,13 @@ public Task> ListInvitesAsync(long tenantId, lo } /// 按队伍当前成员集合整体重建玩家索引(先清该队伍的旧索引,再按成员重挂)。 - /// 租户标识。 - /// App 标识。 /// 队伍标识。 - private void RebuildPlayerIndex(long tenantId, long appId, string partyId) + private void RebuildPlayerIndex(string partyId) { var staleKeys = new List(); foreach (var pair in _partyIdByPlayer) { - if (pair.Value == partyId && pair.Key.StartsWith(tenantId + ":" + appId + ":", StringComparison.Ordinal)) + if (pair.Value == partyId) { staleKeys.Add(pair.Key); } @@ -280,7 +255,7 @@ private void RebuildPlayerIndex(long tenantId, long appId, string partyId) _partyIdByPlayer.Remove(staleKey); } - if (!_parties.TryGetValue(BuildKey(tenantId, appId, partyId), out var party)) + if (!_parties.TryGetValue(partyId, out var party)) { return; } @@ -292,27 +267,7 @@ private void RebuildPlayerIndex(long tenantId, long appId, string partyId) foreach (var member in party.Members) { - _partyIdByPlayer[BuildKey(tenantId, appId, member.PlayerId)] = partyId; + _partyIdByPlayer[member.PlayerId.ToString(System.Globalization.CultureInfo.InvariantCulture)] = partyId; } } - - /// 构造玩家维度的存储键。 - /// 租户标识。 - /// App 标识。 - /// 玩家标识。 - /// 复合键字符串。 - private static string BuildKey(long tenantId, long appId, long playerId) - { - return BuildKey(tenantId, appId, playerId.ToString(System.Globalization.CultureInfo.InvariantCulture)); - } - - /// 构造存储键。 - /// 租户标识。 - /// App 标识。 - /// 标识(队伍或邀请)。 - /// 复合键字符串。 - private static string BuildKey(long tenantId, long appId, string id) - { - return tenantId + ":" + appId + ":" + id; - } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlineParty.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlineParty.cs index 6e2c89d0b..05a48ffb3 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlineParty.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlineParty.cs @@ -44,16 +44,6 @@ public sealed class OnlineParty /// public string PartyId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置区服标识(作用域隔离键)。 /// @@ -117,8 +107,6 @@ public OnlineParty Copy() return new OnlineParty { PartyId = PartyId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, LeaderId = LeaderId, State = State, diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyEvents.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyEvents.cs index 827072cb7..6ec6b6bf3 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyEvents.cs @@ -54,8 +54,6 @@ public static class OnlinePartyEvents /// /// 构造队伍状态变更事件。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 队伍标识(可空;载荷落空字符串)。 /// 队长标识。 @@ -65,7 +63,7 @@ public static class OnlinePartyEvents /// 变更后成员数快照。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreatePartyChanged(long tenantId, long appId, long serverId, string partyId, long leaderId, string fromState, string toState, string reason, int memberCount, string correlationId = null) + public static OnlineEvent CreatePartyChanged(long serverId, string partyId, long leaderId, string fromState, string toState, string reason, int memberCount, string correlationId = null) { var payload = new PartyChangedPayload { @@ -91,8 +89,6 @@ public static OnlineEvent CreatePartyChanged(long tenantId, long appId, long ser EventType = PartyChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = leaderId, Source = Source, @@ -105,8 +101,6 @@ public static OnlineEvent CreatePartyChanged(long tenantId, long appId, long ser /// /// 构造邀请状态变更事件。 /// - /// 租户标识。 - /// App 标识。 /// 被邀请玩家标识。 /// 邀请标识(可空;载荷落空字符串)。 /// 队伍标识(可空;载荷落空字符串)。 @@ -115,7 +109,7 @@ public static OnlineEvent CreatePartyChanged(long tenantId, long appId, long ser /// 区服标识。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateInviteChanged(long tenantId, long appId, long inviteeId, string inviteId, string partyId, long inviterId, string state, long serverId, string correlationId = null) + public static OnlineEvent CreateInviteChanged(long inviteeId, string inviteId, string partyId, long inviterId, string state, long serverId, string correlationId = null) { var payload = new PartyInviteChangedPayload { @@ -139,8 +133,6 @@ public static OnlineEvent CreateInviteChanged(long tenantId, long appId, long in EventType = PartyInviteChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = inviteeId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyInvite.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyInvite.cs index a58d07146..a508439dd 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyInvite.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyInvite.cs @@ -49,16 +49,6 @@ public sealed class OnlinePartyInvite /// public string PartyId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置邀请发起人(队长)。 /// @@ -94,8 +84,6 @@ public OnlinePartyInvite Copy() { InviteId = InviteId, PartyId = PartyId, - TenantId = TenantId, - AppId = AppId, InviterId = InviterId, InviteeId = InviteeId, State = State, diff --git a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyService.cs b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyService.cs index 7296f0b96..fb55d27a2 100644 --- a/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyService.cs +++ b/Capability/GameFrameX.Capability.Online.Matchmaking/Party/OnlinePartyService.cs @@ -135,7 +135,7 @@ public async Task> CreateAsync(OnlineScope scope, stri return failure; } - var existing = await _store.FindPartyByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var existing = await _store.FindPartyByPlayerAsync(scope.PlayerId, cancellationToken); if (existing != null) { return OnlineResult.Ok(existing); @@ -145,8 +145,6 @@ public async Task> CreateAsync(OnlineScope scope, stri var party = new OnlineParty { PartyId = "pty-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, LeaderId = scope.PlayerId, State = OnlinePartyState.Created, @@ -191,7 +189,7 @@ public async Task> InviteAsync(OnlineScope scope return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "被邀请玩家标识无效"); } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, partyId, cancellationToken); + var party = await _store.FindPartyAsync(partyId, cancellationToken); var reachable = EnsureLeaderReachable(party, scope.PlayerId); if (reachable != null) { @@ -202,7 +200,7 @@ public async Task> InviteAsync(OnlineScope scope { // 社交裁决走跨域唯一入口:屏蔽双向生效、封禁拒绝、禁言不影响组队。 // 置于去重检查之前——被屏蔽/被封禁的邀请即使此前已存在待答复记录也不得再取得答复通道。 - var decision = await _socialGate.EvaluateAsync(scope.TenantId, scope.AppId, scope.PlayerId, inviteeId, OnlineSocialInteractionPurpose.PartyInvite, cancellationToken); + var decision = await _socialGate.EvaluateAsync(scope.PlayerId, inviteeId, OnlineSocialInteractionPurpose.PartyInvite, cancellationToken); if (!decision.Allowed) { return OnlineResult.Fail(decision.Code, decision.Reason); @@ -214,13 +212,13 @@ public async Task> InviteAsync(OnlineScope scope return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "队伍人数已达上限"); } - var existingInvite = await _store.FindPendingInviteAsync(scope.TenantId, scope.AppId, inviteeId, partyId, cancellationToken); + var existingInvite = await _store.FindPendingInviteAsync(inviteeId, partyId, cancellationToken); if (existingInvite != null) { return OnlineResult.Ok(existingInvite); } - var target = await _store.FindPartyByPlayerAsync(scope.TenantId, scope.AppId, inviteeId, cancellationToken); + var target = await _store.FindPartyByPlayerAsync(inviteeId, cancellationToken); if (target != null) { return OnlineResult.Fail(OnlineErrorCode.DuplicateRequest, "被邀请玩家已在其它队伍中"); @@ -231,8 +229,6 @@ public async Task> InviteAsync(OnlineScope scope { InviteId = "inv-" + Guid.NewGuid().ToString("N"), PartyId = party.PartyId, - TenantId = scope.TenantId, - AppId = scope.AppId, InviterId = scope.PlayerId, InviteeId = inviteeId, State = OnlinePartyInviteState.Pending, @@ -240,7 +236,7 @@ public async Task> InviteAsync(OnlineScope scope ExpiresAtTime = now + _inviteTimeToLiveSeconds * 1000, }; await _store.SaveInviteAsync(invite, cancellationToken); - await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.TenantId, invite.AppId, invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), party.ServerId, correlationId), cancellationToken); + await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), party.ServerId, correlationId), cancellationToken); var invited = await TransitionAsync(party, OnlinePartyState.Inviting, OnlinePartyLeaveReason.Left, correlationId, cancellationToken); if (!invited.IsSuccess) @@ -272,13 +268,13 @@ public async Task> AnswerInviteAsync(OnlineScope scope return failure; } - var invite = await _store.FindInviteAsync(scope.TenantId, scope.AppId, inviteId, cancellationToken); + var invite = await _store.FindInviteAsync(inviteId, cancellationToken); if (invite == null || invite.InviteeId != scope.PlayerId) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "邀请不存在"); } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, invite.PartyId, cancellationToken); + var party = await _store.FindPartyAsync(invite.PartyId, cancellationToken); if (party == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "队伍不存在"); @@ -293,7 +289,7 @@ public async Task> AnswerInviteAsync(OnlineScope scope { invite.State = OnlinePartyInviteState.Expired; await _store.SaveInviteAsync(invite, cancellationToken); - await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.TenantId, invite.AppId, invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), party.ServerId, correlationId), cancellationToken); + await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), party.ServerId, correlationId), cancellationToken); return OnlineResult.Fail(OnlineErrorCode.StateEnded, "邀请已过期"); } @@ -301,7 +297,7 @@ public async Task> AnswerInviteAsync(OnlineScope scope { invite.State = OnlinePartyInviteState.Rejected; await _store.SaveInviteAsync(invite, cancellationToken); - await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.TenantId, invite.AppId, invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), party.ServerId, correlationId), cancellationToken); + await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), party.ServerId, correlationId), cancellationToken); return OnlineResult.Ok(party); } @@ -312,7 +308,7 @@ public async Task> AnswerInviteAsync(OnlineScope scope // 等于绕开红线。这里复核的是与重新发起邀请时同一组关系的裁决(屏蔽本就双向生效)。 // 拒绝不做裁决——拒绝是脱离互动,拦下它只会把玩家困在待答复状态里。 // 禁言 / 封禁的持续强制不在此处重复:其后果由下游同源判定兜底(聊天发送 / 匹配成组)。 - var decision = await _socialGate.EvaluateAsync(scope.TenantId, scope.AppId, invite.InviterId, scope.PlayerId, OnlineSocialInteractionPurpose.PartyInvite, cancellationToken); + var decision = await _socialGate.EvaluateAsync(invite.InviterId, scope.PlayerId, OnlineSocialInteractionPurpose.PartyInvite, cancellationToken); if (!decision.Allowed) { return OnlineResult.Fail(decision.Code, decision.Reason); @@ -336,7 +332,7 @@ public async Task> AnswerInviteAsync(OnlineScope scope invite.State = OnlinePartyInviteState.Accepted; await _store.SaveInviteAsync(invite, cancellationToken); - await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.TenantId, invite.AppId, invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), party.ServerId, correlationId), cancellationToken); + await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), party.ServerId, correlationId), cancellationToken); return await RefreshAfterMemberChangeAsync(party, OnlinePartyLeaveReason.Left, correlationId, cancellationToken); } @@ -356,7 +352,7 @@ public async Task> JoinAsync(OnlineScope scope, string return failure; } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, partyId, cancellationToken); + var party = await _store.FindPartyAsync(partyId, cancellationToken); if (party == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "队伍不存在"); @@ -377,7 +373,7 @@ public async Task> JoinAsync(OnlineScope scope, string return OnlineResult.Ok(party); } - var occupied = await _store.FindPartyByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var occupied = await _store.FindPartyByPlayerAsync(scope.PlayerId, cancellationToken); if (occupied != null) { return OnlineResult.Fail(OnlineErrorCode.DuplicateRequest, "玩家已在其它队伍中"); @@ -413,7 +409,7 @@ public async Task> LeaveAsync(OnlineScope scope, Onlin return failure; } - var party = await _store.FindPartyByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var party = await _store.FindPartyByPlayerAsync(scope.PlayerId, cancellationToken); if (party == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "玩家不在任何队伍中"); @@ -439,7 +435,7 @@ public async Task> KickAsync(OnlineScope scope, string return failure; } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, partyId, cancellationToken); + var party = await _store.FindPartyAsync(partyId, cancellationToken); var reachable = EnsureLeaderReachable(party, scope.PlayerId); if (reachable != null) { @@ -476,7 +472,7 @@ public async Task> TransferLeaderAsync(OnlineScope sco return failure; } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, partyId, cancellationToken); + var party = await _store.FindPartyAsync(partyId, cancellationToken); var reachable = EnsureLeaderReachable(party, scope.PlayerId); if (reachable != null) { @@ -511,7 +507,7 @@ public async Task> SetReadyAsync(OnlineScope scope, bo return failure; } - var party = await _store.FindPartyByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var party = await _store.FindPartyByPlayerAsync(scope.PlayerId, cancellationToken); if (party == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "玩家不在任何队伍中"); @@ -547,7 +543,7 @@ public async Task> CancelAsync(OnlineScope scope, stri return failure; } - var party = await _store.FindPartyByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var party = await _store.FindPartyByPlayerAsync(scope.PlayerId, cancellationToken); if (party == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "玩家不在任何队伍中"); @@ -577,7 +573,7 @@ public async Task> DisbandAsync(OnlineScope scope, str return failure; } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, partyId, cancellationToken); + var party = await _store.FindPartyAsync(partyId, cancellationToken); var reachable = EnsureLeaderReachable(party, scope.PlayerId); if (reachable != null) { @@ -613,7 +609,7 @@ public async Task> PruneOfflineMembersAsync(OnlineScop return failure; } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, partyId, cancellationToken); + var party = await _store.FindPartyAsync(partyId, cancellationToken); var reachable = EnsureLeaderReachable(party, scope.PlayerId); if (reachable != null) { @@ -633,7 +629,7 @@ public async Task> PruneOfflineMembersAsync(OnlineScop continue; } - var online = await _presenceProbe.IsOnlineAsync(scope.TenantId, scope.AppId, member.PlayerId, cancellationToken); + var online = await _presenceProbe.IsOnlineAsync(member.PlayerId, cancellationToken); if (!online) { offline.Add(member.PlayerId); @@ -667,7 +663,7 @@ public async Task> GetAsync(OnlineScope scope, string return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "缺少作用域"); } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, partyId, cancellationToken); + var party = await _store.FindPartyAsync(partyId, cancellationToken); if (party == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "队伍不存在"); @@ -691,21 +687,19 @@ public async Task> GetAsync(OnlineScope scope, string /// 一律返回 false(不认领),由对应的归属域应答。 /// /// - /// 租户标识。 - /// App 标识。 /// 频道类型。 /// 频道绑定的业务标识(本域为队伍标识)。 /// 待裁决玩家。 /// 取消令牌。 /// 是成员且队伍仍可发言返回 true。 - public async Task IsChannelMemberAsync(long tenantId, long appId, OnlineChatChannelKind kind, string boundId, long playerId, CancellationToken cancellationToken = default) + public async Task IsChannelMemberAsync(OnlineChatChannelKind kind, string boundId, long playerId, CancellationToken cancellationToken = default) { if (kind != OnlineChatChannelKind.Party || string.IsNullOrEmpty(boundId)) { return false; } - var party = await _store.FindPartyAsync(tenantId, appId, boundId, cancellationToken).ConfigureAwait(false); + var party = await _store.FindPartyAsync(boundId, cancellationToken).ConfigureAwait(false); if (party == null || OnlinePartyStateMachine.IsTerminal(party.State) || party.Members == null) { return false; @@ -736,7 +730,7 @@ public async Task> FindMyPartyAsync(OnlineScope scope, return failure; } - var party = await _store.FindPartyByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken); + var party = await _store.FindPartyByPlayerAsync(scope.PlayerId, cancellationToken); if (party == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "玩家不在任何队伍中"); @@ -759,7 +753,7 @@ public async Task>> ListPendingInv return failure; } - var invites = await _store.ListInvitesAsync(scope.TenantId, scope.AppId, cancellationToken); + var invites = await _store.ListInvitesAsync(cancellationToken); var result = new List(); foreach (var invite in invites) { @@ -802,7 +796,7 @@ public async Task> BindMatchStateAsync(OnlineScope sco return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "匹配域不允许迁入状态:" + targetState); } - var party = await _store.FindPartyAsync(scope.TenantId, scope.AppId, partyId, cancellationToken); + var party = await _store.FindPartyAsync(partyId, cancellationToken); if (party == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "队伍不存在"); @@ -815,17 +809,15 @@ public async Task> BindMatchStateAsync(OnlineScope sco /// 扫描并终结过期对象:超期邀请置 ;空闲队伍置 /// 。匹配中与终态队伍不参与空闲过期。 /// - /// 租户标识。 - /// App 标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 /// 本次终结的(邀请 + 队伍)总数。 - public async Task> SweepExpiredAsync(long tenantId, long appId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task> SweepExpiredAsync(long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : Now(); var affected = 0; - var invites = await _store.ListInvitesAsync(tenantId, appId, cancellationToken); + var invites = await _store.ListInvitesAsync(cancellationToken); foreach (var invite in invites) { if (invite.State != OnlinePartyInviteState.Pending || invite.ExpiresAtTime > now) @@ -835,11 +827,11 @@ public async Task> SweepExpiredAsync(long tenantId, long appId invite.State = OnlinePartyInviteState.Expired; await _store.SaveInviteAsync(invite, cancellationToken); - await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.TenantId, invite.AppId, invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), 0), cancellationToken); + await _eventPublisher.PublishAsync(OnlinePartyEvents.CreateInviteChanged(invite.InviteeId, invite.InviteId, invite.PartyId, invite.InviterId, invite.State.ToString(), 0), cancellationToken); affected++; } - var parties = await _store.ListPartiesAsync(tenantId, appId, cancellationToken); + var parties = await _store.ListPartiesAsync(cancellationToken); foreach (var party in parties) { if (OnlinePartyStateMachine.IsTerminal(party.State) || party.State == OnlinePartyState.Matching) @@ -956,7 +948,7 @@ private async Task> TransitionAsync(OnlineParty party, party.UpdatedAtTime = Now(); party.ExpiresAtTime = party.UpdatedAtTime + _idleTimeToLiveSeconds * 1000; await _store.SavePartyAsync(party, cancellationToken); - await _eventPublisher.PublishAsync(OnlinePartyEvents.CreatePartyChanged(party.TenantId, party.AppId, party.ServerId, party.PartyId, party.LeaderId, from.ToString(), target.ToString(), reason.ToString(), party.Members == null ? 0 : party.Members.Count, correlationId), cancellationToken); + await _eventPublisher.PublishAsync(OnlinePartyEvents.CreatePartyChanged(party.ServerId, party.PartyId, party.LeaderId, from.ToString(), target.ToString(), reason.ToString(), party.Members == null ? 0 : party.Members.Count, correlationId), cancellationToken); return OnlineResult.Ok(party); } diff --git a/Capability/GameFrameX.Capability.Online.Operations/AdminApi/OnlineAdminConsoleHandlers.cs b/Capability/GameFrameX.Capability.Online.Operations/AdminApi/OnlineAdminConsoleHandlers.cs index ee2dcd4d4..b50e0f74d 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/AdminApi/OnlineAdminConsoleHandlers.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/AdminApi/OnlineAdminConsoleHandlers.cs @@ -162,7 +162,7 @@ private static async Task QueryOnlineAuditEventsAsync(AdminApiRequest re Cursor = OnlineAdminApiContract.ReadCursor(request), PageSize = OnlineAdminApiContract.ReadPageSize(request), }; - var page = OnlineAdminApiContract.Unwrap(await audit.QueryAsync(scope, query, cancellationToken).ConfigureAwait(false)); + var page = OnlineAdminApiContract.Unwrap(await audit.QueryAsync(query, cancellationToken).ConfigureAwait(false)); var items = new List(); if (page.Records != null) { diff --git a/Capability/GameFrameX.Capability.Online.Operations/AdminApi/OnlineAdminHotfixHandlers.cs b/Capability/GameFrameX.Capability.Online.Operations/AdminApi/OnlineAdminHotfixHandlers.cs index 73015142a..6c994c3b8 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/AdminApi/OnlineAdminHotfixHandlers.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/AdminApi/OnlineAdminHotfixHandlers.cs @@ -38,7 +38,7 @@ namespace GameFrameX.Capability.Online.Operations.AdminApi; ///(旧 ReloadHttpHandler HTTP 通道已退役)。 /// /// 维护约束:四 action 直接映射 服务面; -/// 作用域两键(TenantId/AppId)从 admin scope 锚定(清单是 App 级资产,ServerId 归一为 0,body 不携带作用域字段); +/// 清单是全局资产(单键化后无作用域锚定,body 不携带作用域字段); /// dispatcher 幂等包裹 = false——服务自幂等(登记按版本判重 / 激活幂等 / 切换命令服务内幂等先行), /// 不做双层包裹(grant 族先例)。 /// @@ -52,27 +52,24 @@ public static class OnlineAdminHotfixHandlers /// Hotfix 回滚受控服务(幂等基建缺席未装配时为 null,action 不可达)。 public static void RegisterHotfixActions(AdminActionRegistry registry, OnlineHotfixRollbackService service) { - registry.Register("register_hotfix_manifest", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => RegisterHotfixManifestAsync(request, scope, cancellationToken, service)), false); - registry.Register("activate_hotfix_version", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => ActivateHotfixVersionAsync(request, scope, cancellationToken, service)), false); - registry.Register("check_hotfix_compatibility", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => CheckHotfixCompatibilityAsync(request, scope, cancellationToken, service)), false); - registry.Register("rollback_hotfix_version", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => RollbackHotfixVersionAsync(request, scope, cancellationToken, service)), false); + registry.Register("register_hotfix_manifest", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => RegisterHotfixManifestAsync(request, cancellationToken, service)), false); + registry.Register("activate_hotfix_version", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => ActivateHotfixVersionAsync(request, cancellationToken, service)), false); + registry.Register("check_hotfix_compatibility", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => CheckHotfixCompatibilityAsync(request, cancellationToken, service)), false); + registry.Register("rollback_hotfix_version", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => RollbackHotfixVersionAsync(request, cancellationToken, service)), false); } /// /// register_hotfix_manifest:登记版本协议清单(发布流水线簿记;可携制品字段经获取器链先行落盘)。 /// /// 请求。 - /// 作用域(两键锚定:TenantId/AppId)。 /// 取消令牌。 /// Hotfix 回滚受控服务。 /// 登记回执。 - private static async Task RegisterHotfixManifestAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineHotfixRollbackService service) + private static async Task RegisterHotfixManifestAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineHotfixRollbackService service) { var manifest = new OnlineHotfixProtocolManifest { Version = OnlineAdminApiContract.RequireString(request, "Version"), - TenantId = scope.TenantId, - AppId = scope.AppId, Messages = ReadProtocolMessages(request), RegisteredTime = OnlineAdminApiContract.ReadOptionalInt64(request, "RegisteredTime") ?? OnlineAdminApiContract.NowSeconds() * 1000, ArtifactSourceUrl = OnlineAdminApiContract.ReadOptionalString(request, "ArtifactSourceUrl"), @@ -90,14 +87,13 @@ private static async Task RegisterHotfixManifestAsync(AdminApiRequest re /// activate_hotfix_version:激活已登记版本为活跃基线(装配面初始化入口)。 /// /// 请求。 - /// 作用域(两键锚定:TenantId/AppId)。 /// 取消令牌。 /// Hotfix 回滚受控服务。 /// 激活回执。 - private static async Task ActivateHotfixVersionAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineHotfixRollbackService service) + private static async Task ActivateHotfixVersionAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineHotfixRollbackService service) { var version = OnlineAdminApiContract.RequireString(request, "Version"); - OnlineAdminApiContract.Unwrap(await service.ActivateAsync(new OnlineScope(scope.TenantId, scope.AppId, 0), version, cancellationToken).ConfigureAwait(false)); + OnlineAdminApiContract.Unwrap(await service.ActivateAsync(version, cancellationToken).ConfigureAwait(false)); return new HotfixVersionActivateResponse { Version = version, @@ -109,14 +105,13 @@ private static async Task ActivateHotfixVersionAsync(AdminApiRequest req /// check_hotfix_compatibility:协议兼容只读预检(回滚演练 Runbook 面;不经幂等、不落审计、不触执行器)。 /// /// 请求。 - /// 作用域(两键锚定:TenantId/AppId)。 /// 取消令牌。 /// Hotfix 回滚受控服务。 /// 兼容检查报告。 - private static async Task CheckHotfixCompatibilityAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineHotfixRollbackService service) + private static async Task CheckHotfixCompatibilityAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineHotfixRollbackService service) { var targetVersion = OnlineAdminApiContract.RequireString(request, "TargetVersion"); - var report = OnlineAdminApiContract.Unwrap(await service.CheckProtocolCompatibilityAsync(new OnlineScope(scope.TenantId, scope.AppId, 0), targetVersion, cancellationToken).ConfigureAwait(false)); + var report = OnlineAdminApiContract.Unwrap(await service.CheckProtocolCompatibilityAsync(targetVersion, cancellationToken).ConfigureAwait(false)); return new HotfixCompatibilityCheckResponse { TargetVersion = targetVersion, @@ -131,15 +126,13 @@ private static async Task CheckHotfixCompatibilityAsync(AdminApiRequest /// rollback_hotfix_version:热更版本受控切换命令(幂等先行 → 兼容闸 → 审计先行 → 执行器 → 切活跃 → 事件)。 /// /// 请求。 - /// 作用域(两键锚定:TenantId/AppId)。 /// 取消令牌。 /// Hotfix 回滚受控服务。 /// 切换回执。 - private static async Task RollbackHotfixVersionAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineHotfixRollbackService service) + private static async Task RollbackHotfixVersionAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineHotfixRollbackService service) { var rollbackRequest = new OnlineHotfixRollbackRequest { - Scope = new OnlineScope(scope.TenantId, scope.AppId, 0), TargetVersion = OnlineAdminApiContract.RequireString(request, "TargetVersion"), OperatorId = OnlineAdminApiContract.RequireString(request, "OperatorId"), OperatorName = OnlineAdminApiContract.ReadOptionalString(request, "OperatorName"), @@ -218,7 +211,7 @@ public sealed class HotfixManifestRegisterResponse /// 获取或设置版本号。 public string Version { get; set; } - /// 获取或设置是否新登记(同 (作用域, 版本号) 已存在为 false,幂等回执不覆盖)。 + /// 获取或设置是否新登记(同版本号已存在为 false,幂等回执不覆盖)。 public bool IsNewRegistered { get; set; } } diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/IOnlineGameEventDeadLetterSink.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/IOnlineGameEventDeadLetterSink.cs index 82f7a503a..12c239b11 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/IOnlineGameEventDeadLetterSink.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/IOnlineGameEventDeadLetterSink.cs @@ -42,9 +42,7 @@ namespace GameFrameX.Capability.Online.Operations.GameEvents; /// 「不污染下游」的结构性保证即失效。 /// /// -/// 归档口径:死信按**事件自身的作用域**归档,故作用域非法的事件会落在其退化作用域 -/// (TenantId 或 AppId 为 0)之下——不丢失、可检索,但正常作用域的查询看不到它们, -/// 这类拒绝对投递方的可达路径是摄取回执。 +/// 归档口径:死信全量落档、按拒收时刻全局可检索(不丢失);这类拒绝对投递方的可达路径是摄取回执。 /// /// public interface IOnlineGameEventDeadLetterSink @@ -61,12 +59,10 @@ public interface IOnlineGameEventDeadLetterSink Task WriteAsync(OnlineEvent onlineEvent, OnlineGameEventRejectionReason reason, string message, long rejectedTime, CancellationToken cancellationToken = default); /// - /// 按作用域与时间窗列出死信(查询与指标复算入口;跨作用域查不到,反预言)。 + /// 按时间窗列出死信(查询与指标复算入口)。 /// - /// 租户标识。 - /// App 标识。 /// 时间窗查询载荷(闭区间;与事件存储同型)。 /// 取消令牌。 /// 死信列表(按拒收时刻升序);无记录返回空列表。 - Task> ListAsync(long tenantId, long appId, EventTimeRangeQuery query, CancellationToken cancellationToken = default); + Task> ListAsync(EventTimeRangeQuery query, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/IOnlineGameEventStore.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/IOnlineGameEventStore.cs index 1f0132715..7ec06c3ff 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/IOnlineGameEventStore.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/IOnlineGameEventStore.cs @@ -43,7 +43,7 @@ namespace GameFrameX.Capability.Online.Operations.GameEvents; /// (2) **事件标识唯一**(EventId 为幂等键):重复投递同一信封只落一条(返回 false), /// 否则重投会让指标翻倍、报表失真; /// (3) **追加即不可变**——只追加不修改不删除(留存与归档策略归运行时装配); -/// (4) 作用域隔离:查询以 (TenantId, AppId) 为前置条件,跨作用域查不到(反预言)。 +/// (4) 查询以时间窗为前置过滤条件(闭区间,边界确定供指标复算)。 /// /// public interface IOnlineGameEventStore @@ -65,12 +65,10 @@ public interface IOnlineGameEventStore Task FindAsync(string eventId, CancellationToken cancellationToken = default); /// - /// 按作用域与时间窗列出事件(按事件发生时刻升序,**含窗口两端**——指标复算要求边界确定)。 + /// 按时间窗列出事件(按事件发生时刻升序,**含窗口两端**——指标复算要求边界确定)。 /// - /// 租户标识。 - /// App 标识。 /// 时间窗查询载荷(闭区间)。 /// 取消令牌。 /// 事件列表;无记录返回空列表。 - Task> ListAsync(long tenantId, long appId, EventTimeRangeQuery query, CancellationToken cancellationToken = default); + Task> ListAsync(EventTimeRangeQuery query, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/InMemoryOnlineGameEventDeadLetterSink.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/InMemoryOnlineGameEventDeadLetterSink.cs index 3f8fe5126..183425d60 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/InMemoryOnlineGameEventDeadLetterSink.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/InMemoryOnlineGameEventDeadLetterSink.cs @@ -106,17 +106,15 @@ public Task WriteAsync(OnlineEvent onlineEvent, Onlin } /// - /// 在全局锁内按作用域与闭区间时间窗筛选内存中的死信。 + /// 在全局锁内按闭区间时间窗筛选内存中的死信。 /// /// - /// Filters the in-memory dead letters by scope and inclusive time window under the global lock. + /// Filters the in-memory dead letters by the inclusive time window under the global lock. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 时间窗查询载荷(闭区间)/ The time-range query payload (inclusive window) /// 取消令牌 / Cancellation token /// 匹配的死信列表(按写入即拒收顺序升序);无记录返回空列表 / The matched dead letters in write (rejection) order; an empty list when none match - public Task> ListAsync(long tenantId, long appId, EventTimeRangeQuery query, CancellationToken cancellationToken = default) + public Task> ListAsync(EventTimeRangeQuery query, CancellationToken cancellationToken = default) { var fromTime = query.FromTime; var toTime = query.ToTime; @@ -131,7 +129,7 @@ public Task> ListAsync(long tenantId, long appId } var onlineEvent = deadLetter.Event; - if (onlineEvent == null || onlineEvent.TenantId != tenantId || onlineEvent.AppId != appId) + if (onlineEvent == null) { continue; } diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/InMemoryOnlineGameEventStore.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/InMemoryOnlineGameEventStore.cs index 09e5146e1..16f13ff21 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/InMemoryOnlineGameEventStore.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/InMemoryOnlineGameEventStore.cs @@ -112,17 +112,15 @@ public Task FindAsync(string eventId, CancellationToken cancellatio } /// - /// 在全局锁内按作用域与闭区间时间窗筛选事件,并按事件发生时刻升序排序返回。 + /// 在全局锁内按闭区间时间窗筛选事件,并按事件发生时刻升序排序返回。 /// /// - /// Filters events by scope and inclusive time window under the global lock, returning them sorted ascending by occurred time. + /// Filters events by the inclusive time window under the global lock, returning them sorted ascending by occurred time. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 时间窗查询载荷(闭区间)/ The time-range query payload (inclusive window) /// 取消令牌 / Cancellation token /// 事件列表;无记录返回空列表 / The event list; an empty list when none match - public Task> ListAsync(long tenantId, long appId, EventTimeRangeQuery query, CancellationToken cancellationToken = default) + public Task> ListAsync(EventTimeRangeQuery query, CancellationToken cancellationToken = default) { var fromTime = query.FromTime; var toTime = query.ToTime; @@ -131,7 +129,7 @@ public Task> ListAsync(long tenantId, long appId, EventTimeRan { foreach (var stored in _events.Values) { - if (stored.TenantId != tenantId || stored.AppId != appId) + if (stored.OccurredTime < fromTime || stored.OccurredTime > toTime) { continue; } diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventMetrics.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventMetrics.cs index 2e7179427..56a7091a2 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventMetrics.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventMetrics.cs @@ -41,16 +41,6 @@ namespace GameFrameX.Capability.Online.Operations.GameEvents; /// public sealed class OnlineGameEventMetrics { - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置统计窗口起点(UTC 毫秒,含)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventMetricsService.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventMetricsService.cs index 3cac14bac..2519ccabe 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventMetricsService.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventMetricsService.cs @@ -69,25 +69,21 @@ public OnlineGameEventMetricsService(IOnlineGameEventStore eventStore, IOnlineGa } /// - /// 复算指定作用域与时间窗的事件指标。 + /// 复算指定时间窗的事件指标。 /// - /// 租户标识。 - /// App 标识。 /// 窗口起点(UTC 毫秒,含)。 /// 窗口终点(UTC 毫秒,含)。 /// 取消令牌。 /// 指标快照。 - public async Task ComputeAsync(long tenantId, long appId, long fromTime, long toTime, CancellationToken cancellationToken = default) + public async Task ComputeAsync(long fromTime, long toTime, CancellationToken cancellationToken = default) { var metrics = new OnlineGameEventMetrics { - TenantId = tenantId, - AppId = appId, FromTime = fromTime, ToTime = toTime, }; - var events = await _eventStore.ListAsync(tenantId, appId, new EventTimeRangeQuery { FromTime = fromTime, ToTime = toTime, }, cancellationToken).ConfigureAwait(false); + var events = await _eventStore.ListAsync(new EventTimeRangeQuery { FromTime = fromTime, ToTime = toTime, }, cancellationToken).ConfigureAwait(false); if (events != null) { var activePlayers = new HashSet(); @@ -116,7 +112,7 @@ public async Task ComputeAsync(long tenantId, long appId metrics.ActivePlayerCount = activePlayers.Count; } - var deadLetters = await _deadLetterSink.ListAsync(tenantId, appId, new EventTimeRangeQuery { FromTime = fromTime, ToTime = toTime, }, cancellationToken).ConfigureAwait(false); + var deadLetters = await _deadLetterSink.ListAsync(new EventTimeRangeQuery { FromTime = fromTime, ToTime = toTime, }, cancellationToken).ConfigureAwait(false); metrics.RejectedCount = deadLetters == null ? 0 : deadLetters.Count; return metrics; } diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventProjector.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventProjector.cs index adc8b4ea6..e1096b455 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventProjector.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventProjector.cs @@ -104,18 +104,18 @@ public List ProjectSessionEvents(OnlineSession session) switch (session.State) { case OnlineSessionState.Authenticated: - events.Add(Build(OnlineGameEventName.Login, session.TenantId, session.AppId, session.ServerId, session.PlayerId, Fallback(session.AuthenticatedAtTime, session.CreatedAtTime), session.Id, fields)); + events.Add(Build(OnlineGameEventName.Login, session.ServerId, session.PlayerId, Fallback(session.AuthenticatedAtTime, session.CreatedAtTime), session.Id, fields)); break; case OnlineSessionState.Connected: case OnlineSessionState.Active: case OnlineSessionState.Reconnecting: - events.Add(Build(OnlineGameEventName.SessionStart, session.TenantId, session.AppId, session.ServerId, session.PlayerId, Fallback(session.ConnectedAtTime, session.AuthenticatedAtTime), session.Id, fields)); + events.Add(Build(OnlineGameEventName.SessionStart, session.ServerId, session.PlayerId, Fallback(session.ConnectedAtTime, session.AuthenticatedAtTime), session.Id, fields)); break; case OnlineSessionState.Closed: case OnlineSessionState.Kicked: case OnlineSessionState.Expired: fields[OnlineGameEventFieldName.EndReason] = session.State.ToString(); - events.Add(Build(OnlineGameEventName.SessionEnd, session.TenantId, session.AppId, session.ServerId, session.PlayerId, Fallback(session.DisconnectAtTime, session.CreatedAtTime), session.Id, fields)); + events.Add(Build(OnlineGameEventName.SessionEnd, session.ServerId, session.PlayerId, Fallback(session.DisconnectAtTime, session.CreatedAtTime), session.Id, fields)); break; } @@ -145,7 +145,7 @@ public List ProjectMatchQueueEvents(OnlineMatchTicket ticket) var events = new List { - Build(OnlineGameEventName.MatchQueue, ticket.TenantId, ticket.AppId, ticket.ServerId, 0, ticket.CreatedAtTime, ticket.TicketId, fields), + Build(OnlineGameEventName.MatchQueue, ticket.ServerId, 0, ticket.CreatedAtTime, ticket.TicketId, fields), }; return events; } @@ -177,7 +177,7 @@ public List ProjectMatchEvents(OnlineMatch match) { OnlineGameEventFieldName.State, match.State.ToString() }, }; - events.Add(Build(OnlineGameEventName.MatchStart, match.TenantId, match.AppId, match.ServerId, 0, Fallback(match.StateChangedTime, match.CreatedTime), match.MatchId, fields)); + events.Add(Build(OnlineGameEventName.MatchStart, match.ServerId, 0, Fallback(match.StateChangedTime, match.CreatedTime), match.MatchId, fields)); return events; } @@ -208,7 +208,7 @@ public List ProjectMatchResultEvents(OnlineMatchResult result) var events = new List { - Build(OnlineGameEventName.MatchEnd, result.TenantId, result.AppId, result.ServerId, 0, occurredTime, result.MatchResultId, matchFields), + Build(OnlineGameEventName.MatchEnd, result.ServerId, 0, occurredTime, result.MatchResultId, matchFields), }; if (result.Entries == null) @@ -234,7 +234,7 @@ public List ProjectMatchResultEvents(OnlineMatchResult result) { OnlineGameEventFieldName.Score, FormatId(entry.Score) }, }; - events.Add(Build(name, result.TenantId, result.AppId, result.ServerId, entry.PlayerId, occurredTime, result.MatchResultId, playerFields)); + events.Add(Build(name, result.ServerId, entry.PlayerId, occurredTime, result.MatchResultId, playerFields)); } return events; @@ -290,7 +290,7 @@ public List ProjectAssetTransactionEvents(OnlineAssetTransaction tr { OnlineGameEventFieldName.ChangeCount, FormatId(transaction.ExpectedChangeCount) }, }; - events.Add(Build(name, transaction.TenantId, transaction.AppId, transaction.HomeServerId, transaction.PlayerId, Fallback(transaction.SettledTime, transaction.CreatedTime), transaction.TransactionId, fields)); + events.Add(Build(name, transaction.HomeServerId, transaction.PlayerId, Fallback(transaction.SettledTime, transaction.CreatedTime), transaction.TransactionId, fields)); return events; } @@ -325,7 +325,7 @@ public List ProjectReportCaseEvents(OnlineReportCase reportCase) { OnlineGameEventFieldName.ChatMessageId, reportCase.ChatMessageId ?? string.Empty }, }; - events.Add(Build(OnlineGameEventName.ChatReport, reportCase.TenantId, reportCase.AppId, 0, reportCase.ReporterId, Fallback(reportCase.CreatedAtTime, reportCase.UpdatedAtTime), reportCase.ReportId, fields)); + events.Add(Build(OnlineGameEventName.ChatReport, 0, reportCase.ReporterId, Fallback(reportCase.CreatedAtTime, reportCase.UpdatedAtTime), reportCase.ReportId, fields)); return events; } @@ -357,7 +357,7 @@ public List ProjectPunishmentEvents(OnlinePunishment punishment) { OnlineGameEventFieldName.ExpiresAtTime, FormatId(punishment.ExpiresAtTime) }, }; - events.Add(Build(OnlineGameEventName.Penalty, punishment.TenantId, punishment.AppId, 0, punishment.PlayerId, Fallback(punishment.EffectiveAtTime, punishment.CreatedAtTime), punishment.PunishmentId, fields)); + events.Add(Build(OnlineGameEventName.Penalty, 0, punishment.PlayerId, Fallback(punishment.EffectiveAtTime, punishment.CreatedAtTime), punishment.PunishmentId, fields)); return events; } @@ -388,15 +388,13 @@ public async Task> ProjectAsync(IReadOnlyList /// 构造标准游戏事件信封(载荷与载荷审计字段取同一份字段投影)。 /// /// 登记表内的事件名。 - /// 租户标识。 - /// App 标识。 /// 区服标识(无归属服传 0)。 /// 玩家标识(聚合事件传 0)。 /// 事件发生时刻(UTC 毫秒;小于等于 0 时取当前时刻)。 /// 关联领域标识。 /// 载荷字段投影(同时充当 PayloadAuditFields)。 /// 事件信封实例。 - private static OnlineEvent Build(string eventName, long tenantId, long appId, long serverId, long playerId, long occurredTime, string correlationId, Dictionary fields) + private static OnlineEvent Build(string eventName, long serverId, long playerId, long occurredTime, string correlationId, Dictionary fields) { return new OnlineEvent { @@ -404,8 +402,6 @@ private static OnlineEvent Build(string eventName, long tenantId, long appId, lo EventType = eventName, OccurredTime = occurredTime > 0 ? occurredTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = playerId, Source = OnlineGameEventSchema.Source, diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventRejectionReason.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventRejectionReason.cs index 7bd88cbf9..ac183130b 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventRejectionReason.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventRejectionReason.cs @@ -30,7 +30,7 @@ namespace GameFrameX.Capability.Online.Operations.GameEvents; /// -/// 游戏事件基础校验的拒绝码(四类拒绝;**不是** OnlineErrorCode)。 +/// 游戏事件基础校验的拒绝码(**不是** OnlineErrorCode)。 /// /// 维护约束(红线):拒绝码描述的是**脏事件本身**(投递方数据问题),不是业务判定结果, /// 因而不占用 23 个已冻结的 OnlineErrorCode 成员(对齐 OnlineSocialDecision / @@ -51,6 +51,6 @@ public enum OnlineGameEventRejectionReason /// 必需字段缺失(登记表声明的必需载荷字段未在载荷中提供)。 MissingRequiredField = 3, - /// 作用域非法(TenantId 或 AppId 非正数——无法归属的事件无法被任何下游消费)。 + /// 作用域非法(单键化后事件信封已无租户/App 位,基础校验不再产生该拒绝;值保留供历史死信兼容)。 InvalidScope = 4, } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventValidator.cs b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventValidator.cs index 535cf0dac..6b7a3da3d 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventValidator.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/GameEvents/OnlineGameEventValidator.cs @@ -34,7 +34,7 @@ namespace GameFrameX.Capability.Online.Operations.GameEvents; /// -/// 游戏事件基础校验器:登记表驱动的四类拒绝。 +/// 游戏事件基础校验器:登记表驱动的三类拒绝。 /// /// 维护约束(红线): /// (1) **校验依据全部来自登记表**()——事件名、版本上限、必需字段 @@ -48,7 +48,7 @@ namespace GameFrameX.Capability.Online.Operations.GameEvents; public static class OnlineGameEventValidator { /// - /// 执行基础校验(按耗时从低到高的顺序:作用域 → 事件名 → 版本 → 必需字段)。 + /// 执行基础校验(按耗时从低到高的顺序:事件名 → 版本 → 必需字段)。 /// /// 待校验的事件信封。 /// 校验结果。 @@ -59,13 +59,6 @@ public static OnlineGameEventValidationResult Validate(OnlineEvent onlineEvent) return OnlineGameEventValidationResult.Reject(OnlineGameEventRejectionReason.UnknownEventName, "事件为空"); } - if (onlineEvent.TenantId <= 0 || onlineEvent.AppId <= 0) - { - return OnlineGameEventValidationResult.Reject( - OnlineGameEventRejectionReason.InvalidScope, - "事件作用域非法:TenantId=" + onlineEvent.TenantId.ToString(CultureInfo.InvariantCulture) + ",AppId=" + onlineEvent.AppId.ToString(CultureInfo.InvariantCulture)); - } - var descriptor = OnlineGameEventSchema.Find(onlineEvent.EventType); if (descriptor == null) { diff --git a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/IOnlineHotfixVersionStore.cs b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/IOnlineHotfixVersionStore.cs index 1653c3f2f..728028ff4 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/IOnlineHotfixVersionStore.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/IOnlineHotfixVersionStore.cs @@ -34,10 +34,10 @@ namespace GameFrameX.Capability.Online.Operations.HotfixRollback; /// /// Hotfix 版本清单存储契约(版本协议清单登记簿 + 活跃版本指针; -/// 作用域按 (TenantId, AppId) 两键隔离——清单是 App 级资产,ServerId 固定 0 不参与定位)。 +/// 清单是全局资产,单键化后无作用域隔离位,按版本号全局定位)。 /// /// 维护约束(红线): -/// ① 登记幂等判重——同 (作用域, 版本号) 重复登记返回「非新登记」且不覆盖既有清单 +/// ① 登记幂等判重——同版本号重复登记返回「非新登记」且不覆盖既有清单 /// (清单一经登记不可变更,历史清单稳定是回滚兼容判定的前提); /// ② 活跃版本切换与登记判重在实现内须处同一临界区(并发登记 + 切换不得撕裂状态); /// ③ 出入参防御性拷贝(持久化行语义,调用方引用不得别名存储内部状态)。 @@ -48,38 +48,32 @@ public interface IOnlineHotfixVersionStore /// /// 登记一份版本协议清单(发布流水线簿记;不改变活跃版本,不落审计)。 /// - /// 待登记清单(版本号在同作用域内唯一)。 + /// 待登记清单(版本号全局唯一)。 /// 取消令牌。 - /// 新登记返回 true;同 (作用域, 版本号) 已存在返回 false(幂等回执,不覆盖既有清单)。 + /// 新登记返回 true;同版本号已存在返回 false(幂等回执,不覆盖既有清单)。 Task RegisterAsync(OnlineHotfixProtocolManifest manifest, CancellationToken cancellationToken = default); /// /// 按版本号查找清单(只读)。 /// - /// 租户标识。 - /// App 标识。 /// 版本号。 /// 取消令牌。 /// 清单快照;未登记返回 。 - Task FindAsync(long tenantId, long appId, string version, CancellationToken cancellationToken = default); + Task FindAsync(string version, CancellationToken cancellationToken = default); /// /// 查找当前活跃版本清单(只读)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 活跃清单快照;从未激活返回 。 - Task FindActiveAsync(long tenantId, long appId, CancellationToken cancellationToken = default); + Task FindActiveAsync(CancellationToken cancellationToken = default); /// /// 把活跃版本切换到已登记的目标版本(回滚链路在执行器成功后调用)。 /// - /// 租户标识。 - /// App 标识。 /// 目标版本号(须已登记)。 /// 取消令牌。 /// 切换前的活跃版本号(从未激活返回空字符串)。 /// 目标版本未登记。 - Task SetActiveAsync(long tenantId, long appId, string version, CancellationToken cancellationToken = default); + Task SetActiveAsync(string version, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/InMemoryOnlineHotfixVersionStore.cs b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/InMemoryOnlineHotfixVersionStore.cs index 1ebd45e62..138efcf10 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/InMemoryOnlineHotfixVersionStore.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/InMemoryOnlineHotfixVersionStore.cs @@ -28,7 +28,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Threading; using System.Threading.Tasks; using GameFrameX.Foundation.Localization.Core; @@ -39,7 +38,7 @@ namespace GameFrameX.Capability.Online.Operations.HotfixRollback; /// Hotfix 版本清单内存存储(单进程默认实现;生产持久化实现归运行时装配,X4)。 /// /// 维护约束:「登记判重 + 落档」与「活跃版本切换」在 锁内**同一临界区**完成 -/// (并发登记与切换不撕裂);作用域索引键为 (TenantId, AppId) 两键;出入参防御性拷贝 +/// (并发登记与切换不撕裂);出入参防御性拷贝 /// (持久化行语义,调用方引用不得别名存储内部状态)。 /// /// @@ -56,9 +55,9 @@ public sealed class InMemoryOnlineHotfixVersionStore : IOnlineHotfixVersionStore private readonly object _gate = new(); /// - /// 作用域级状态索引(键 = "TenantId|AppId";值为作用域内的版本登记簿与活跃指针)。 + /// 版本登记簿与活跃指针(全局唯一状态;清单是全局资产,无作用域隔离位)。 /// - private readonly Dictionary _statesByScope = new(StringComparer.Ordinal); + private readonly RegistryState _state = new RegistryState(); /// /// 登记一份版本协议清单(锁内判重 + 落档同一临界区;重复登记不覆盖)。 @@ -75,7 +74,7 @@ public Task RegisterAsync(OnlineHotfixProtocolManifest manifest, Cancellat lock (_gate) { - var state = GetOrCreateState(manifest.TenantId, manifest.AppId); + var state = _state; if (state.Manifests.ContainsKey(manifest.Version)) { return Task.FromResult(false); @@ -89,17 +88,15 @@ public Task RegisterAsync(OnlineHotfixProtocolManifest manifest, Cancellat /// /// 按版本号查找清单(快照拷贝)。 /// - /// 租户标识。 - /// App 标识。 /// 版本号。 /// 取消令牌(内存实现无异步等待,令牌仅契约对齐)。 /// 清单快照;未登记返回 。 - public Task FindAsync(long tenantId, long appId, string version, CancellationToken cancellationToken = default) + public Task FindAsync(string version, CancellationToken cancellationToken = default) { lock (_gate) { - var state = FindState(tenantId, appId); - if (state == null || !state.Manifests.TryGetValue(version, out var manifest)) + var state = _state; + if (!state.Manifests.TryGetValue(version, out var manifest)) { return Task.FromResult(null); } @@ -111,16 +108,14 @@ public Task FindAsync(long tenantId, long appId, s /// /// 查找当前活跃版本清单(快照拷贝)。 /// - /// 租户标识。 - /// App 标识。 /// 取消令牌(内存实现无异步等待,令牌仅契约对齐)。 /// 活跃清单快照;从未激活返回 。 - public Task FindActiveAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task FindActiveAsync(CancellationToken cancellationToken = default) { lock (_gate) { - var state = FindState(tenantId, appId); - if (state == null || string.IsNullOrEmpty(state.ActiveVersion) || !state.Manifests.TryGetValue(state.ActiveVersion, out var manifest)) + var state = _state; + if (string.IsNullOrEmpty(state.ActiveVersion) || !state.Manifests.TryGetValue(state.ActiveVersion, out var manifest)) { return Task.FromResult(null); } @@ -132,16 +127,14 @@ public Task FindActiveAsync(long tenantId, long ap /// /// 把活跃版本切换到已登记的目标版本(锁内完成;返回切换前活跃版本号)。 /// - /// 租户标识。 - /// App 标识。 /// 目标版本号(须已登记)。 /// 取消令牌(内存实现无异步等待,令牌仅契约对齐)。 /// 切换前的活跃版本号(从未激活返回空字符串)。 - public Task SetActiveAsync(long tenantId, long appId, string version, CancellationToken cancellationToken = default) + public Task SetActiveAsync(string version, CancellationToken cancellationToken = default) { lock (_gate) { - var state = GetOrCreateState(tenantId, appId); + var state = _state; if (!state.Manifests.ContainsKey(version)) { // Localization: Online.HotfixRollback.TargetVersionNotRegistered - 目标版本未登记,拒绝切换活跃版本:{0} @@ -154,47 +147,6 @@ public Task SetActiveAsync(long tenantId, long appId, string version, Ca } } - /// - /// 查找作用域状态(不在锁内新建)。 - /// - /// 租户标识。 - /// App 标识。 - /// 作用域状态;作用域无任何登记返回 。 - private ScopeState FindState(long tenantId, long appId) - { - var scopeKey = BuildScopeKey(tenantId, appId); - return _statesByScope.TryGetValue(scopeKey, out var state) ? state : null; - } - - /// - /// 获取或创建作用域状态(调用方须持 )。 - /// - /// 租户标识。 - /// App 标识。 - /// 作用域状态。 - private ScopeState GetOrCreateState(long tenantId, long appId) - { - var scopeKey = BuildScopeKey(tenantId, appId); - if (!_statesByScope.TryGetValue(scopeKey, out var state)) - { - state = new ScopeState(); - _statesByScope[scopeKey] = state; - } - - return state; - } - - /// - /// 构造作用域索引键("TenantId|AppId")。 - /// - /// 租户标识。 - /// App 标识。 - /// 作用域键。 - private static string BuildScopeKey(long tenantId, long appId) - { - return tenantId.ToString(CultureInfo.InvariantCulture) + "|" + appId.ToString(CultureInfo.InvariantCulture); - } - /// /// 深拷贝清单(含消息契约行集合;持久化行语义——出入参不与存储内部状态别名)。 /// @@ -220,17 +172,15 @@ private static OnlineHotfixProtocolManifest CloneManifest(OnlineHotfixProtocolMa return new OnlineHotfixProtocolManifest { Version = manifest.Version, - TenantId = manifest.TenantId, - AppId = manifest.AppId, Messages = messages, RegisteredTime = manifest.RegisteredTime, }; } /// - /// 作用域级状态(版本登记簿 + 活跃版本指针)。 + /// 版本登记簿与活跃指针(全局唯一状态)。 /// - private sealed class ScopeState + private sealed class RegistryState { /// /// 版本登记簿(版本号 → 清单;一经登记不可变更)。 diff --git a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixEvents.cs b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixEvents.cs index 4ef55380f..eed76ca22 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixEvents.cs @@ -58,13 +58,11 @@ public static class OnlineHotfixEvents /// /// 构造版本清单登记事件。 /// - /// 租户标识。 - /// App 标识。 /// 版本号。 /// 登记时刻(UTC 毫秒)。 /// 协议消息契约行数(清单行集合为空时传 0)。 /// 事件信封实例。 - public static OnlineEvent CreateVersionRegistered(long tenantId, long appId, string version, long registeredTime, int messageCount) + public static OnlineEvent CreateVersionRegistered(string version, long registeredTime, int messageCount) { var payload = new VersionRegisteredPayload { @@ -84,8 +82,6 @@ public static OnlineEvent CreateVersionRegistered(long tenantId, long appId, str EventType = VersionRegistered, OccurredTime = registeredTime > 0 ? registeredTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -98,13 +94,11 @@ public static OnlineEvent CreateVersionRegistered(long tenantId, long appId, str /// /// 构造 Hotfix 回滚事件(切换成功后发布;兼容摘要为三类差异计数)。 /// - /// 租户标识。 - /// App 标识。 /// 回滚前活跃版本号。 /// 回滚到的目标版本号。 /// 协议兼容报告摘要(Removed/Changed/Added 计数文本)。 /// 事件信封实例。 - public static OnlineEvent CreateRolledBack(long tenantId, long appId, string previousVersion, string targetVersion, string compatibilitySummary) + public static OnlineEvent CreateRolledBack(string previousVersion, string targetVersion, string compatibilitySummary) { var payload = new RolledBackPayload { @@ -124,8 +118,6 @@ public static OnlineEvent CreateRolledBack(long tenantId, long appId, string pre EventType = RolledBack, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixProtocolManifest.cs b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixProtocolManifest.cs index 9088941af..4a704d4d4 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixProtocolManifest.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixProtocolManifest.cs @@ -36,8 +36,7 @@ namespace GameFrameX.Capability.Online.Operations.HotfixRollback; /// 协议兼容检查以「当前活跃清单 vs 目标回滚清单」比对)。 /// /// 维护约束(红线): -/// ① 清单是 App 级资产——作用域锚定 / 两键, -/// ServerId 固定 0(对齐统一审计「远程配置等 App 级操作」口径); +/// ① 清单是**全局资产**(单键化后无作用域锚定位,登记与活跃指针按版本号全局定位); /// ② 清单一经登记不可变更(存储按版本号判重,重复登记幂等回执、不覆盖既有行—— /// 回滚兼容判定的前提是历史清单稳定);版本号须与 Hotfix 程序集版本(HotfixManager.dllVersion 契约)一致; /// ③ 版本号禁止包含竖线 |(幂等回放令牌与规范化请求文本的分隔符,防止回放令牌损坏), @@ -48,20 +47,10 @@ namespace GameFrameX.Capability.Online.Operations.HotfixRollback; public sealed class OnlineHotfixProtocolManifest { /// - /// 获取或设置版本号(与 Hotfix 程序集版本一致;同作用域内唯一,禁止包含 | 与路径分隔符 /「..」段)。 + /// 获取或设置版本号(与 Hotfix 程序集版本一致;全局唯一,禁止包含 | 与路径分隔符 /「..」段)。 /// public string Version { get; set; } - /// - /// 获取或设置租户标识(必填,必须大于 0)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(必填,必须大于 0)。 - /// - public long AppId { get; set; } - /// /// 获取或设置协议消息契约行集合(同清单内消息名与消息号均唯一;可为空集合,表示该版本无对外协议面)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixRollbackRequest.cs b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixRollbackRequest.cs index 932e1a75b..bd823f115 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixRollbackRequest.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixRollbackRequest.cs @@ -26,27 +26,19 @@ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== -using GameFrameX.Capability.Online.Abstractions.Scope; - namespace GameFrameX.Capability.Online.Operations.HotfixRollback; /// /// Hotfix 回滚命令请求(回滚是唯一受控操作——操作者显式命令 + 审计; /// 登记(Register)与激活(Activate)为簿记 / 装配面初始化入口,不落审计)。 /// -/// 维护约束(红线): 只锚定 TenantId/AppId 两键(App 级资产,ServerId 固定 0 -/// ——服务内统一归一,调用方传入的 ServerId 不参与定位);、、 +/// 维护约束(红线):、、 /// 、 必填(宁拒毋缺,缺失拒绝 4001); /// 幂等键承载「回滚到版本 X」这一业务意图——相同键不同意图判 6002 冲突。 /// /// public sealed class OnlineHotfixRollbackRequest { - /// - /// 获取或设置生效作用域(服务内只用 TenantId/AppId 两键定位,ServerId 归一为 0)。 - /// - public OnlineScope Scope { get; set; } - /// /// 获取或设置目标回滚版本号(须已登记清单;禁止包含 |)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixRollbackService.cs b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixRollbackService.cs index 18e39defa..35af51ee5 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixRollbackService.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/HotfixRollback/OnlineHotfixRollbackService.cs @@ -52,8 +52,8 @@ namespace GameFrameX.Capability.Online.Operations.HotfixRollback; /// ② 登记 / 激活不落审计——登记是发布流水线簿记、激活是装配面初始化入口,回滚是唯一受控操作 /// (操作者显式命令 + 审计);回滚审计标识从命令幂等键确定性派生(hotfix-rollback-{幂等键}, /// 重复执行同一命令命中同一条审计); -/// ③ 作用域两键锚定——清单与活跃指针是 App 级资产,服务内统一以 (TenantId, AppId) 定位并归一 -/// ServerId = 0(对齐审计口径);多实例逐实例回滚编排归运维,本服务单进程语义; +/// ③ 清单与活跃指针是全局资产(单键化后无作用域锚定位;原「App 级资产」口径)——服务内按版本号 +/// 全局定位(对齐审计口径);多实例逐实例回滚编排归运维,本服务单进程语义; /// ④ 依赖方向——实际 DLL 加载切换经 承载(装配面), /// 本模块不引用 Core。 /// ⑤ 状态收敛与轨迹——执行器切换成功后,活跃指针写入失败自动重试(指数退避,至多 @@ -152,7 +152,7 @@ public OnlineHotfixRollbackService(IOnlineHotfixVersionStore store, OnlineIdempo /// /// 待登记清单。 /// 取消令牌。 - /// 新登记返回 true;同 (作用域, 版本号) 已存在返回 false;清单非法返回 4001; + /// 新登记返回 true;同版本号已存在返回 false;清单非法返回 4001; /// 制品获取失败或获取器未装配返回 8002(登记未生效)。 public async Task> RegisterAsync(OnlineHotfixProtocolManifest manifest, CancellationToken cancellationToken = default) { @@ -176,7 +176,7 @@ public async Task> RegisterAsync(OnlineHotfixProtocolManifest var isNew = await _store.RegisterAsync(manifest, cancellationToken).ConfigureAwait(false); if (isNew && _eventPublisher != null) { - await _eventPublisher.PublishAsync(OnlineHotfixEvents.CreateVersionRegistered(manifest.TenantId, manifest.AppId, manifest.Version, manifest.RegisteredTime, manifest.Messages?.Count ?? 0), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineHotfixEvents.CreateVersionRegistered(manifest.Version, manifest.RegisteredTime, manifest.Messages?.Count ?? 0), cancellationToken).ConfigureAwait(false); } return OnlineResult.Ok(isNew); @@ -185,49 +185,35 @@ public async Task> RegisterAsync(OnlineHotfixProtocolManifest /// /// 激活一个已登记版本为活跃版本(装配面初始化入口:不落审计、不经幂等)。 /// - /// 生效作用域(只用 TenantId/AppId 两键定位)。 /// 目标版本号(须已登记)。 /// 取消令牌。 - /// 激活成功(重复激活同版本幂等返回成功);作用域缺失 4001、版本未登记 4002。 - public async Task> ActivateAsync(OnlineScope scope, string version, CancellationToken cancellationToken = default) + /// 激活成功(重复激活同版本幂等返回成功);版本未登记 4002。 + public async Task> ActivateAsync(string version, CancellationToken cancellationToken = default) { - var scopeValidation = ValidateTwoKeyScope(scope); - if (scopeValidation != null) - { - return scopeValidation; - } - if (string.IsNullOrWhiteSpace(version) || version.IndexOf('|') >= 0) { return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "版本号必填且禁止包含竖线(回放令牌分隔符)"); } - var manifest = await _store.FindAsync(scope.TenantId, scope.AppId, version, cancellationToken).ConfigureAwait(false); + var manifest = await _store.FindAsync(version, cancellationToken).ConfigureAwait(false); if (manifest == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "目标版本未登记清单,无法激活:" + version); } - await _store.SetActiveAsync(scope.TenantId, scope.AppId, version, cancellationToken).ConfigureAwait(false); + await _store.SetActiveAsync(version, cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(true); } /// /// 协议兼容预检(只读演练入口:回滚演练 Runbook / Admin 预检调用;不经幂等、不落审计、不触执行器)。 /// - /// 生效作用域(只用 TenantId/AppId 两键定位)。 /// 目标回滚版本号。 /// 取消令牌。 - /// 兼容检查报告;作用域缺失 4001、目标未登记 4002、无活跃版本 5001。 - public async Task> CheckProtocolCompatibilityAsync(OnlineScope scope, string targetVersion, CancellationToken cancellationToken = default) + /// 兼容检查报告;目标未登记 4002、无活跃版本 5001。 + public async Task> CheckProtocolCompatibilityAsync(string targetVersion, CancellationToken cancellationToken = default) { - var scopeValidation = ValidateTwoKeyScope(scope); - if (scopeValidation != null) - { - return OnlineResult.Fail(scopeValidation.Code, scopeValidation.Message); - } - - var preparation = await PrepareTargetAndCurrentAsync(scope.TenantId, scope.AppId, targetVersion, cancellationToken).ConfigureAwait(false); + var preparation = await PrepareTargetAndCurrentAsync(targetVersion, cancellationToken).ConfigureAwait(false); if (!preparation.IsSuccess) { return OnlineResult.Fail(preparation.Code, preparation.Message); @@ -253,8 +239,9 @@ public async Task> RollbackAsync(Online return validation; } - var anchor = new OnlineScope(request.Scope.TenantId, request.Scope.AppId, 0); - var outcome = await _idempotencyService.BeginAsync(anchor, request.IdempotencyKey, BuildCanonicalRequestText(anchor, request), false, cancellationToken).ConfigureAwait(false); + // 幂等锚点:清单与活跃指针是全局资产(原 App 级),锚定不带区服位——回滚命令的幂等键不随区服分裂。 + var anchor = new OnlineScope(0); + var outcome = await _idempotencyService.BeginAsync(anchor, request.IdempotencyKey, BuildCanonicalRequestText(request), false, cancellationToken).ConfigureAwait(false); if (!outcome.CanExecute) { return await ResolveNonExecuteOutcomeAsync(request, outcome, cancellationToken).ConfigureAwait(false); @@ -273,13 +260,13 @@ public async Task> RollbackAsync(Online /// 回滚命令的清单守卫链(目标可寻 4002 / 有活跃 5001 / 目标≠当前 5003 / 协议兼容 6002; /// 任一守卫失败把幂等键落定失败后返回错误——失败命令不得占住幂等占位)。 /// - /// 两键锚定作用域。 + /// 全局锚定作用域(幂等键空间锚点)。 /// 回滚命令请求。 /// 取消令牌。 /// 守卫通过返回回滚准备物(目标清单 + 当前清单 + 兼容报告);否则返回对应错误。 private async Task> PrepareRollbackAsync(OnlineScope anchor, OnlineHotfixRollbackRequest request, CancellationToken cancellationToken) { - var guard = await PrepareTargetAndCurrentAsync(anchor.TenantId, anchor.AppId, request.TargetVersion, cancellationToken).ConfigureAwait(false); + var guard = await PrepareTargetAndCurrentAsync(request.TargetVersion, cancellationToken).ConfigureAwait(false); if (!guard.IsSuccess) { await FailIdempotencyAsync(anchor, request.IdempotencyKey, cancellationToken).ConfigureAwait(false); @@ -307,14 +294,14 @@ private async Task> PrepareRollbackAsync(Onlin /// 回滚执行链(审计先行 → 执行器 → 切活跃(失败指数退避重试,耗尽反切)→ 事件 → 幂等落定; /// 全程状态变迁经 落轨迹)。 /// - /// 两键锚定作用域。 + /// 全局锚定作用域(幂等落定锚点)。 /// 回滚命令请求。 /// 守卫链产物(目标清单 + 当前清单 + 兼容报告)。 /// 取消令牌。 /// 回滚回执。 private async Task> ExecuteRollbackAsync(OnlineScope anchor, OnlineHotfixRollbackRequest request, RollbackPreparation preparation, CancellationToken cancellationToken) { - var auditFailure = await IngestRollbackAuditAsync(anchor, request, preparation, cancellationToken).ConfigureAwait(false); + var auditFailure = await IngestRollbackAuditAsync(request, preparation, cancellationToken).ConfigureAwait(false); if (auditFailure != null) { await FailIdempotencyAsync(anchor, request.IdempotencyKey, cancellationToken).ConfigureAwait(false); @@ -328,7 +315,7 @@ private async Task> ExecuteRollbackAsyn } // 状态轨迹:审计已落、守卫已过——执行链正式启动(此前任何失败点状态零变迁,结果码即终态)。 - WriteLog(RollbackLogLevel.Info, BuildTraceMessage(anchor, request, "chain-started", "previous=" + preparation.Current.Version + "|target=" + request.TargetVersion)); + WriteLog(RollbackLogLevel.Info, BuildTraceMessage(request, "chain-started", "previous=" + preparation.Current.Version + "|target=" + request.TargetVersion)); try { @@ -337,15 +324,15 @@ private async Task> ExecuteRollbackAsyn catch (Exception ex) { // 状态轨迹:执行器未切换成功,系统仍在旧版本(状态一致)——失败结果码即终态,无须补偿。 - WriteLog(RollbackLogLevel.Warn, BuildTraceMessage(anchor, request, "executor-switch-failed", "target=" + request.TargetVersion + "|error=" + ex.Message)); + WriteLog(RollbackLogLevel.Warn, BuildTraceMessage(request, "executor-switch-failed", "target=" + request.TargetVersion + "|error=" + ex.Message)); await FailIdempotencyAsync(anchor, request.IdempotencyKey, cancellationToken).ConfigureAwait(false); return OnlineResult.Fail(OnlineErrorCode.DependencyUnavailable, "回滚执行器执行失败(回滚未生效):" + ex.Message); } // 状态轨迹:执行器已切到目标版本——此后到活跃指针落定之间是两处状态可能分叉的窗口。 - WriteLog(RollbackLogLevel.Info, BuildTraceMessage(anchor, request, "executor-switched", "target=" + request.TargetVersion)); + WriteLog(RollbackLogLevel.Info, BuildTraceMessage(request, "executor-switched", "target=" + request.TargetVersion)); - var switchOutcome = await SwitchActiveVersionWithRetryAsync(anchor, request, preparation, cancellationToken).ConfigureAwait(false); + var switchOutcome = await SwitchActiveVersionWithRetryAsync(request, preparation, cancellationToken).ConfigureAwait(false); if (!switchOutcome.IsSuccess) { await FailIdempotencyAsync(anchor, request.IdempotencyKey, cancellationToken).ConfigureAwait(false); @@ -355,12 +342,12 @@ private async Task> ExecuteRollbackAsyn var previousVersion = switchOutcome.Data; // 状态轨迹:活跃指针已切换——执行器与指针同指目标版本,状态回到一致。 - WriteLog(RollbackLogLevel.Info, BuildTraceMessage(anchor, request, "pointer-switched", "previous=" + previousVersion + "|target=" + request.TargetVersion)); + WriteLog(RollbackLogLevel.Info, BuildTraceMessage(request, "pointer-switched", "previous=" + previousVersion + "|target=" + request.TargetVersion)); var summary = BuildCompatibilitySummary(preparation.Report); if (_eventPublisher != null) { - await _eventPublisher.PublishAsync(OnlineHotfixEvents.CreateRolledBack(anchor.TenantId, anchor.AppId, previousVersion, request.TargetVersion, summary), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineHotfixEvents.CreateRolledBack(previousVersion, request.TargetVersion, summary), cancellationToken).ConfigureAwait(false); } var result = new OnlineHotfixRollbackResult @@ -373,7 +360,7 @@ private async Task> ExecuteRollbackAsyn await _idempotencyService.CompleteAsync(anchor, request.IdempotencyKey, EncodeReplayToken(previousVersion, request.TargetVersion, summary), false, cancellationToken).ConfigureAwait(false); // 状态轨迹:事件已发、幂等已落定——回滚完成(终态 = 执行器与活跃指针同指目标版本)。 - WriteLog(RollbackLogLevel.Info, BuildTraceMessage(anchor, request, "rollback-completed", "previous=" + previousVersion + "|target=" + request.TargetVersion)); + WriteLog(RollbackLogLevel.Info, BuildTraceMessage(request, "rollback-completed", "previous=" + previousVersion + "|target=" + request.TargetVersion)); return OnlineResult.Ok(result); } @@ -382,12 +369,11 @@ private async Task> ExecuteRollbackAsyn /// 第 n 次失败后延迟 基准 × 2^(n-1);重试耗尽进入反切补偿——执行器已切换而指针未落时, /// 不再裸露不一致状态,逐次尝试与耗尽均落状态轨迹)。 /// - /// 两键锚定作用域。 /// 回滚命令请求。 /// 守卫链产物(Current = 反切锚定的旧版本)。 /// 取消令牌(取消视同本次尝试失败,照常进入补偿链)。 /// 成功返回切换前活跃版本号;重试耗尽返回反切结果(已反切 = 状态一致 5000 可重试 / 反切失败 = 须对账 5000)。 - private async Task> SwitchActiveVersionWithRetryAsync(OnlineScope anchor, OnlineHotfixRollbackRequest request, RollbackPreparation preparation, CancellationToken cancellationToken) + private async Task> SwitchActiveVersionWithRetryAsync(OnlineHotfixRollbackRequest request, RollbackPreparation preparation, CancellationToken cancellationToken) { var totalAttempts = 1 + ActivePointerWriteMaxRetryCount; Exception lastFailure = null; @@ -395,7 +381,7 @@ private async Task> SwitchActiveVersionWithRetryAsync(Onlin { try { - var previousVersion = await _store.SetActiveAsync(anchor.TenantId, anchor.AppId, request.TargetVersion, cancellationToken).ConfigureAwait(false); + var previousVersion = await _store.SetActiveAsync(request.TargetVersion, cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(previousVersion); } catch (Exception ex) @@ -409,7 +395,7 @@ private async Task> SwitchActiveVersionWithRetryAsync(Onlin var retryDelayMilliseconds = GetExponentialBackoffMilliseconds(attempt); // 状态轨迹:指针写入单次失败——记录第几次 / 共几次与退避间隔,失败点可还原。 - WriteLog(RollbackLogLevel.Warn, BuildTraceMessage(anchor, request, "pointer-write-failed", "attempt=" + attempt + "/" + totalAttempts + "|retryInMilliseconds=" + retryDelayMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture) + "|error=" + ex.Message)); + WriteLog(RollbackLogLevel.Warn, BuildTraceMessage(request, "pointer-write-failed", "attempt=" + attempt + "/" + totalAttempts + "|retryInMilliseconds=" + retryDelayMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture) + "|error=" + ex.Message)); try { await Task.Delay(TimeSpan.FromMilliseconds(retryDelayMilliseconds), cancellationToken).ConfigureAwait(false); @@ -425,20 +411,19 @@ private async Task> SwitchActiveVersionWithRetryAsync(Onlin var lastFailureMessage = lastFailure == null ? string.Empty : lastFailure.Message; // 状态轨迹:重试耗尽——进入反切补偿(此行之后执行器与指针可能短暂分叉,以反切结果行收束)。 - WriteLog(RollbackLogLevel.Error, BuildTraceMessage(anchor, request, "pointer-write-exhausted", "attempts=" + totalAttempts.ToString(System.Globalization.CultureInfo.InvariantCulture) + "|error=" + lastFailureMessage)); - return await RevertExecutorAfterPointerFailureAsync(anchor, request, preparation, lastFailureMessage).ConfigureAwait(false); + WriteLog(RollbackLogLevel.Error, BuildTraceMessage(request, "pointer-write-exhausted", "attempts=" + totalAttempts.ToString(System.Globalization.CultureInfo.InvariantCulture) + "|error=" + lastFailureMessage)); + return await RevertExecutorAfterPointerFailureAsync(request, preparation, lastFailureMessage).ConfigureAwait(false); } /// /// 反切补偿:把执行器切回守卫期旧版本(活跃指针仍指旧版本——反切成功即两处状态一致、 /// 回滚未生效、命令可重试;反切失败为真正须对账的不一致终态并落 Error 轨迹)。 /// - /// 两键锚定作用域。 /// 回滚命令请求。 /// 守卫链产物(Current.Version = 反切目标)。 /// 指针写入重试耗尽时的最后错误消息。 /// 反切成功或失败对应的 5000 错误结果(回滚未生效)。 - private async Task> RevertExecutorAfterPointerFailureAsync(OnlineScope anchor, OnlineHotfixRollbackRequest request, RollbackPreparation preparation, string pointerFailureMessage) + private async Task> RevertExecutorAfterPointerFailureAsync(OnlineHotfixRollbackRequest request, RollbackPreparation preparation, string pointerFailureMessage) { var previousVersion = preparation.Current.Version; try @@ -447,7 +432,7 @@ private async Task> RevertExecutorAfterPointerFailureAsync( await _executor.RollbackAsync(previousVersion, CancellationToken.None).ConfigureAwait(false); // 状态轨迹:反切成功——终态 = 执行器与活跃指针一致停留在旧版本,回滚未生效,命令可重试。 - WriteLog(RollbackLogLevel.Warn, BuildTraceMessage(anchor, request, "executor-reverted", "previous=" + previousVersion + "|target=" + request.TargetVersion + "|detail=回滚未生效,执行器与活跃指针一致停留在旧版本,命令可重试")); + WriteLog(RollbackLogLevel.Warn, BuildTraceMessage(request, "executor-reverted", "previous=" + previousVersion + "|target=" + request.TargetVersion + "|detail=回滚未生效,执行器与活跃指针一致停留在旧版本,命令可重试")); return OnlineResult.Fail(OnlineErrorCode.InternalError, "活跃版本切换重试耗尽,已反切执行器回旧版本(回滚未生效,状态一致,可重试):" + previousVersion + ";指针写入最后错误:" + pointerFailureMessage); } catch (Exception revertFailure) @@ -455,7 +440,7 @@ private async Task> RevertExecutorAfterPointerFailureAsync( var revertFailureMessage = revertFailure == null ? string.Empty : revertFailure.Message; // 状态轨迹:反切失败——终态 = 执行器停目标版本、活跃指针停旧版本(不一致,须对账)。 - WriteLog(RollbackLogLevel.Error, BuildTraceMessage(anchor, request, "executor-revert-failed", "executor=" + request.TargetVersion + "|activePointer=" + previousVersion + "|detail=状态不一致,须对账|error=" + revertFailureMessage)); + WriteLog(RollbackLogLevel.Error, BuildTraceMessage(request, "executor-revert-failed", "executor=" + request.TargetVersion + "|activePointer=" + previousVersion + "|detail=状态不一致,须对账|error=" + revertFailureMessage)); return OnlineResult.Fail(OnlineErrorCode.InternalError, "活跃版本切换重试耗尽且反切旧版本失败(执行器已切到 " + request.TargetVersion + " 但活跃指针仍为 " + previousVersion + ",状态不一致,须对账);指针写入错误:" + pointerFailureMessage + ";反切错误:" + revertFailureMessage); } } @@ -506,18 +491,15 @@ private void WriteLog(RollbackLogLevel level, string message) } /// - /// 组装回滚状态轨迹行(固定前缀 + 作用域 + 幂等键 + 变迁名 + 事实字段,单行可独立归因与还原)。 + /// 组装回滚状态轨迹行(固定前缀 + 幂等键 + 变迁名 + 事实字段,单行可独立归因与还原)。 /// - /// 两键锚定作用域。 /// 回滚命令请求。 /// 变迁名(chain-started / executor-switched / pointer-write-failed 等)。 /// 事实字段(竖线分隔的 key=value)。 /// 轨迹行文本。 - private static string BuildTraceMessage(OnlineScope anchor, OnlineHotfixRollbackRequest request, string transition, string facts) + private static string BuildTraceMessage(OnlineHotfixRollbackRequest request, string transition, string facts) { - return "hotfix-rollback|tenant=" + anchor.TenantId.ToString(System.Globalization.CultureInfo.InvariantCulture) - + "|app=" + anchor.AppId.ToString(System.Globalization.CultureInfo.InvariantCulture) - + "|key=" + request.IdempotencyKey + return "hotfix-rollback|key=" + request.IdempotencyKey + "|transition=" + transition + (string.IsNullOrEmpty(facts) ? string.Empty : "|" + facts); } @@ -525,25 +507,23 @@ private static string BuildTraceMessage(OnlineScope anchor, OnlineHotfixRollback /// /// 读取并守卫目标 / 当前清单(目标未登记 4002、无活跃版本 5001;供预检与回滚守卫链共用)。 /// - /// 租户标识。 - /// App 标识。 /// 目标版本号。 /// 取消令牌。 /// 守卫通过返回准备物;否则返回对应错误。 - private async Task> PrepareTargetAndCurrentAsync(long tenantId, long appId, string targetVersion, CancellationToken cancellationToken) + private async Task> PrepareTargetAndCurrentAsync(string targetVersion, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(targetVersion)) { return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "目标版本号必填"); } - var target = await _store.FindAsync(tenantId, appId, targetVersion, cancellationToken).ConfigureAwait(false); + var target = await _store.FindAsync(targetVersion, cancellationToken).ConfigureAwait(false); if (target == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "目标版本未登记清单:" + targetVersion); } - var current = await _store.FindActiveAsync(tenantId, appId, cancellationToken).ConfigureAwait(false); + var current = await _store.FindActiveAsync(cancellationToken).ConfigureAwait(false); if (current == null) { return OnlineResult.Fail(OnlineErrorCode.StateNotReady, "当前无活跃版本,无从回滚(先经 ActivateAsync 激活基线版本)"); @@ -604,12 +584,11 @@ private static Task> BuildReplayResultA /// /// 审计先行:把回滚命令落统一审计(Domain = Operation;审计失败即拒绝执行——「无审计不执行」)。 /// - /// 两键锚定作用域。 /// 回滚命令请求。 /// 守卫链产物。 /// 取消令牌。 /// 审计失败时返回 1001 错误结果;成功返回 。 - private async Task> IngestRollbackAuditAsync(OnlineScope anchor, OnlineHotfixRollbackRequest request, RollbackPreparation preparation, CancellationToken cancellationToken) + private async Task> IngestRollbackAuditAsync(OnlineHotfixRollbackRequest request, RollbackPreparation preparation, CancellationToken cancellationToken) { var entry = new OnlineAuditEntry { @@ -617,8 +596,6 @@ private async Task> IngestRollbackAudit EventId = "hotfix-rollback-" + request.IdempotencyKey, EventType = OnlineHotfixEvents.RolledBack, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), - TenantId = anchor.TenantId, - AppId = anchor.AppId, ServerId = 0, PlayerId = 0, OperatorId = request.OperatorId, @@ -655,7 +632,7 @@ private async Task> IngestRollbackAudit /// /// 把幂等键落定失败(失败路径专用;落定失败不掩盖原始错误,静默吞并)。 /// - /// 两键锚定作用域。 + /// 全局锚定作用域(幂等落定锚点)。 /// 命令幂等键。 /// 取消令牌。 private async Task FailIdempotencyAsync(OnlineScope anchor, string idempotencyKey, CancellationToken cancellationToken) @@ -682,16 +659,6 @@ private static OnlineResult ValidateRollbackRequest( throw new ArgumentNullException(nameof(request)); } - if (request.Scope == null) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "回滚命令必须携带作用域(TenantId / AppId 两键锚定)"); - } - - if (request.Scope.TenantId <= 0 || request.Scope.AppId <= 0) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "回滚命令必须锚定租户与 App(TenantId / AppId 大于 0)"); - } - if (string.IsNullOrWhiteSpace(request.TargetVersion) || request.TargetVersion.IndexOf('|') >= 0) { return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "目标版本号必填且禁止包含竖线(回放令牌分隔符)"); @@ -716,7 +683,7 @@ private static OnlineResult ValidateRollbackRequest( } /// - /// 校验登记清单(版本号 / 作用域 / 契约行名与号的唯一性,4001 宁拒毋缺)。 + /// 校验登记清单(版本号 / 契约行名与号的唯一性,4001 宁拒毋缺)。 /// /// 待登记清单。 /// 非法时返回失败结果;合法返回 。 @@ -734,11 +701,6 @@ private static OnlineResult ValidateManifest(OnlineHotfixProtocolManifest return artifactFailure; } - if (manifest.TenantId <= 0 || manifest.AppId <= 0) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "清单必须锚定租户与 App(TenantId / AppId 大于 0)"); - } - var messagesFailure = ValidateManifestMessages(manifest); if (messagesFailure != null) { @@ -900,35 +862,14 @@ private static bool IsSha256Hex(string value) return true; } - /// - /// 校验两键作用域(预检 / 激活入口共用)。 - /// - /// 生效作用域。 - /// 非法时返回失败结果;合法返回 。 - private static OnlineResult ValidateTwoKeyScope(OnlineScope scope) - { - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - - if (scope.TenantId <= 0 || scope.AppId <= 0) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "必须锚定租户与 App(TenantId / AppId 大于 0;清单与活跃指针是 App 级资产)"); - } - - return null; - } - /// /// 构造回滚命令的规范化请求文本(幂等意图摘要——同键不同意图判冲突;目标版本 + 操作者为意图主体)。 /// - /// 两键锚定作用域。 /// 回滚命令请求。 /// 规范化请求文本。 - private static string BuildCanonicalRequestText(OnlineScope anchor, OnlineHotfixRollbackRequest request) + private static string BuildCanonicalRequestText(OnlineHotfixRollbackRequest request) { - return "hotfix-rollback|v1|" + anchor.TenantId + ":" + anchor.AppId + "|" + request.TargetVersion + "|" + request.OperatorId; + return "hotfix-rollback|v1|" + request.TargetVersion + "|" + request.OperatorId; } /// diff --git a/Capability/GameFrameX.Capability.Online.Operations/OnlineOperationsCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Operations/OnlineOperationsCapabilityModule.cs index 42ed7c9e1..a43dd5919 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/OnlineOperationsCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/OnlineOperationsCapabilityModule.cs @@ -316,8 +316,6 @@ private static void IngestAuditFromEvent(OnlineEvent onlineEvent, OnlineEventSan EventId = view.EventId, EventType = view.EventType, OccurredTime = view.OccurredTime, - TenantId = view.TenantId, - AppId = view.AppId, ServerId = view.ServerId, PlayerId = view.PlayerId, OperatorId = "online-runtime", diff --git a/Capability/GameFrameX.Capability.Online.Operations/Overview/OnlineOverviewService.cs b/Capability/GameFrameX.Capability.Online.Operations/Overview/OnlineOverviewService.cs index 49c896076..d6076c28e 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/Overview/OnlineOverviewService.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/Overview/OnlineOverviewService.cs @@ -48,7 +48,7 @@ namespace GameFrameX.Capability.Online.Operations.Overview; /// ① **只读**——本服务只依赖各域存储的读取方法(对齐 「只依赖存储的读取方法」先例), /// 不持有任何写入型服务,调用本服务不会产生任何状态副作用或事件; /// ② 数据源唯一 = Online 玩家侧存储,**不含管理员连接**; -/// ③ 所有计数按作用域三键 (TenantId, AppId, ServerId) 过滤,跨作用域读数与不存在同构(反预言)。 +/// ③ 所有计数按作用域区服键 (ServerId) 过滤,跨作用域读数与不存在同构(反预言)。 /// /// /// 统计口径(集中定义,禁止在别处重复定义;**谓词经存储聚合方法下推执行**——各存储接口的聚合读方法以本口径为契约语义, @@ -59,7 +59,7 @@ namespace GameFrameX.Capability.Online.Operations.Overview; /// 重连率:重连中会话数 ÷ 非终态会话数;分母为 0 时取 0(不做补 1 平滑,消费方按需自行处理)。 /// 队伍数:作用域内**非终态**队伍数(终态判定复用 )。 /// 对局数:作用域内**非 ** 对局数(Closed = 已释放,按运行时口径随即删档;读取面仍显式排除,使该计数不依赖写入侧时序)。 -/// 队列深度:作用域内排队态票据数。**匹配池为 App 级**,本快照报告该池在当前 Server 上的分区——各 Server 深度之和等于 App 级排队总数,不得把本值当作跨服共享的池大小。 +/// 队列深度:作用域内排队态票据数。**匹配池为全局共享池**,本快照报告该池在当前 Server 上的分区——各 Server 深度之和等于全局排队总数,不得把本值当作跨服共享的池大小。 /// 平均等待:排队态票据等待时长的算术平均(等待时长复用 ,与匹配域同源;无排队票据时为 0)。 /// 吞吐:最近 60 秒内((观测时刻 - 60000, 观测时刻],左开右闭——恰好落在窗口起点的分配不计入,避免把「上一轮窗口的边界」重复计入相邻两次查询)落档的匹配分配所消费的票据数——口径是「每分钟达成匹配的票据数」,不是对局数(一张票据可携带多人)。 /// @@ -114,10 +114,10 @@ public OnlineOverviewService( /// /// 观测指定作用域的在线总览快照(六路存储聚合读并发执行)。 /// - /// 生效作用域(取 TenantId / AppId / ServerId 三键过滤;不含玩家主体位)。 + /// 生效作用域(取 ServerId 区服键过滤;不含玩家主体位)。 /// 观测时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 - /// 在线总览快照;作用域三键非法时返回 。 + /// 在线总览快照;作用域区服键非法时返回 。 public async Task> ReviewAsync(OnlineScope scope, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var failure = ValidateScope(scope); @@ -129,19 +129,17 @@ public async Task> ReviewAsync(OnlineScope var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var windowStart = now - ThroughputWindowMilliseconds; - var presenceCountTask = _presenceStore.CountOnlineByServerAsync(scope.TenantId, scope.AppId, scope.ServerId, cancellationToken); - var sessionCountsTask = _sessionStore.CountNonTerminalByScopeAsync(scope.TenantId, scope.AppId, scope.ServerId, cancellationToken); - var partyCountsTask = _partyStore.CountNonTerminalByScopeAsync(scope.TenantId, scope.AppId, scope.ServerId, cancellationToken); - var matchCountsTask = _matchStore.CountActiveByScopeAsync(scope.TenantId, scope.AppId, scope.ServerId, cancellationToken); - var queueDepthTask = _ticketStore.AggregateQueuedBySlotAsync(scope.TenantId, scope.AppId, scope.ServerId, now, cancellationToken); - var throughputTask = _ticketStore.CountAssignmentTicketsBySlotAsync(scope.TenantId, scope.AppId, scope.ServerId, windowStart, now, cancellationToken); + var presenceCountTask = _presenceStore.CountOnlineByServerAsync(scope.ServerId, cancellationToken); + var sessionCountsTask = _sessionStore.CountNonTerminalByScopeAsync(scope.ServerId, cancellationToken); + var partyCountsTask = _partyStore.CountNonTerminalByScopeAsync(scope.ServerId, cancellationToken); + var matchCountsTask = _matchStore.CountActiveByScopeAsync(scope.ServerId, cancellationToken); + var queueDepthTask = _ticketStore.AggregateQueuedBySlotAsync(scope.ServerId, now, cancellationToken); + var throughputTask = _ticketStore.CountAssignmentTicketsBySlotAsync(scope.ServerId, windowStart, now, cancellationToken); await Task.WhenAll(presenceCountTask, sessionCountsTask, partyCountsTask, matchCountsTask, queueDepthTask, throughputTask).ConfigureAwait(false); var snapshot = new OnlineOverviewSnapshot { - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, ObservedTime = now, OnlinePlayerCount = presenceCountTask.Result, @@ -270,7 +268,7 @@ private static int CompareQueueSummaries(OnlineOverviewQueueSummary left, Online } /// - /// 校验作用域三键(总览不面向单个玩家,故不要求玩家主体位)。 + /// 校验作用域区服键(总览不面向单个玩家,故不要求玩家主体位)。 /// /// 结果负载类型。 /// 生效作用域。 @@ -282,9 +280,9 @@ private static OnlineResult ValidateScope(OnlineScope scope) throw new ArgumentNullException(nameof(scope)); } - if (scope.TenantId <= 0 || scope.AppId <= 0 || scope.ServerId <= 0) + if (scope.ServerId <= 0) { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "在线总览查询必须携带完整作用域三键(TenantId / AppId / ServerId)"); + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "在线总览查询必须携带作用域区服键(ServerId)"); } return null; diff --git a/Capability/GameFrameX.Capability.Online.Operations/Overview/OnlineOverviewSnapshot.cs b/Capability/GameFrameX.Capability.Online.Operations/Overview/OnlineOverviewSnapshot.cs index d6120a800..70489623b 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/Overview/OnlineOverviewSnapshot.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/Overview/OnlineOverviewSnapshot.cs @@ -41,7 +41,7 @@ namespace GameFrameX.Capability.Online.Operations.Overview; /// 维护约束(红线): /// ① **运行态快照而非权威状态**——数值由运行态存储现场聚合,随时会变,消费方不得缓存后当作权威状态使用; /// ② 数据源唯一 = Online 玩家侧存储;**管理员连接不计入任何计数**(管理员在线链路不是玩家在线数据源); -/// ③ 所有计数按作用域三键 (TenantId, AppId, ServerId) 过滤,跨作用域读数与不存在同构(反预言)。 +/// ③ 所有计数按作用域区服键 (ServerId) 过滤,跨作用域读数与不存在同构(反预言)。 /// /// /// 口径定义见 类文档——各计数的统计边界集中在那里,本类型只承载结果。 @@ -49,16 +49,6 @@ namespace GameFrameX.Capability.Online.Operations.Overview; /// public sealed class OnlineOverviewSnapshot { - /// - /// 获取或设置租户标识(本快照的作用域归属)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(本快照的作用域归属)。 - /// - public long AppId { get; set; } - /// /// 获取或设置区服标识(本快照的作用域归属)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Operations/Timeline/IOnlineConfigHitProbe.cs b/Capability/GameFrameX.Capability.Online.Operations/Timeline/IOnlineConfigHitProbe.cs index 04b5379a4..2ea128d79 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/Timeline/IOnlineConfigHitProbe.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/Timeline/IOnlineConfigHitProbe.cs @@ -51,11 +51,9 @@ public interface IOnlineConfigHitProbe /// /// 列出指定玩家在作用域内的配置命中记录。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 玩家标识。 /// 取消令牌。 /// 命中记录(无命中返回空集合;顺序由实现保证稳定,时间线侧自行全量排序)。 - Task> ListHitsAsync(long tenantId, long appId, long serverId, long playerId, CancellationToken cancellationToken = default); + Task> ListHitsAsync(long serverId, long playerId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Operations/Timeline/OnlinePlayerTimelineService.cs b/Capability/GameFrameX.Capability.Online.Operations/Timeline/OnlinePlayerTimelineService.cs index a4a103b27..d50776ebf 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/Timeline/OnlinePlayerTimelineService.cs +++ b/Capability/GameFrameX.Capability.Online.Operations/Timeline/OnlinePlayerTimelineService.cs @@ -52,7 +52,7 @@ namespace GameFrameX.Capability.Online.Operations.Timeline; /// 与可空探针()。不持有任何写入型服务,调用本服务不产生状态副作用与事件 /// ——「只读视图不直写各域状态」由类型系统结构性保证,对齐 OnlineMatchQueueObserver 先例; /// ② 数据源唯一 = 各权威域自身记录,**不拼接、不推断、不补齐**:缺数据源(配置命中未装配探针)即空槽; -/// ③ 全部行按作用域三键 (TenantId, AppId, ServerId) + 玩家主体位过滤,跨作用域读取与「无数据」**同构**(反预言): +/// ③ 全部行按作用域区服键 (ServerId) + 玩家主体位过滤,跨作用域读取与「无数据」**同构**(反预言): /// 查询先以**档案作用域门**判定「该玩家是否存在于本作用域」,不存在即直接返回空行集、不触及其余各腿 /// (处罚记录没有区服维度,若逐腿各自过滤,跨作用域查询会返回「有处罚但无身份」的半截视图而泄露存在性)。 /// @@ -74,7 +74,7 @@ namespace GameFrameX.Capability.Online.Operations.Timeline; /// /// /// 天花板(ponytail):各腿均为按玩家 / 作用域过滤后的内存聚合,规模有限;账本腿受 -/// 限制(见该常量注释),对局腿按 App 级列表全扫后按玩家过滤。 +/// 限制(见该常量注释),对局腿按全量列表全扫后按玩家过滤。 /// /// public sealed class OnlinePlayerTimelineService @@ -144,7 +144,7 @@ public OnlinePlayerTimelineService( /// /// 查询指定玩家的跨域时间线(只读;不产生任何状态变更)。 /// - /// 生效作用域(必须含完整三键与玩家主体位)。 + /// 生效作用域(必须含区服键与玩家主体位)。 /// 查询条件;传 等价于默认条件(全部行、首页、默认页大小)。 /// 取消令牌。 /// 时间线分页结果;作用域 / 玩家位缺失、页大小越界、游标非法返回 。 @@ -265,7 +265,7 @@ private static OnlinePlayerTimelinePage BuildPage(List /// 按玩家标识加载档案并判定其是否落在本作用域(作用域门的唯一实现处)。 /// - /// 档案读取面按玩家标识单查、不带作用域参数,故此处显式做三键比对:跨作用域玩家与不存在**同构**(都返回 )。 + /// 档案读取面按玩家标识单查、不带作用域参数,故此处显式做区服键比对:跨作用域玩家与不存在**同构**(都返回 )。 /// /// /// 生效作用域。 @@ -274,7 +274,7 @@ private static OnlinePlayerTimelinePage BuildPage(List LoadInScopeProfileAsync(OnlineScope scope, CancellationToken cancellationToken) { var profile = await _identityStore.FindPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); - if (profile == null || !IsInScope(profile.TenantId, profile.AppId, profile.ServerId, scope)) + if (profile == null || !IsInScope(profile.ServerId, scope)) { return null; } @@ -304,7 +304,7 @@ private async Task CollectIdentityRowsAsync(OnlineScope scope, OnlinePlayerProfi }); var account = await _identityStore.FindAccountAsync(profile.GameAccountId, cancellationToken).ConfigureAwait(false); - if (account != null && account.TenantId == scope.TenantId && account.AppId == scope.AppId) + if (account != null) { rows.Add(new OnlinePlayerTimelineEntry { @@ -326,7 +326,7 @@ private async Task CollectIdentityRowsAsync(OnlineScope scope, OnlinePlayerProfi foreach (var identity in identities) { - if (identity == null || identity.TenantId != scope.TenantId || identity.AppId != scope.AppId) + if (identity == null) { continue; } @@ -359,7 +359,7 @@ private async Task CollectIdentityRowsAsync(OnlineScope scope, OnlinePlayerProfi /// 异步任务。 private async Task CollectSessionRowsAsync(OnlineScope scope, List rows, CancellationToken cancellationToken) { - var sessions = await _sessionStore.ListActiveByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var sessions = await _sessionStore.ListActiveByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); if (sessions == null) { return; @@ -390,7 +390,7 @@ private async Task CollectSessionRowsAsync(OnlineScope scope, List /// 只读经 (不直连存储,保持依赖面为「只读查询服务」); - /// 账本键为 (租户, App, 玩家)、**无区服维度**(HomeServerId 只表资产归属/运行位置,不做数据隔离), + /// 账本键按玩家维度、**无区服维度**(HomeServerId 只表资产归属/运行位置,不做数据隔离), /// 故此处不按归属服过滤——否则「归属服与玩家所在服不一致」的流水会在**任何作用域**都取不到(静默缺行)。 /// 作用域边界由档案作用域门承担(他服玩家的档案过不了门,根本走不到本腿)。 /// @@ -438,7 +438,7 @@ private async Task> CollectAssetRowsAsync /// /// 收集对局腿行(分组 Match):该玩家作为成员的对局。 /// - /// 对局读取面按 (租户, App) 列表返回(无按玩家查询面),故此处全扫后按成员关系过滤——玩家的成员关系以 + /// 对局读取面为全量列表返回(无按玩家查询面),故此处全扫后按成员关系过滤——玩家的成员关系以 /// OnlineMatch.FindMember 为准,不从票据 / 分配记录推断。 /// /// @@ -448,7 +448,7 @@ private async Task> CollectAssetRowsAsync /// 异步任务。 private async Task CollectMatchRowsAsync(OnlineScope scope, List rows, CancellationToken cancellationToken) { - var matches = await _matchStore.ListAsync(scope.TenantId, scope.AppId, cancellationToken).ConfigureAwait(false); + var matches = await _matchStore.ListAsync(cancellationToken).ConfigureAwait(false); if (matches == null) { return; @@ -484,7 +484,7 @@ private async Task CollectMatchRowsAsync(OnlineScope scope, List异步任务。 private async Task CollectPenaltyRowsAsync(OnlineScope scope, List rows, CancellationToken cancellationToken) { - var punishments = await _socialGraphStore.ListPunishmentsByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var punishments = await _socialGraphStore.ListPunishmentsByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); if (punishments == null) { return; @@ -544,7 +544,7 @@ private async Task CollectConfigHitRowsAsync(OnlineScope scope, List - /// 判断来源记录是否落在观测作用域内(三键全等)。 + /// 判断来源记录是否落在观测作用域内(区服键全等)。 /// - /// 记录租户标识。 - /// 记录 App 标识。 /// 记录区服标识。 /// 观测作用域。 /// 在作用域内返回 true。 - private static bool IsInScope(long tenantId, long appId, long serverId, OnlineScope scope) + private static bool IsInScope(long serverId, OnlineScope scope) { - return tenantId == scope.TenantId && appId == scope.AppId && serverId == scope.ServerId; + return serverId == scope.ServerId; } /// - /// 校验作用域(三键 + 玩家主体位;玩家标识只取自作用域,不从查询体重复读取)。 + /// 校验作用域(区服键 + 玩家主体位;玩家标识只取自作用域,不从查询体重复读取)。 /// /// 结果负载类型。 /// 生效作用域。 @@ -829,9 +827,9 @@ private static OnlineResult ValidateScope(OnlineScope scope) throw new ArgumentNullException(nameof(scope)); } - if (scope.TenantId <= 0 || scope.AppId <= 0 || scope.ServerId <= 0) + if (scope.ServerId <= 0) { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "玩家时间线查询必须携带完整作用域三键(TenantId / AppId / ServerId)"); + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "玩家时间线查询必须携带作用域区服键(ServerId)"); } if (scope.PlayerId <= 0) diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Assets/GameDbOnlineAssetStore.cs b/Capability/GameFrameX.Capability.Online.Persistence/Assets/GameDbOnlineAssetStore.cs index 5221c4041..20d947f7d 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Assets/GameDbOnlineAssetStore.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Assets/GameDbOnlineAssetStore.cs @@ -33,6 +33,7 @@ namespace GameFrameX.Capability.Online.Persistence.Assets; using System.Threading; using System.Threading.Tasks; using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Keys; using GameFrameX.Capability.Online.Assets; using GameFrameX.DataBase; @@ -50,7 +51,7 @@ namespace GameFrameX.Capability.Online.Persistence.Assets; /// /// 不可变红线:账本行只经插入路径写入(SaveOneAsync),本适配零账本修改/删除调用; /// 纠正只能追加反转条目(契约面既有约定)。玩家维度账本序由 NextSequenceAsync -/// 玩家键控序列分配("tenant:app:player";原子单调、重启不复用)。 +/// 玩家键控序列分配(OnlineRowKey.LedgerSequence;原子单调、重启不复用)。 /// /// /// 列举保真:账本分页排序键为数值账本序(provider 原生排序,无 collation 分歧); @@ -76,57 +77,49 @@ public sealed class GameDbOnlineAssetStore : IOnlineAssetStore private readonly object _registryLock = new(); /// - /// 玩家分片信号量注册表:键 = "tenant:app:player"(进程内并发正确性目标,同 InMemory 分片锁)。 + /// 玩家分片信号量注册表:键 = 玩家标识(OnlineRowKey.LedgerSequence;进程内并发正确性目标,同 InMemory 分片锁)。 /// private readonly Dictionary _playerGates = new(); /// 查找货币账户快照。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 货币代码。 /// 取消令牌。 /// 账户快照;从未发生过变更返回 null(视余额为 0)。 - public async Task FindWalletAsync(long tenantId, long appId, long playerId, string currencyId, CancellationToken cancellationToken = default) + public async Task FindWalletAsync(long playerId, string currencyId, CancellationToken cancellationToken = default) { - var state = await FindWalletStateAsync(BuildWalletKey(tenantId, appId, playerId, currencyId), cancellationToken).ConfigureAwait(false); + var state = await FindWalletStateAsync(OnlineRowKey.WalletAccount(playerId, currencyId), cancellationToken).ConfigureAwait(false); return state == null ? null : ToEntity(state); } /// 查找道具库存堆栈快照。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 道具标识。 /// 取消令牌。 /// 库存快照;从未发生过变更返回 null(视数量为 0)。 - public async Task FindInventoryAsync(long tenantId, long appId, long playerId, string itemId, CancellationToken cancellationToken = default) + public async Task FindInventoryAsync(long playerId, string itemId, CancellationToken cancellationToken = default) { - var state = await FindInventoryStateAsync(BuildInventoryKey(tenantId, appId, playerId, itemId), cancellationToken).ConfigureAwait(false); + var state = await FindInventoryStateAsync(OnlineRowKey.InventoryStack(playerId, itemId), cancellationToken).ConfigureAwait(false); return state == null ? null : ToEntity(state); } /// 列举玩家全部货币账户快照(按货币代码 ordinal 字典序)。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 账户快照列表。 - public async Task> ListWalletAccountsAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public async Task> ListWalletAccountsAsync(long playerId, CancellationToken cancellationToken = default) { - var states = await GameDb.FindListAsync(state => state.TenantId == tenantId && state.AppId == appId && state.PlayerId == playerId, cancellationToken).ConfigureAwait(false); + var states = await GameDb.FindListAsync(state => state.PlayerId == playerId, cancellationToken).ConfigureAwait(false); return states.OrderBy(state => state.CurrencyId, StringComparer.Ordinal).Select(ToEntity).ToList(); } /// 列举玩家全部道具库存快照(按道具标识 ordinal 字典序)。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 库存快照列表。 - public async Task> ListInventoryStacksAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public async Task> ListInventoryStacksAsync(long playerId, CancellationToken cancellationToken = default) { - var states = await GameDb.FindListAsync(state => state.TenantId == tenantId && state.AppId == appId && state.PlayerId == playerId, cancellationToken).ConfigureAwait(false); + var states = await GameDb.FindListAsync(state => state.PlayerId == playerId, cancellationToken).ConfigureAwait(false); return states.OrderBy(state => state.ItemId, StringComparer.Ordinal).Select(ToEntity).ToList(); } @@ -144,7 +137,7 @@ public async Task ApplyAsync(OnlineAssetChangeBatch batc { ArgumentNullException.ThrowIfNull(batch); - var gate = GetPlayerGate(batch.TenantId, batch.AppId, batch.PlayerId); + var gate = GetPlayerGate(batch.PlayerId); await gate.WaitAsync(cancellationToken).ConfigureAwait(false); try { @@ -199,7 +192,7 @@ public async Task> ListLedgerEntriesAsync(Onlin var afterSequenceNumber = query.AfterSequenceNumber; var states = await GameDb.FindSortAscendingAsync( - state => state.TenantId == query.TenantId && state.AppId == query.AppId && state.PlayerId == query.PlayerId && state.SequenceNumber > afterSequenceNumber, + state => state.PlayerId == query.PlayerId && state.SequenceNumber > afterSequenceNumber, state => state.SequenceNumber, 0, query.MaxCount, cancellationToken).ConfigureAwait(false); return states.Select(ToEntity).ToList(); } @@ -215,14 +208,12 @@ public async Task> FindLedgerEntriesByTransacti } /// 聚合玩家账本带符号数额(对账的账本侧事实源;键 = 类别前缀 + 资产标识)。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 各资产账本累加。 - public async Task> SumLedgerDeltasByAssetAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public async Task> SumLedgerDeltasByAssetAsync(long playerId, CancellationToken cancellationToken = default) { - var states = await GameDb.FindListAsync(state => state.TenantId == tenantId && state.AppId == appId && state.PlayerId == playerId, cancellationToken).ConfigureAwait(false); + var states = await GameDb.FindListAsync(state => state.PlayerId == playerId, cancellationToken).ConfigureAwait(false); var sums = new Dictionary(); foreach (var state in states) { @@ -234,14 +225,12 @@ public async Task> SumLedgerDeltasByAssetAsync return sums; } - /// 列举 (租户, App) 下发生过资产活动(账本非空)的玩家(对账遍历输入;升序去重)。 - /// 租户标识。 - /// App 标识。 + /// 列举发生过资产活动(账本非空)的玩家(对账遍历输入;升序去重)。 /// 取消令牌。 /// 玩家标识列表。 - public async Task> ListPlayerIdsAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public async Task> ListPlayerIdsAsync(CancellationToken cancellationToken = default) { - var states = await GameDb.FindListAsync(state => state.TenantId == tenantId && state.AppId == appId, cancellationToken).ConfigureAwait(false); + var states = await GameDb.FindListAsync(state => true, cancellationToken).ConfigureAwait(false); return states.Select(state => state.PlayerId).Distinct().OrderBy(playerId => playerId).ToList(); } @@ -255,7 +244,7 @@ private static OnlineAssetApplyResult ValidateBatchAssetUniqueness(OnlineAssetCh var seenAssets = new HashSet(StringComparer.Ordinal); foreach (var line in batch.Lines) { - if (!seenAssets.Add(BuildAssetKey(batch.TenantId, batch.AppId, batch.PlayerId, line.AssetKind, line.AssetId))) + if (!seenAssets.Add(OnlineRowKey.AssetDedup(batch.PlayerId, line.AssetKind == OnlineAssetKind.Currency, line.AssetId))) { return new OnlineAssetApplyResult(false, OnlineErrorCode.ParameterInvalid, "同一批次内资产重复:" + line.AssetId, Array.Empty()); } @@ -283,13 +272,13 @@ private static OnlineAssetApplyResult ValidateBatchAssetUniqueness(OnlineAssetCh PlannedAssetSnapshot snapshot; if (line.AssetKind == OnlineAssetKind.Currency) { - var wallet = await FindWalletStateAsync(BuildWalletKey(batch.TenantId, batch.AppId, batch.PlayerId, line.AssetId), cancellationToken).ConfigureAwait(false); + var wallet = await FindWalletStateAsync(OnlineRowKey.WalletAccount(batch.PlayerId, line.AssetId), cancellationToken).ConfigureAwait(false); amountBefore = wallet?.Balance ?? 0; snapshot = wallet == null ? PlannedAssetSnapshot.Absent() : PlannedAssetSnapshot.Existing(wallet.Id, wallet.RowVersion); } else { - var stack = await FindInventoryStateAsync(BuildInventoryKey(batch.TenantId, batch.AppId, batch.PlayerId, line.AssetId), cancellationToken).ConfigureAwait(false); + var stack = await FindInventoryStateAsync(OnlineRowKey.InventoryStack(batch.PlayerId, line.AssetId), cancellationToken).ConfigureAwait(false); amountBefore = stack?.Quantity ?? 0; snapshot = stack == null ? PlannedAssetSnapshot.Absent() : PlannedAssetSnapshot.Existing(stack.Id, stack.RowVersion); } @@ -320,14 +309,12 @@ private static OnlineAssetApplyResult ValidateBatchAssetUniqueness(OnlineAssetCh /// 账本条目。 private static async Task BuildEntryAsync(OnlineAssetChangeBatch batch, OnlineAssetChangeLine line, long amountBefore, long amountAfter, long occurredTime, CancellationToken cancellationToken) { - var sequence = await GameDb.NextSequenceAsync(BuildLedgerSequenceKey(batch.TenantId, batch.AppId, batch.PlayerId), cancellationToken).ConfigureAwait(false); + var sequence = await GameDb.NextSequenceAsync(OnlineRowKey.LedgerSequence(batch.PlayerId), cancellationToken).ConfigureAwait(false); return new OnlineLedgerEntry( "led-" + Guid.NewGuid().ToString("N"), batch.TransactionId, new OnlineLedgerHeader { - TenantId = batch.TenantId, - AppId = batch.AppId, PlayerId = batch.PlayerId, HomeServerId = batch.HomeServerId, InitiatingServerId = batch.InitiatingServerId, @@ -381,15 +368,13 @@ private static async Task CommitEntriesAsync(List planned, Li /// 取消令牌。 private static async Task UpsertWalletAsync(OnlineLedgerEntry entry, PlannedAssetSnapshot snapshot, long occurredTime, CancellationToken cancellationToken) { - var uniqueKey = BuildWalletKey(entry.TenantId, entry.AppId, entry.PlayerId, entry.AssetId); + var uniqueKey = OnlineRowKey.WalletAccount(entry.PlayerId, entry.AssetId); if (snapshot.RowExists) { var updated = new OnlineWalletAccountState { Id = snapshot.RowId, UniqueKey = uniqueKey, - TenantId = entry.TenantId, - AppId = entry.AppId, PlayerId = entry.PlayerId, CurrencyId = entry.AssetId, Balance = entry.AmountAfter, @@ -415,8 +400,6 @@ private static async Task UpsertWalletAsync(OnlineLedgerEntry entry, PlannedAsse { Id = rowId, UniqueKey = uniqueKey, - TenantId = entry.TenantId, - AppId = entry.AppId, PlayerId = entry.PlayerId, CurrencyId = entry.AssetId, Balance = entry.AmountAfter, @@ -436,15 +419,13 @@ private static async Task UpsertWalletAsync(OnlineLedgerEntry entry, PlannedAsse /// 取消令牌。 private static async Task UpsertInventoryStackAsync(OnlineLedgerEntry entry, PlannedAssetSnapshot snapshot, long occurredTime, CancellationToken cancellationToken) { - var uniqueKey = BuildInventoryKey(entry.TenantId, entry.AppId, entry.PlayerId, entry.AssetId); + var uniqueKey = OnlineRowKey.InventoryStack(entry.PlayerId, entry.AssetId); if (snapshot.RowExists) { var updated = new OnlineInventoryStackState { Id = snapshot.RowId, UniqueKey = uniqueKey, - TenantId = entry.TenantId, - AppId = entry.AppId, PlayerId = entry.PlayerId, ItemId = entry.AssetId, Quantity = entry.AmountAfter, @@ -470,8 +451,6 @@ private static async Task UpsertInventoryStackAsync(OnlineLedgerEntry entry, Pla { Id = rowId, UniqueKey = uniqueKey, - TenantId = entry.TenantId, - AppId = entry.AppId, PlayerId = entry.PlayerId, ItemId = entry.AssetId, Quantity = entry.AmountAfter, @@ -520,13 +499,11 @@ public static PlannedAssetSnapshot Existing(long rowId, long? rowVersion) } /// 获取玩家分片信号量(不存在则注册)。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 分片信号量。 - private SemaphoreSlim GetPlayerGate(long tenantId, long appId, long playerId) + private SemaphoreSlim GetPlayerGate(long playerId) { - var playerKey = BuildLedgerSequenceKey(tenantId, appId, playerId); + var playerKey = OnlineRowKey.LedgerSequence(playerId); lock (_registryLock) { if (!_playerGates.TryGetValue(playerKey, out var gate)) @@ -551,30 +528,6 @@ private static Task FindInventoryStateAsync(string un return GameDb.FindAsync(state => state.UniqueKey == uniqueKey, isCreateIfNotExists: false, cancellationToken: cancellationToken); } - /// 构造玩家键控账本序序列名("tenant:app:player")。 - private static string BuildLedgerSequenceKey(long tenantId, long appId, long playerId) - { - return tenantId + ":" + appId + ":" + playerId; - } - - /// 构造钱包物化复合键("tenant:app:player:货币代码")。 - private static string BuildWalletKey(long tenantId, long appId, long playerId, string currencyId) - { - return tenantId + ":" + appId + ":" + playerId + ":" + currencyId; - } - - /// 构造库存物化复合键("tenant:app:player:道具标识")。 - private static string BuildInventoryKey(long tenantId, long appId, long playerId, string itemId) - { - return tenantId + ":" + appId + ":" + playerId + ":" + itemId; - } - - /// 构造批次内资产去重键(与 InMemory BuildAssetKey 同构)。 - private static string BuildAssetKey(long tenantId, long appId, long playerId, OnlineAssetKind assetKind, string assetId) - { - return tenantId + ":" + appId + ":" + playerId + ":" + (assetKind == OnlineAssetKind.Currency ? "c" : "i") + ":" + assetId; - } - /// 账本条目 → 行(只追加路径;行 Id 由序列分配)。 private static OnlineLedgerEntryState ToState(OnlineLedgerEntry entry) { @@ -582,8 +535,6 @@ private static OnlineLedgerEntryState ToState(OnlineLedgerEntry entry) { EntryId = entry.EntryId, TransactionId = entry.TransactionId, - TenantId = entry.TenantId, - AppId = entry.AppId, PlayerId = entry.PlayerId, HomeServerId = entry.HomeServerId, InitiatingServerId = entry.InitiatingServerId, @@ -611,8 +562,6 @@ private static OnlineLedgerEntry ToEntity(OnlineLedgerEntryState state) state.TransactionId, new OnlineLedgerHeader { - TenantId = state.TenantId, - AppId = state.AppId, PlayerId = state.PlayerId, HomeServerId = state.HomeServerId, InitiatingServerId = state.InitiatingServerId, @@ -637,8 +586,6 @@ private static OnlineWalletAccount ToEntity(OnlineWalletAccountState state) { return new OnlineWalletAccount { - TenantId = state.TenantId, - AppId = state.AppId, PlayerId = state.PlayerId, CurrencyId = state.CurrencyId, Balance = state.Balance, @@ -652,8 +599,6 @@ private static OnlineInventoryStack ToEntity(OnlineInventoryStackState state) { return new OnlineInventoryStack { - TenantId = state.TenantId, - AppId = state.AppId, PlayerId = state.PlayerId, ItemId = state.ItemId, Quantity = state.Quantity, diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Assets/GameDbOnlineAssetTransactionStore.cs b/Capability/GameFrameX.Capability.Online.Persistence/Assets/GameDbOnlineAssetTransactionStore.cs index 914167062..d3eaf4a34 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Assets/GameDbOnlineAssetTransactionStore.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Assets/GameDbOnlineAssetTransactionStore.cs @@ -133,8 +133,6 @@ private static OnlineAssetTransactionRowState ToState(OnlineAssetTransaction tra TransactionId = transaction.TransactionId, IdempotencyKey = transaction.IdempotencyKey, RequestDigest = transaction.RequestDigest, - TenantId = transaction.TenantId, - AppId = transaction.AppId, PlayerId = transaction.PlayerId, HomeServerId = transaction.HomeServerId, InitiatingServerId = transaction.InitiatingServerId, @@ -161,8 +159,6 @@ private static OnlineAssetTransaction ToEntity(OnlineAssetTransactionRowState st TransactionId = state.TransactionId, IdempotencyKey = state.IdempotencyKey, RequestDigest = state.RequestDigest, - TenantId = state.TenantId, - AppId = state.AppId, PlayerId = state.PlayerId, HomeServerId = state.HomeServerId, InitiatingServerId = state.InitiatingServerId, diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineAssetTransactionRowState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineAssetTransactionRowState.cs index 0de796181..92fd3a510 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineAssetTransactionRowState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineAssetTransactionRowState.cs @@ -64,16 +64,6 @@ public sealed class OnlineAssetTransactionRowState : BaseCacheState /// public string CompensatesTransactionId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置玩家标识。 /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineInventoryStackState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineInventoryStackState.cs index 54c96c5ed..e4233924a 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineInventoryStackState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineInventoryStackState.cs @@ -36,7 +36,8 @@ namespace GameFrameX.Capability.Online.Persistence.Assets; /// 道具库存堆栈快照持久化行(一级 store:Assets 域 → GameDb 适配的落库形态)。 /// /// 键编码与行版本约定同 :物化复合键 -/// ("tenant:app:player:道具标识")单列唯一索引;行版本唯一事实源 = 基类 RowVersion +/// ("player:道具标识",与 InMemory 键同构,唯一构造点 OnlineRowKey.InventoryStack) +/// 单列唯一索引;行版本唯一事实源 = 基类 RowVersion /// (乐观锁专用,不承载业务含义),实体 Version 为派生视图(实体 Version = 行 /// RowVersion + 1);存量行 null 行版本由适配层惰性回填。快照为账本派生面。 /// @@ -44,21 +45,11 @@ namespace GameFrameX.Capability.Online.Persistence.Assets; public sealed class OnlineInventoryStackState : BaseCacheState { /// - /// 获取或设置物化复合键("tenant:app:player:itemId";唯一索引列)。 + /// 获取或设置物化复合键("player:itemId";唯一索引列)。 /// [EntityIndex("ux_online_inventory_unique_key", Unique = true)] public string UniqueKey { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置玩家标识。 /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineLedgerEntryState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineLedgerEntryState.cs index 5bd4c0561..36ec74063 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineLedgerEntryState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineLedgerEntryState.cs @@ -38,7 +38,7 @@ namespace GameFrameX.Capability.Online.Persistence.Assets; /// 资产红线:账本只追加——适配层仅经插入路径写本表(SaveOneAsync),结构性不提供任何 /// 修改/删除调用; 单列唯一索引兜底条目级幂等。玩家维度账本序 /// 由 NextSequenceAsync 玩家键控序列分配 -/// ("tenant:app:player",原子单调、重启不复用——接管 InMemory 内存计数器)。 +/// (OnlineRowKey.LedgerSequence,原子单调、重启不复用——接管 InMemory 内存计数器)。 /// 账本是余额/库存对账的事实源(快照为派生面,崩溃残留由对账服务重算兜底)。 /// /// @@ -55,16 +55,6 @@ public sealed class OnlineLedgerEntryState : BaseCacheState /// public string TransactionId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置玩家标识。 /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineWalletAccountState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineWalletAccountState.cs index 507be74ec..6baac56bd 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineWalletAccountState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Assets/OnlineWalletAccountState.cs @@ -35,7 +35,8 @@ namespace GameFrameX.Capability.Online.Persistence.Assets; /// /// 货币账户快照持久化行(一级 store:Assets 域 → GameDb 适配的落库形态)。 /// -/// 键编码约定: = 物化复合键("tenant:app:player:货币代码") +/// 键编码约定: = 物化复合键("player:货币代码",与 InMemory 键同构, +/// 唯一构造点 OnlineRowKey.WalletAccount) /// 单列唯一索引;行 Id 由 NextSequenceAsync 分配。行版本唯一事实源 = 基类 /// RowVersion(乐观锁专用字段,只承载并发控制语义、不承载业务含义); /// 实体 Version 为派生视图(恒等式:实体 Version = 行 RowVersion + 1,首次落账建档即 1)。 @@ -46,21 +47,11 @@ namespace GameFrameX.Capability.Online.Persistence.Assets; public sealed class OnlineWalletAccountState : BaseCacheState { /// - /// 获取或设置物化复合键("tenant:app:player:currencyId";唯一索引列)。 + /// 获取或设置物化复合键("player:currencyId";唯一索引列)。 /// [EntityIndex("ux_online_wallet_unique_key", Unique = true)] public string UniqueKey { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置玩家标识。 /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Identity/GameDbOnlineIdentityStore.cs b/Capability/GameFrameX.Capability.Online.Persistence/Identity/GameDbOnlineIdentityStore.cs index 2d058d681..61874bafe 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Identity/GameDbOnlineIdentityStore.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Identity/GameDbOnlineIdentityStore.cs @@ -31,6 +31,7 @@ namespace GameFrameX.Capability.Online.Persistence.Identity; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; using GameFrameX.Capability.Online.Foundation.Identity; using GameFrameX.DataBase; @@ -70,16 +71,14 @@ public sealed class GameDbOnlineIdentityStore : IOnlineIdentityStore /// private const string PlayerIdSequence = "player-id"; - /// 按唯一键 (TenantId, AppId, Kind, Identifier) 查找身份。 - /// 租户标识。 - /// 应用标识。 + /// 按唯一键 (Kind, Identifier) 查找身份。 /// 身份类型。 /// 身份标识串。 /// 取消令牌。 /// 身份实体;不存在返回 null。 - public async Task FindIdentityAsync(long tenantId, long appId, OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default) + public async Task FindIdentityAsync(OnlineIdentityKind kind, string identifier, CancellationToken cancellationToken = default) { - var state = await FindIdentityStateAsync(BuildIdentityKey(tenantId, appId, kind, identifier), cancellationToken).ConfigureAwait(false); + var state = await FindIdentityStateAsync(OnlineRowKey.Identity((int)kind, identifier), cancellationToken).ConfigureAwait(false); return state == null ? null : ToEntity(state); } @@ -90,7 +89,7 @@ public async Task AddOrUpdateIdentityAsync(OnlineIdentity identity, Cancellation { ArgumentNullException.ThrowIfNull(identity); - var uniqueKey = BuildIdentityKey(identity.TenantId, identity.AppId, identity.Kind, identity.Identifier); + var uniqueKey = OnlineRowKey.Identity((int)identity.Kind, identity.Identifier); var existing = await FindIdentityStateAsync(uniqueKey, cancellationToken).ConfigureAwait(false); if (existing != null) { @@ -123,7 +122,7 @@ public async Task TryAddIdentityAsync(OnlineIdentity identity, Cancellatio { ArgumentNullException.ThrowIfNull(identity); - var uniqueKey = BuildIdentityKey(identity.TenantId, identity.AppId, identity.Kind, identity.Identifier); + var uniqueKey = OnlineRowKey.Identity((int)identity.Kind, identity.Identifier); var rowId = await GameDb.NextSequenceAsync(IdentityRowIdSequence, cancellationToken).ConfigureAwait(false); var state = ToState(identity, uniqueKey, rowId); state.RowVersion = 1; @@ -142,7 +141,7 @@ public async Task TryUpdateIdentityIfRowVersionAsync(OnlineIdentity identi { ArgumentNullException.ThrowIfNull(identity); - var uniqueKey = BuildIdentityKey(identity.TenantId, identity.AppId, identity.Kind, identity.Identifier); + var uniqueKey = OnlineRowKey.Identity((int)identity.Kind, identity.Identifier); var existing = await FindIdentityStateAsync(uniqueKey, cancellationToken).ConfigureAwait(false); if (existing == null) { @@ -212,19 +211,18 @@ public async Task AddOrUpdatePlayerAsync(OnlinePlayerProfile player, Cancellatio await GameDb.AddOrUpdateAsync(ToState(player), cancellationToken).ConfigureAwait(false); } - /// 列出账号在指定 App/Server 归属下的玩家档案(按创建时间升序;并列按 Id 定序)。 + /// 列出账号在指定区服归属下的玩家档案(按创建时间升序;并列按 Id 定序)。 /// 游戏账号标识。 - /// 应用标识。 /// 区服标识。 /// 取消令牌。 /// 玩家档案列表。 - public async Task> ListPlayersAsync(long gameAccountId, long appId, long serverId, CancellationToken cancellationToken = default) + public async Task> ListPlayersAsync(long gameAccountId, long serverId, CancellationToken cancellationToken = default) { - var states = await GameDb.FindListAsync(state => state.GameAccountId == gameAccountId && state.AppId == appId && state.ServerId == serverId, cancellationToken).ConfigureAwait(false); + var states = await GameDb.FindListAsync(state => state.GameAccountId == gameAccountId && state.ServerId == serverId, cancellationToken).ConfigureAwait(false); return states.OrderBy(state => state.CreatedAtTime).ThenBy(state => state.Id).Select(ToEntity).ToList(); } - /// 列出账号下全部玩家档案(不限 App/Server 归属;按创建时间升序,并列按 Id 定序)。 + /// 列出账号下全部玩家档案(不限区服归属;按创建时间升序,并列按 Id 定序)。 /// 游戏账号标识。 /// 取消令牌。 /// 玩家档案列表。 @@ -241,7 +239,7 @@ public async Task> ListAllPlayersAsync(long g /// 设备实体;不存在返回 null。 public async Task FindDeviceAsync(long gameAccountId, string deviceIdentifier, CancellationToken cancellationToken = default) { - var state = await FindDeviceStateAsync(BuildDeviceKey(gameAccountId, deviceIdentifier), cancellationToken).ConfigureAwait(false); + var state = await FindDeviceStateAsync(OnlineRowKey.PlayerDevice(gameAccountId, deviceIdentifier), cancellationToken).ConfigureAwait(false); return state == null ? null : ToEntity(state); } @@ -252,7 +250,7 @@ public async Task AddOrUpdateDeviceAsync(OnlinePlayerDevice device, Cancellation { ArgumentNullException.ThrowIfNull(device); - var uniqueKey = BuildDeviceKey(device.GameAccountId, device.DeviceIdentifier); + var uniqueKey = OnlineRowKey.PlayerDevice(device.GameAccountId, device.DeviceIdentifier); var existing = await FindDeviceStateAsync(uniqueKey, cancellationToken).ConfigureAwait(false); if (existing != null) { @@ -335,26 +333,6 @@ private static Task FindDeviceStateAsync(string uniqueK return GameDb.FindAsync(state => state.UniqueKey == uniqueKey, isCreateIfNotExists: false, cancellationToken: cancellationToken); } - /// 构造身份唯一键(与 InMemory BuildIdentityKey 同构)。 - /// 租户标识。 - /// 应用标识。 - /// 身份类型。 - /// 身份标识串。 - /// 复合键字符串。 - private static string BuildIdentityKey(long tenantId, long appId, OnlineIdentityKind kind, string identifier) - { - return tenantId + ":" + appId + ":" + (int)kind + ":" + identifier; - } - - /// 构造设备唯一键(与 InMemory BuildDeviceKey 同构)。 - /// 游戏账号标识。 - /// 设备唯一标识串。 - /// 复合键字符串。 - private static string BuildDeviceKey(long gameAccountId, string deviceIdentifier) - { - return gameAccountId + ":" + deviceIdentifier; - } - /// 身份实体 → 行(指定行 Id;RowVersion 由写入路径管理——条件写原语递增 / 盲写回填存量,不作实体映射输入)。 private static OnlineIdentityState ToState(OnlineIdentity identity, string uniqueKey, long rowId) { @@ -363,8 +341,6 @@ private static OnlineIdentityState ToState(OnlineIdentity identity, string uniqu Id = rowId, UniqueKey = uniqueKey, EntityId = identity.Id, - TenantId = identity.TenantId, - AppId = identity.AppId, Kind = (int)identity.Kind, Identifier = identity.Identifier, GameAccountId = identity.GameAccountId, @@ -380,8 +356,6 @@ private static OnlineIdentity ToEntity(OnlineIdentityState state) return new OnlineIdentity { Id = state.EntityId, - TenantId = state.TenantId, - AppId = state.AppId, Kind = (OnlineIdentityKind)state.Kind, Identifier = state.Identifier, GameAccountId = state.GameAccountId, @@ -398,8 +372,6 @@ private static OnlineGameAccountState ToState(OnlineGameAccount account) return new OnlineGameAccountState { Id = account.Id, - TenantId = account.TenantId, - AppId = account.AppId, Status = (int)account.Status, CreatedAtTime = account.CreatedAtTime, UpdatedAtTime = account.UpdatedAtTime, @@ -415,8 +387,6 @@ private static OnlineGameAccount ToEntity(OnlineGameAccountState state) return new OnlineGameAccount { Id = state.Id, - TenantId = state.TenantId, - AppId = state.AppId, Status = (OnlineGameAccountStatus)state.Status, CreatedAtTime = state.CreatedAtTime, UpdatedAtTime = state.UpdatedAtTime, @@ -433,8 +403,6 @@ private static OnlinePlayerProfileState ToState(OnlinePlayerProfile player) { Id = player.Id, GameAccountId = player.GameAccountId, - TenantId = player.TenantId, - AppId = player.AppId, ServerId = player.ServerId, Name = player.Name, CreatedAtTime = player.CreatedAtTime, @@ -449,8 +417,6 @@ private static OnlinePlayerProfile ToEntity(OnlinePlayerProfileState state) { Id = state.Id, GameAccountId = state.GameAccountId, - TenantId = state.TenantId, - AppId = state.AppId, ServerId = state.ServerId, Name = state.Name, CreatedAtTime = state.CreatedAtTime, diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlineGameAccountState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlineGameAccountState.cs index 6264a9484..14e756847 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlineGameAccountState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlineGameAccountState.cs @@ -41,15 +41,6 @@ namespace GameFrameX.Capability.Online.Persistence.Identity; /// public sealed class OnlineGameAccountState : BaseCacheState { - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } /// /// 获取或设置账号状态(枚举数值落库)。 diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlineIdentityState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlineIdentityState.cs index c5894b925..5b0f40408 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlineIdentityState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlineIdentityState.cs @@ -35,8 +35,8 @@ namespace GameFrameX.Capability.Online.Persistence.Identity; /// /// 外源身份持久化行(Identity 域 → GameDb 适配的落库形态)。 /// -/// 键编码约定: = 物化复合键(无损拼接原文,与 InMemory -/// BuildIdentityKey 同构),单列唯一索引承接四元组 (TenantId, AppId, Kind, Identifier) 唯一性; +/// 键编码约定: = 物化复合键(无损拼接原文,与 InMemory 键同构, +/// 唯一构造点 OnlineRowKey.Identity),单列唯一索引承接二元组 (Kind, Identifier) 唯一性; /// 分隔符冒号与业务串内冒号的歧义语义与 InMemory 键逐字节同构(保真优先)。行 Id 无自然主键, /// 由 NextSequenceAsync 分配;业务字段保留为独立列供等值/归属查询。 /// @@ -44,7 +44,7 @@ namespace GameFrameX.Capability.Online.Persistence.Identity; public sealed class OnlineIdentityState : BaseCacheState { /// - /// 获取或设置物化复合键("tenant:app:kind:identifier";唯一索引列)。 + /// 获取或设置物化复合键("kind:identifier";唯一索引列)。 /// [EntityIndex("ux_online_identity_unique_key", Unique = true)] public string UniqueKey { get; set; } @@ -54,16 +54,6 @@ public sealed class OnlineIdentityState : BaseCacheState /// public string EntityId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置身份类型(枚举数值落库)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlinePlayerDeviceState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlinePlayerDeviceState.cs index c525c4119..570530bfa 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlinePlayerDeviceState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlinePlayerDeviceState.cs @@ -36,7 +36,7 @@ namespace GameFrameX.Capability.Online.Persistence.Identity; /// 玩家设备持久化行(一级 store:Identity 域 → GameDb 适配的落库形态)。 /// /// 键编码约定: = 物化复合键("gameAccountId:deviceIdentifier", -/// 与 InMemory BuildDeviceKey 同构)单列唯一索引承接二元组唯一性;行 Id 无自然主键, +/// 与 InMemory 键同构,唯一构造点 OnlineRowKey.PlayerDevice)单列唯一索引承接二元组唯一性;行 Id 无自然主键, /// 由 NextSequenceAsync 分配。 /// /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlinePlayerProfileState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlinePlayerProfileState.cs index 8c3903105..ca555e21c 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlinePlayerProfileState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Identity/OnlinePlayerProfileState.cs @@ -35,7 +35,7 @@ namespace GameFrameX.Capability.Online.Persistence.Identity; /// 玩家档案持久化行(一级 store:Identity 域 → GameDb 适配的落库形态)。 /// /// 键编码约定:行 Id = 实体自然 long 主键(PlayerId 直用);归属检索按 -/// (GameAccountId[, AppId, ServerId]) 字段查询,列举按 CreatedAtTime 升序(适配层排序); +/// (GameAccountId, ServerId) 字段查询,列举按 CreatedAtTime 升序(适配层排序); /// 玩家标识序列(NextPlayerIdAsync)由 NextSequenceAsync<OnlinePlayerProfileState> 承接。 /// /// @@ -46,15 +46,6 @@ public sealed class OnlinePlayerProfileState : BaseCacheState /// public long GameAccountId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } /// /// 获取或设置区服标识。 diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Match/GameDbOnlineMatchSettlementStore.cs b/Capability/GameFrameX.Capability.Online.Persistence/Match/GameDbOnlineMatchSettlementStore.cs index a2be03430..2e604aec6 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Match/GameDbOnlineMatchSettlementStore.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Match/GameDbOnlineMatchSettlementStore.cs @@ -17,10 +17,10 @@ namespace GameFrameX.Capability.Online.Persistence.Match; using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; using GameFrameX.Capability.Online.Match; using GameFrameX.DataBase; @@ -51,15 +51,13 @@ public sealed class GameDbOnlineMatchSettlementStore : IOnlineMatchSettlementSto /// private const string OutboxRowIdSequence = "row-id"; - /// 按作用域与对局标识查找结算结果副本。 - /// 租户标识。 - /// App 标识。 + /// 按对局标识查找结算结果副本。 /// 对局标识。 /// 取消令牌。 /// 结果副本;未结算返回 null。 - public async Task FindByMatchAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default) + public async Task FindByMatchAsync(string matchId, CancellationToken cancellationToken = default) { - var state = await FindResultRowAsync(BuildResultKey(tenantId, appId, matchId), cancellationToken).ConfigureAwait(false); + var state = await FindResultRowAsync(OnlineRowKey.MatchResult(matchId), cancellationToken).ConfigureAwait(false); return state == null || state.Result == null ? null : state.Result.Copy(); } @@ -74,14 +72,12 @@ public async Task CommitAsync(OnlineMatchResult result, Cance throw new ArgumentNullException(nameof(result)); } - var uniqueKey = BuildResultKey(result.TenantId, result.AppId, result.MatchId); + var uniqueKey = OnlineRowKey.MatchResult(result.MatchId); var rowId = await GameDb.NextSequenceAsync(ResultRowIdSequence, cancellationToken).ConfigureAwait(false); var state = new OnlineMatchResultRowState { Id = rowId, UniqueKey = uniqueKey, - TenantId = result.TenantId, - AppId = result.AppId, MatchId = result.MatchId, Result = result.Copy(), }; @@ -219,8 +215,6 @@ public async Task TryWriteBackAsync(OnlineMatchRewardOutboxRecord record, stored.RowVersion = record.RowVersion + 1; row.Record = stored; row.MatchId = stored.MatchId; - row.TenantId = stored.TenantId; - row.AppId = stored.AppId; row.NextAttemptTimeUnixMilliseconds = stored.NextAttemptTimeUnixMilliseconds; row.ClaimExpiresAtUnixMilliseconds = stored.ClaimExpiresAtUnixMilliseconds; return await GameDb.UpdateIfRowVersionAsync(row.Id, expectedRowVersion, row, cancellationToken).ConfigureAwait(false); @@ -277,8 +271,6 @@ private static OnlineMatchRewardOutboxRecord BuildInitialOutbox(OnlineMatchResul { MatchResultId = result.MatchResultId, MatchId = result.MatchId, - TenantId = result.TenantId, - AppId = result.AppId, Result = result.Copy(), RowVersion = 1, }; @@ -312,8 +304,6 @@ private static OnlineMatchRewardOutboxRowState ToOutboxRow(long rowId, OnlineMat Id = rowId, MatchResultId = record.MatchResultId, MatchId = record.MatchId, - TenantId = record.TenantId, - AppId = record.AppId, NextAttemptTimeUnixMilliseconds = record.NextAttemptTimeUnixMilliseconds, ClaimExpiresAtUnixMilliseconds = record.ClaimExpiresAtUnixMilliseconds, Record = record.Copy(), @@ -351,18 +341,4 @@ private static OnlineMatchSettlementRetryEntry ToRetryEntry(OnlineMatchRewardOut }; } - /// 构造结果作用域隔离键(与 InMemory 实现逐字节同构)。 - /// 租户标识。 - /// App 标识。 - /// 对局标识。 - /// 复合键。 - private static string BuildResultKey(long tenantId, long appId, string matchId) - { - return string.Concat( - tenantId.ToString(CultureInfo.InvariantCulture), - ":", - appId.ToString(CultureInfo.InvariantCulture), - ":", - matchId ?? string.Empty); - } } diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Match/OnlineMatchResultRowState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Match/OnlineMatchResultRowState.cs index e53b2bc5a..bd1e57663 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Match/OnlineMatchResultRowState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Match/OnlineMatchResultRowState.cs @@ -23,29 +23,20 @@ namespace GameFrameX.Capability.Online.Persistence.Match; /// /// 结算结果持久化行(Match 域 → GameDb 适配的落库形态)。 /// -/// 键编码约定: = 物化复合键("tenant:app:matchId",与 InMemory 实现同构), -/// 单列唯一索引承接 (TenantId, AppId, MatchId) 唯一性——「同一对局首次结果胜出」由 -/// TryAddUniqueAsync 原语在数据库层担保。 +/// 键编码约定: = 物化复合键("{matchId}",与 InMemory 实现同构, +/// 唯一构造点 OnlineRowKey.MatchResult——对局标识为 match-{Guid:N} 全局唯一, +/// 区服维度由 文档的 ServerId 快照承载),单列唯一索引承接 MatchId +/// 唯一性——「同一对局首次结果胜出」由 TryAddUniqueAsync 原语在数据库层担保。 /// /// public sealed class OnlineMatchResultRowState : BaseCacheState { /// - /// 获取或设置物化复合键("tenant:app:matchId";唯一索引列)。 + /// 获取或设置物化复合键("{matchId}";唯一索引列)。 /// [EntityIndex("ux_online_match_result_unique_key", Unique = true)] public string UniqueKey { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置对局标识。 /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Match/OnlineMatchRewardOutboxRowState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Match/OnlineMatchRewardOutboxRowState.cs index 1bfae2a23..8da19cb63 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Match/OnlineMatchRewardOutboxRowState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Match/OnlineMatchRewardOutboxRowState.cs @@ -46,16 +46,6 @@ public sealed class OnlineMatchRewardOutboxRowState : BaseCacheState /// public string MatchId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置下一轮投递最早时刻(Unix 毫秒;0 = 立即可投)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Social/GameDbOnlineFriendStore.cs b/Capability/GameFrameX.Capability.Online.Persistence/Social/GameDbOnlineFriendStore.cs index 5550cb6a9..16e4c8752 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Social/GameDbOnlineFriendStore.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Social/GameDbOnlineFriendStore.cs @@ -29,6 +29,7 @@ namespace GameFrameX.Capability.Online.Persistence.Social; +using GameFrameX.Capability.Online.Abstractions.Keys; using GameFrameX.Capability.Online.Social; using GameFrameX.DataBase; @@ -80,7 +81,7 @@ public async Task SaveIfAbsentAsync(OnlineFriendship friendshi { ArgumentNullException.ThrowIfNull(friendship); - var uniqueKey = BuildPairKey(friendship.TenantId, friendship.AppId, friendship.LowPlayerId, friendship.HighPlayerId); + var uniqueKey = OnlineRowKey.Friendship(friendship.LowPlayerId, friendship.HighPlayerId); var existing = await FindRowAsync(uniqueKey, cancellationToken).ConfigureAwait(false); if (existing != null) { @@ -112,38 +113,34 @@ public async Task SaveIfAbsentAsync(OnlineFriendship friendshi /// /// Canonicalizes the two players into the undirected pair first, then looks up by the materialized composite key and returns a copy (either direction of the arguments hits the same record). /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 一侧玩家标识(无需预先规范化) / One-side player id (no pre-canonicalization needed) /// 另一侧玩家标识(无需预先规范化) / Other-side player id (no pre-canonicalization needed) /// 取消令牌 / Cancellation token /// 关系副本;不存在返回 null / Copy of the friendship; null if absent - public async Task FindAsync(long tenantId, long appId, long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default) + public async Task FindAsync(long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default) { long low; long high; OnlineFriendship.Canonicalize(leftPlayerId, rightPlayerId, out low, out high); - var state = await FindRowAsync(BuildPairKey(tenantId, appId, low, high), cancellationToken).ConfigureAwait(false); + var state = await FindRowAsync(OnlineRowKey.Friendship(low, high), cancellationToken).ConfigureAwait(false); return state == null ? null : ToEntity(state); } /// - /// 以 CAS 语义改写关系状态:按关系标识定位行,作用域或当前状态与期望不符(或记录不存在)时不留写入痕迹并返回 null。 + /// 以 CAS 语义改写关系状态:按关系标识定位行,当前状态与期望不符(或记录不存在)时不留写入痕迹并返回 null。 /// /// - /// Rewrites the friendship state with CAS semantics: locates the row by friendship id and leaves no write trace, returning null on scope mismatch, expected-state mismatch or missing record. + /// Rewrites the friendship state with CAS semantics: locates the row by friendship id and leaves no write trace, returning null on expected-state mismatch or missing record. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 状态迁移载荷(关系定位 + 期望/目标状态 + 变更时刻与答复标记) / State transition payload (friendship locator + expected/target states + change time and responded flag) /// 取消令牌 / Cancellation token /// 更新后的关系副本;CAS 失败或记录不存在返回 null / Copy of the updated friendship; null on CAS failure or missing record /// 当 为 null 时抛出 / Thrown when is null - public async Task UpdateStateAsync(long tenantId, long appId, FriendshipStateTransition transition, CancellationToken cancellationToken = default) + public async Task UpdateStateAsync(FriendshipStateTransition transition, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(transition); - return await TransitionRowAsync(tenantId, appId, transition.FriendshipId ?? string.Empty, current => + return await TransitionRowAsync(transition.FriendshipId ?? string.Empty, current => { if ((OnlineFriendshipState)current.State != transition.ExpectedState) { @@ -170,14 +167,12 @@ public async Task UpdateStateAsync(long tenantId, long appId, /// /// Rewrites the friendship state with CAS semantics and enforces the friend limit inside the same method: when the target state is Accepted with a positive limit, counts both sides' established (Accepted) relations first and rejects with zero writes once either side has reached the limit. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 状态迁移载荷(关系定位 + 期望/目标状态 + 变更时刻与答复标记) / State transition payload (friendship locator + expected/target states + change time and responded flag) /// 已建立好友数上限(<= 0 表示不启用上限判定) / Established friend limit (<= 0 disables the limit check) /// 取消令牌 / Cancellation token /// 迁移结果:成功携带更新后的副本;上限拒绝置 FriendLimitReached;CAS 失败两者皆空 / Transition outcome: updated copy on success; FriendLimitReached on limit rejection; both empty on CAS failure /// 当 为 null 时抛出 / Thrown when is null - public async Task UpdateStateWithFriendLimitAsync(long tenantId, long appId, FriendshipStateTransition transition, int establishedFriendLimit, CancellationToken cancellationToken = default) + public async Task UpdateStateWithFriendLimitAsync(FriendshipStateTransition transition, int establishedFriendLimit, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(transition); @@ -187,11 +182,6 @@ public async Task UpdateStateWithFriendLimit return OnlineFriendStateTransitionOutcome.FromCasConflict(); } - if (current.TenantId != tenantId || current.AppId != appId) - { - return OnlineFriendStateTransitionOutcome.FromCasConflict(); - } - if ((OnlineFriendshipState)current.State != transition.ExpectedState) { return OnlineFriendStateTransitionOutcome.FromCasConflict(); @@ -202,8 +192,8 @@ public async Task UpdateStateWithFriendLimit // 计数与写入收在同一方法内:本行此刻尚处 Requested(未计入),两侧任一满员即整体拒绝、零写入。 // ponytail:跨行「计数 + 覆盖写」依赖 GameDb 行级写收敛;多实例并发下残余窗口以单写者语义收口, // 需要硬约束时下沉为数据库内计数事务。 - if (await CountEstablishedAsync(tenantId, appId, current.RequesterId, cancellationToken).ConfigureAwait(false) >= establishedFriendLimit - || await CountEstablishedAsync(tenantId, appId, current.AddresseeId, cancellationToken).ConfigureAwait(false) >= establishedFriendLimit) + if (await CountEstablishedAsync(current.RequesterId, cancellationToken).ConfigureAwait(false) >= establishedFriendLimit + || await CountEstablishedAsync(current.AddresseeId, cancellationToken).ConfigureAwait(false) >= establishedFriendLimit) { return OnlineFriendStateTransitionOutcome.FromFriendLimitReached(); } @@ -221,19 +211,16 @@ public async Task UpdateStateWithFriendLimit } /// - /// 统计某玩家在作用域内已建立(Accepted)的好友关系数。 + /// 统计某玩家已建立(Accepted)的好友关系数。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 已建立的好友关系数。 - private static async Task CountEstablishedAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken) + private static async Task CountEstablishedAsync(long playerId, CancellationToken cancellationToken) { var acceptedState = (int)OnlineFriendshipState.Accepted; var states = await GameDb.FindListAsync( - state => state.TenantId == tenantId && state.AppId == appId - && state.State == acceptedState + state => state.State == acceptedState && (state.LowPlayerId == playerId || state.HighPlayerId == playerId), cancellationToken).ConfigureAwait(false); return states.Count; @@ -245,17 +232,15 @@ private static async Task CountEstablishedAsync(long tenantId, long appId, /// /// Re-initiates a quiescent friendship as a pending request with CAS semantics, writing state, direction and expiry together onto the same row. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 重新发起载荷(关系标识、期望状态、发起人、被请求方、变更时刻、失效时刻) / Renewal payload (friendship id, expected state, requester, addressee, change time, expiry) /// 取消令牌 / Cancellation token /// 更新后的关系副本;CAS 失败或记录不存在返回 null / Copy of the updated friendship; null on CAS failure or missing record /// 当 为 null 时抛出 / Thrown when is null - public async Task RenewRequestAsync(long tenantId, long appId, FriendshipRenewal renewal, CancellationToken cancellationToken = default) + public async Task RenewRequestAsync(FriendshipRenewal renewal, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(renewal); - return await TransitionRowAsync(tenantId, appId, renewal.FriendshipId ?? string.Empty, current => (OnlineFriendshipState)current.State == renewal.ExpectedState, current => + return await TransitionRowAsync(renewal.FriendshipId ?? string.Empty, current => (OnlineFriendshipState)current.State == renewal.ExpectedState, current => { // 三项同临界区落定:状态 + 方向 + 有效期(拆开写会让权限判据读到半成品)。 current.State = (int)OnlineFriendshipState.Requested; @@ -267,40 +252,36 @@ public async Task RenewRequestAsync(long tenantId, long appId, } /// - /// 列出作用域内包含指定玩家的全部关系记录(任意状态;双侧等值匹配 + Tenant/App 过滤)。 + /// 列出包含指定玩家的全部关系记录(任意状态;双侧等值匹配)。 /// /// - /// Lists all friendship records in the scope containing the given player (any state; both-side equality plus tenant/app filtering). + /// Lists all friendship records containing the given player (any state; both-side equality). /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌 / Cancellation token /// 关系副本列表 / List of friendship copies - public async Task> ListByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public async Task> ListByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { var states = await GameDb.FindListAsync( - state => state.TenantId == tenantId && state.AppId == appId && (state.LowPlayerId == playerId || state.HighPlayerId == playerId), + state => state.LowPlayerId == playerId || state.HighPlayerId == playerId, cancellationToken).ConfigureAwait(false); return states.Select(ToEntity).ToList(); } /// - /// 列出作用域内处于指定状态的全部关系记录(状态 + Tenant/App 过滤)。 + /// 列出处于指定状态的全部关系记录(超期扫描输入)。 /// /// - /// Lists all friendship records in the scope with the given state (state plus tenant/app filtering). + /// Lists all friendship records with the given state (expiry-sweep input). /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 关系状态 / Friendship state /// 取消令牌 / Cancellation token /// 关系副本列表 / List of friendship copies - public async Task> ListByStateAsync(long tenantId, long appId, OnlineFriendshipState state, CancellationToken cancellationToken = default) + public async Task> ListByStateAsync(OnlineFriendshipState state, CancellationToken cancellationToken = default) { var stateValue = (int)state; var states = await GameDb.FindListAsync( - state => state.TenantId == tenantId && state.AppId == appId && state.State == stateValue, + state => state.State == stateValue, cancellationToken).ConfigureAwait(false); return states.Select(ToEntity).ToList(); } @@ -328,25 +309,23 @@ private static Task FindRowByIdAsync(string friendship } /// - /// CAS 迁移回路:读行(带 RowVersion)→ 作用域与前置校验 → 行版本条件写;冲突时重读重校验,最多 3 次。 + /// CAS 迁移回路:读行(带 RowVersion)→ 前置校验 → 行版本条件写;冲突时重读重校验,最多 3 次。 /// /// - /// The CAS transition loop: read the row (with its RowVersion) → validate scope and the + /// The CAS transition loop: read the row (with its RowVersion) → validate the /// caller's precondition → conditional write via UpdateIfRowVersionAsync. A false return /// means a concurrent writer advanced the row version; the loop re-reads and re-validates up to /// times. Preconditions failing on the freshly-read row - /// (scope mismatch, expected-state mismatch, missing row) return null immediately — the + /// (expected-state mismatch, missing row) return null immediately — the /// store-contract CAS failure. Exhausted retries also return null (the caller re-reads the /// current fact and converges); no partial writes ever land. /// - /// 租户标识。 - /// App 标识。 /// 关系标识。 /// 对刚读出的行做期望校验(false = CAS 失败,返回 null,不写入)。 /// 把目标态写进行对象(在条件写之前应用于本行)。 /// 取消令牌。 /// 更新后的关系副本;CAS 失败或记录不存在返回 null。 - private static async Task TransitionRowAsync(long tenantId, long appId, string friendshipId, Func precondition, Action apply, CancellationToken cancellationToken) + private static async Task TransitionRowAsync(string friendshipId, Func precondition, Action apply, CancellationToken cancellationToken) { for (var attempt = 0; attempt < MaxTransitionAttemptCount; attempt++) { @@ -356,24 +335,18 @@ private static async Task TransitionRowAsync(long tenantId, lo return null; } - // 作用域校验先于任何写入(含存量补全写)。 - if (current.TenantId != tenantId || current.AppId != appId) - { - return null; - } - current = await EnsureRowVersionAsync(current, cancellationToken).ConfigureAwait(false); if (current == null) { return null; } - // 补全/重读之后必须复检作用域与前置条件:存量行补全被并发抢先时, + // 补全/重读之后必须复检前置条件:存量行补全被并发抢先时, // 重读到的可能是并发写者已推进过的行(状态已变),不复检会把非法迁移写进库。 - // The scope and the precondition must be re-checked after the backfill/re-read: when a + // The precondition must be re-checked after the backfill/re-read: when a // concurrent writer wins the legacy backfill, the re-read row may already have moved on, // and skipping the re-check would persist an illegal transition. - if (current.TenantId != tenantId || current.AppId != appId || !precondition(current)) + if (!precondition(current)) { return null; } @@ -422,19 +395,6 @@ private static async Task EnsureRowVersionAsync(Online return await FindRowByIdAsync(current.FriendshipId, cancellationToken).ConfigureAwait(false); } - /// - /// 构造无向对唯一键(与 InMemory BuildPairKey 同构)。 - /// - /// 租户标识。 - /// App 标识。 - /// 低标识侧玩家。 - /// 高标识侧玩家。 - /// 复合键字符串。 - private static string BuildPairKey(long tenantId, long appId, long lowPlayerId, long highPlayerId) - { - return "friend:" + tenantId + ":" + appId + ":" + lowPlayerId + ":" + highPlayerId; - } - /// /// 实体 → 行(指定行 Id;全字段物化,唯一键由字段派生)。 /// @@ -449,8 +409,6 @@ private static OnlineFriendshipRowState ToState(OnlineFriendship friendship, str Id = rowId, UniqueKey = uniqueKey, FriendshipId = friendship.FriendshipId ?? string.Empty, - TenantId = friendship.TenantId, - AppId = friendship.AppId, ServerId = friendship.ServerId, LowPlayerId = friendship.LowPlayerId, HighPlayerId = friendship.HighPlayerId, @@ -474,8 +432,6 @@ private static OnlineFriendship ToEntity(OnlineFriendshipRowState state) return new OnlineFriendship { FriendshipId = state.FriendshipId, - TenantId = state.TenantId, - AppId = state.AppId, ServerId = state.ServerId, LowPlayerId = state.LowPlayerId, HighPlayerId = state.HighPlayerId, diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Social/OnlineFriendshipRowState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Social/OnlineFriendshipRowState.cs index 5f70feab9..8680e38d6 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Social/OnlineFriendshipRowState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Social/OnlineFriendshipRowState.cs @@ -36,8 +36,8 @@ namespace GameFrameX.Capability.Online.Persistence.Social; /// 好友关系持久化行(Social 域 → GameDb 适配的落库形态)。 /// /// 键编码约定(物化复合键): = -/// "friend:{TenantId}:{AppId}:{LowPlayerId}:{HighPlayerId}"(作用域 + 规范化无向对,与 InMemory -/// BuildPairKey 同构),单列唯一索引承接「一对玩家至多一条关系记录」的结构性不变量。 +/// "friend:{LowPlayerId}:{HighPlayerId}"(规范化无向对,与 InMemory 键同构, +/// 唯一构造点 OnlineRowKey.Friendship),单列唯一索引承接「一对玩家至多一条关系记录」的结构性不变量。 /// 行 Id 无自然主键,由 NextSequenceAsync 分配;业务字段保留为独立列供等值/归属查询; /// 状态以枚举数值落库。 /// @@ -45,7 +45,7 @@ namespace GameFrameX.Capability.Online.Persistence.Social; public sealed class OnlineFriendshipRowState : BaseCacheState { /// - /// 获取或设置物化复合键("friend:{TenantId}:{AppId}:{LowPlayerId}:{HighPlayerId}";唯一索引列)。 + /// 获取或设置物化复合键("friend:{LowPlayerId}:{HighPlayerId}";唯一索引列)。 /// [EntityIndex("ux_online_friendship_unique_key", Unique = true)] public string UniqueKey { get; set; } @@ -55,16 +55,6 @@ public sealed class OnlineFriendshipRowState : BaseCacheState /// public string FriendshipId { get; set; } - /// - /// 获取或设置租户标识(数据隔离根边界)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(数据隔离根边界)。 - /// - public long AppId { get; set; } - /// /// 获取或设置关系建立时的来源区服标识(仅审计参考,不参与唯一键)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Storage/GameDbOnlinePlayerStorageStore.cs b/Capability/GameFrameX.Capability.Online.Persistence/Storage/GameDbOnlinePlayerStorageStore.cs index 84779369a..eaf254093 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Storage/GameDbOnlinePlayerStorageStore.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Storage/GameDbOnlinePlayerStorageStore.cs @@ -31,13 +31,14 @@ namespace GameFrameX.Capability.Online.Persistence.Storage; using System.Threading; using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; using GameFrameX.Capability.Online.Foundation.Storage; using GameFrameX.DataBase; /// /// 玩家云存储 GameDb 持久化适配(一级 store;CAS 乐观锁经条件写原语落地)。 /// -/// CAS 语义(版本换算):expectedVersion == 0 → TryAddUniqueAsync(五元组唯一索引互斥, +/// CAS 语义(版本换算):expectedVersion == 0 → TryAddUniqueAsync(三元组唯一索引互斥, /// 已存在即 false);> 0 → UpdateIfRowVersionAsync(行Id, expectedVersion - 1, 新档) /// (行缺失或存量 RowVersion 不符即 false——原子单语句比较交换)。恒等式 /// 实体 Version = 行 RowVersion + 1(实体从 1 起、行版本从 0 起),读回按此校准。 @@ -71,7 +72,7 @@ public async Task FindAsync(OnlineStorageEntryKey key, { ArgumentNullException.ThrowIfNull(key); - var state = await FindStateAsync(BuildKey(key.TenantId, key.AppId, key.PlayerId, key.Collection, key.Key), cancellationToken).ConfigureAwait(false); + var state = await FindStateAsync(OnlineRowKey.PlayerStorage(key.PlayerId, key.Collection, key.Key), cancellationToken).ConfigureAwait(false); return state == null ? null : ToEntity(state); } @@ -86,7 +87,7 @@ public async Task UpsertAsync(OnlinePlayerStorageEntry entry, long expecte { ArgumentNullException.ThrowIfNull(entry); - var uniqueKey = BuildKey(entry.TenantId, entry.AppId, entry.PlayerId, entry.Collection, entry.Key); + var uniqueKey = OnlineRowKey.PlayerStorage(entry.PlayerId, entry.Collection, entry.Key); var existing = await FindStateAsync(uniqueKey, cancellationToken).ConfigureAwait(false); if (expectedVersion == 0) { @@ -117,7 +118,7 @@ public async Task> ListAsync(OnlineStora ArgumentNullException.ThrowIfNull(query); var afterKey = query.AfterKey ?? string.Empty; - var states = await GameDb.FindListAsync(state => state.TenantId == query.TenantId && state.AppId == query.AppId && state.PlayerId == query.PlayerId && state.Collection == query.Collection, cancellationToken).ConfigureAwait(false); + var states = await GameDb.FindListAsync(state => state.PlayerId == query.PlayerId && state.Collection == query.Collection, cancellationToken).ConfigureAwait(false); return states.Where(state => state.DeletedAtTime == 0) .Where(state => afterKey.Length == 0 || string.CompareOrdinal(state.Key, afterKey) > 0) .OrderBy(state => state.Key, StringComparer.Ordinal) @@ -127,15 +128,13 @@ public async Task> ListAsync(OnlineStora } /// 统计集合内活跃(非软删)键数。 - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 集合名。 /// 取消令牌。 /// 活跃键数。 - public async Task CountActiveKeysAsync(long tenantId, long appId, long playerId, string collection, CancellationToken cancellationToken = default) + public async Task CountActiveKeysAsync(long playerId, string collection, CancellationToken cancellationToken = default) { - var count = await GameDb.CountAsync(state => state.TenantId == tenantId && state.AppId == appId && state.PlayerId == playerId && state.Collection == collection && state.DeletedAtTime == 0, cancellationToken).ConfigureAwait(false); + var count = await GameDb.CountAsync(state => state.PlayerId == playerId && state.Collection == collection && state.DeletedAtTime == 0, cancellationToken).ConfigureAwait(false); return checked((int)count); } @@ -157,18 +156,6 @@ private static Task FindStateAsync(string uniqueK return GameDb.FindAsync(state => state.UniqueKey == uniqueKey, isCreateIfNotExists: false, cancellationToken: cancellationToken); } - /// 构造条目完整键(与 InMemory BuildKey 同构)。 - /// 租户标识。 - /// 应用标识。 - /// 玩家标识。 - /// 集合名。 - /// 条目键。 - /// 复合键字符串。 - private static string BuildKey(long tenantId, long appId, long playerId, string collection, string key) - { - return tenantId + ":" + appId + ":" + playerId + ":" + collection + ":" + key; - } - /// 条目实体 → 行(指定行 Id;RowVersion 由写原语管理,不作映射输入)。 private static OnlinePlayerStorageEntryState ToState(OnlinePlayerStorageEntry entry, string uniqueKey, long rowId) { @@ -176,8 +163,6 @@ private static OnlinePlayerStorageEntryState ToState(OnlinePlayerStorageEntry en { Id = rowId, UniqueKey = uniqueKey, - TenantId = entry.TenantId, - AppId = entry.AppId, PlayerId = entry.PlayerId, Collection = entry.Collection, Key = entry.Key, @@ -196,8 +181,6 @@ private static OnlinePlayerStorageEntry ToEntity(OnlinePlayerStorageEntryState s { return new OnlinePlayerStorageEntry { - TenantId = state.TenantId, - AppId = state.AppId, PlayerId = state.PlayerId, Collection = state.Collection, Key = state.Key, diff --git a/Capability/GameFrameX.Capability.Online.Persistence/Storage/OnlinePlayerStorageEntryState.cs b/Capability/GameFrameX.Capability.Online.Persistence/Storage/OnlinePlayerStorageEntryState.cs index c04ea5b6d..5061c0f4b 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/Storage/OnlinePlayerStorageEntryState.cs +++ b/Capability/GameFrameX.Capability.Online.Persistence/Storage/OnlinePlayerStorageEntryState.cs @@ -35,8 +35,9 @@ namespace GameFrameX.Capability.Online.Persistence.Storage; /// /// 玩家云存储条目持久化行(一级 store:Storage 域 → GameDb 适配的落库形态)。 /// -/// 键编码与版本约定: = 物化复合键(五元组无损拼接, -/// 与 InMemory BuildKey 同构)单列唯一索引,承接「expectedVersion == 0 仅创建」的互斥; +/// 键编码与版本约定: = 物化复合键(三元组无损拼接, +/// 与 InMemory 键同构,唯一构造点 OnlineRowKey.PlayerStorage)单列唯一索引, +/// 承接「expectedVersion == 0 仅创建」的互斥; /// 行 Id 由 NextSequenceAsync 分配。版本换算: 的 RowVersion /// 从 0 起(插入 = 0、每次 CAS 递增),实体 Version 从 1 起——恒等式 /// Version = RowVersion + 1,CAS 目标行版本 = expectedVersion - 1(适配层内换算)。 @@ -47,21 +48,11 @@ namespace GameFrameX.Capability.Online.Persistence.Storage; public sealed class OnlinePlayerStorageEntryState : BaseCacheState { /// - /// 获取或设置物化复合键("tenant:app:player:collection:key";唯一索引列)。 + /// 获取或设置物化复合键("player:collection:key";唯一索引列)。 /// [EntityIndex("ux_online_storage_entry_unique_key", Unique = true)] public string UniqueKey { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置应用标识。 - /// - public long AppId { get; set; } - /// /// 获取或设置玩家标识。 /// diff --git a/Capability/GameFrameX.Capability.Online.Social/AdminApi/OnlineAdminSocialHandlers.cs b/Capability/GameFrameX.Capability.Online.Social/AdminApi/OnlineAdminSocialHandlers.cs index e0a9330ee..d2a371a98 100644 --- a/Capability/GameFrameX.Capability.Online.Social/AdminApi/OnlineAdminSocialHandlers.cs +++ b/Capability/GameFrameX.Capability.Online.Social/AdminApi/OnlineAdminSocialHandlers.cs @@ -143,8 +143,6 @@ public async Task MatchIsolationAsync(AdminApiRequest request, OnlineSco { OnlineAdminApiContract.Unwrap(await _punishments.ApplyAsync(new OnlinePunishmentRequest { - TenantId = scope.TenantId, - AppId = scope.AppId, PlayerId = playerScope.PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "match-isolation:" + reason, @@ -154,11 +152,11 @@ public async Task MatchIsolationAsync(AdminApiRequest request, OnlineSco } else { - var active = OnlineAdminApiContract.Unwrap(await _punishments.ListActiveAsync(scope.TenantId, scope.AppId, playerScope.PlayerId, 0, cancellationToken).ConfigureAwait(false)); + var active = OnlineAdminApiContract.Unwrap(await _punishments.ListActiveAsync(playerScope.PlayerId, 0, cancellationToken).ConfigureAwait(false)); var ban = active.FirstOrDefault(punishment => punishment.Kind == OnlinePunishmentKind.Ban && !punishment.Revoked); if (ban != null) { - OnlineAdminApiContract.Unwrap(await _punishments.RevokeAsync(scope.TenantId, scope.AppId, ban.PunishmentId, adminId, request.ReadRequestId(), cancellationToken).ConfigureAwait(false)); + OnlineAdminApiContract.Unwrap(await _punishments.RevokeAsync(ban.PunishmentId, adminId, request.ReadRequestId(), cancellationToken).ConfigureAwait(false)); } } @@ -176,7 +174,7 @@ public async Task KickPlayerAsync(AdminApiRequest request, OnlineScope s { var playerScope = OnlineAdminApiContract.ReadPlayerScope(request, scope); var reason = BuildPenaltyReason(request); - var sessions = await _sessionStore.ListActiveByPlayerAsync(scope.TenantId, scope.AppId, playerScope.PlayerId, cancellationToken).ConfigureAwait(false); + var sessions = await _sessionStore.ListActiveByPlayerAsync(playerScope.PlayerId, cancellationToken).ConfigureAwait(false); foreach (var session in sessions) { await _tokens.KickAsync(new OnlineTokenKickRequest { Scope = playerScope, SessionId = session.Id, Reason = reason, }, cancellationToken).ConfigureAwait(false); @@ -196,7 +194,7 @@ public async Task RevokeTokenAsync(AdminApiRequest request, OnlineScope { var playerScope = OnlineAdminApiContract.ReadPlayerScope(request, scope); var reason = BuildPenaltyReason(request); - var sessions = await _sessionStore.ListActiveByPlayerAsync(scope.TenantId, scope.AppId, playerScope.PlayerId, cancellationToken).ConfigureAwait(false); + var sessions = await _sessionStore.ListActiveByPlayerAsync(playerScope.PlayerId, cancellationToken).ConfigureAwait(false); foreach (var session in sessions) { await _tokens.RevokeAsync(new OnlineTokenRevokeRequest { Scope = playerScope, SessionId = session.Id, Reason = reason, }, cancellationToken).ConfigureAwait(false); @@ -218,8 +216,6 @@ public async Task MutePlayerAsync(AdminApiRequest request, OnlineScope s var adminId = request.ReadNullableInt64("PenaltyId") ?? 0; OnlineAdminApiContract.Unwrap(await _punishments.ApplyAsync(new OnlinePunishmentRequest { - TenantId = scope.TenantId, - AppId = scope.AppId, PlayerId = playerScope.PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = BuildPenaltyReason(request), @@ -264,7 +260,6 @@ public async Task QueryReportCasesAsync(AdminApiRequest request, OnlineS items.Add(new ReportCaseResponse { CaseId = item.ReportId, - AppId = item.AppId, ServerId = scope.ServerId, ReporterPlayerId = item.ReporterId.ToString(System.Globalization.CultureInfo.InvariantCulture), ReportedPlayerId = item.ReportedPlayerId.ToString(System.Globalization.CultureInfo.InvariantCulture), @@ -315,8 +310,6 @@ public async Task UpdateReportCaseAsync(AdminApiRequest request, OnlineS var resolution = status.Value == OnlineReportState.Rejected ? OnlineReportResolution.NoViolation : OnlineReportResolution.None; OnlineAdminApiContract.Unwrap(await _socialDecisions.TransitionReportAsync(new OnlineReportTransition { - TenantId = scope.TenantId, - AppId = scope.AppId, ReportId = caseId, TargetState = status.Value, Resolution = resolution, @@ -360,7 +353,7 @@ public async Task QueryChatMessagesAsync(AdminApiRequest request, Online var endTime = OnlineAdminApiContract.ReadOptionalInt64(request, "EndTime"); var pageSize = OnlineAdminApiContract.ReadPageSize(request); var cursor = OnlineAdminApiContract.ReadCursor(request); - var page = await _chatAudit.QueryAsync(scope.TenantId, scope.AppId, new ChatAuditQuery + var page = await _chatAudit.QueryAsync(new ChatAuditQuery { ChannelKind = channelKind, ParticipantPlayerId = participantPlayerId, @@ -410,17 +403,17 @@ private async Task> CollectReportCasesAsync(OnlineScope s var cases = new List(); if (status.HasValue) { - cases.AddRange(await _reportStore.ListByStateAsync(scope.TenantId, scope.AppId, status.Value, cancellationToken).ConfigureAwait(false)); + cases.AddRange(await _reportStore.ListByStateAsync(status.Value, cancellationToken).ConfigureAwait(false)); } else if (reporterPlayerId.HasValue) { - cases.AddRange(await _reportStore.ListByReporterAsync(scope.TenantId, scope.AppId, reporterPlayerId.Value, cancellationToken).ConfigureAwait(false)); + cases.AddRange(await _reportStore.ListByReporterAsync(reporterPlayerId.Value, cancellationToken).ConfigureAwait(false)); } else { foreach (OnlineReportState state in Enum.GetValues(typeof(OnlineReportState))) { - cases.AddRange(await _reportStore.ListByStateAsync(scope.TenantId, scope.AppId, state, cancellationToken).ConfigureAwait(false)); + cases.AddRange(await _reportStore.ListByStateAsync(state, cancellationToken).ConfigureAwait(false)); } } @@ -589,8 +582,6 @@ public sealed class ReportCaseResponse /// 获取或设置案件标识。 public string CaseId { get; set; } - /// 获取或设置 App 标识。 - public long AppId { get; set; } /// 获取或设置区服标识。 public long ServerId { get; set; } diff --git a/Capability/GameFrameX.Capability.Online.Social/IOnlineChatStore.cs b/Capability/GameFrameX.Capability.Online.Social/IOnlineChatStore.cs index aa8268ab0..6df8a3942 100644 --- a/Capability/GameFrameX.Capability.Online.Social/IOnlineChatStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/IOnlineChatStore.cs @@ -60,12 +60,10 @@ public interface IOnlineChatStore /// /// 按频道标识查找频道记录。 /// - /// 租户标识。 - /// App 标识。 /// 频道标识。 /// 取消令牌。 /// 频道记录副本;不存在返回 null。 - Task FindChannelAsync(long tenantId, long appId, string channelId, CancellationToken cancellationToken = default); + Task FindChannelAsync(string channelId, CancellationToken cancellationToken = default); /// /// 追加一条消息(分配频道内序号并落定发送时刻;去重键命中时返回既有消息且不写入)。 @@ -84,55 +82,45 @@ public interface IOnlineChatStore /// 本查询只是让重放走捷径;真正的并发唯一约束仍在 的临界区内。 /// /// - /// 租户标识。 - /// App 标识。 /// 频道标识。 /// 发送方去重键(空串表示无去重键,直接返回 null)。 /// 取消令牌。 /// 命中的消息副本;无去重键或未命中返回 null。 - Task FindByDedupeKeyAsync(long tenantId, long appId, string channelId, string dedupeKey, CancellationToken cancellationToken = default); + Task FindByDedupeKeyAsync(string channelId, string dedupeKey, CancellationToken cancellationToken = default); /// /// 按消息标识查找。 /// - /// 租户标识。 - /// App 标识。 /// 频道标识。 /// 消息标识。 /// 取消令牌。 /// 消息副本;不存在返回 null。 - Task FindMessageAsync(long tenantId, long appId, string channelId, string messageId, CancellationToken cancellationToken = default); + Task FindMessageAsync(string channelId, string messageId, CancellationToken cancellationToken = default); /// /// 以 CAS 语义改写消息状态(当前只有撤回一种迁移)。 /// - /// 租户标识。 - /// App 标识。 /// 消息状态迁移载荷(频道/消息定位 + 期望/目标状态 + 变更时刻与撤回人)。 /// 取消令牌。 /// 更新后的消息副本;CAS 失败或记录不存在返回 null。 - Task UpdateMessageStateAsync(long tenantId, long appId, ChatMessageStateTransition transition, CancellationToken cancellationToken = default); + Task UpdateMessageStateAsync(ChatMessageStateTransition transition, CancellationToken cancellationToken = default); /// /// 按稳定排序键升序读取游标之后的消息页(离线补拉与历史分页共用)。 /// - /// 租户标识。 - /// App 标识。 /// 读取游标(频道定位 + 位点二元组 + 页大小)。 /// 取消令牌。 /// 严格位于游标之后、按 (SentAtTime, Sequence) 升序排列的消息副本列表。 - Task> ReadAfterAsync(long tenantId, long appId, ChatReadCursor cursor, CancellationToken cancellationToken = default); + Task> ReadAfterAsync(ChatReadCursor cursor, CancellationToken cancellationToken = default); /// /// 统计游标之后的未读条数(排除本人发送的与已撤回的消息)。 /// - /// 租户标识。 - /// App 标识。 /// 读取游标(频道定位 + 已读位点二元组;页大小字段不消费)。 /// 读取者(本人发的消息不计未读)。 /// 取消令牌。 /// 未读条数。 - Task CountUnreadAsync(long tenantId, long appId, ChatReadCursor cursor, long readerPlayerId, CancellationToken cancellationToken = default); + Task CountUnreadAsync(ChatReadCursor cursor, long readerPlayerId, CancellationToken cancellationToken = default); /// /// 落定已读位点(整体替换:位点是只进不退的最终位置,不做增量合并)。 @@ -152,11 +140,9 @@ public interface IOnlineChatStore /// /// 查找已读位点。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 频道标识。 /// 取消令牌。 /// 已读位点副本;从未标记过返回 null。 - Task FindReadMarkAsync(long tenantId, long appId, long playerId, string channelId, CancellationToken cancellationToken = default); + Task FindReadMarkAsync(long playerId, string channelId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/IOnlineFriendStore.cs b/Capability/GameFrameX.Capability.Online.Social/IOnlineFriendStore.cs index e009369ea..5d49db943 100644 --- a/Capability/GameFrameX.Capability.Online.Social/IOnlineFriendStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/IOnlineFriendStore.cs @@ -60,23 +60,19 @@ public interface IOnlineFriendStore /// /// 按无向对查找关系(两个方向的入参都命中同一条记录)。 /// - /// 租户标识。 - /// App 标识。 /// 一侧玩家标识(无需预先规范化)。 /// 另一侧玩家标识(无需预先规范化)。 /// 取消令牌。 /// 关系副本;不存在返回 null。 - Task FindAsync(long tenantId, long appId, long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default); + Task FindAsync(long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default); /// /// 以 CAS 语义改写关系状态(接受 / 拒绝 / 过期 / 删除 / 重新发起走此入口)。 /// - /// 租户标识。 - /// App 标识。 /// 状态迁移载荷(关系定位 + 期望/目标状态 + 变更时刻与答复标记)。 /// 取消令牌。 /// 更新后的关系副本;CAS 失败或记录不存在返回 null。 - Task UpdateStateAsync(long tenantId, long appId, FriendshipStateTransition transition, CancellationToken cancellationToken = default); + Task UpdateStateAsync(FriendshipStateTransition transition, CancellationToken cancellationToken = default); /// /// 以 CAS 语义改写关系状态,并在**同一临界区内**执行好友上限判定(接受路径的原子收口点)。 @@ -90,13 +86,11 @@ public interface IOnlineFriendStore /// 其余情形的 CAS 语义与 完全一致。 /// /// - /// 租户标识。 - /// App 标识。 /// 状态迁移载荷(关系定位 + 期望/目标状态 + 变更时刻与答复标记)。 /// 已建立好友数上限(<= 0 表示不启用上限判定)。 /// 取消令牌。 /// 迁移结果:成功携带更新后的副本;上限拒绝置 FriendLimitReached;CAS 失败两者皆空。 - Task UpdateStateWithFriendLimitAsync(long tenantId, long appId, FriendshipStateTransition transition, int establishedFriendLimit, CancellationToken cancellationToken = default); + Task UpdateStateWithFriendLimitAsync(FriendshipStateTransition transition, int establishedFriendLimit, CancellationToken cancellationToken = default); /// /// 以 CAS 语义把静止态关系重新发起为待答复请求(「删除后可重新添加」)。 @@ -106,30 +100,24 @@ public interface IOnlineFriendStore /// 有效期也必须重置。三项须在同一临界区内落到同一条记录,故不拆成「改状态 + 再改方向」两次写入。 /// /// - /// 租户标识。 - /// App 标识。 /// 重新发起载荷(关系定位 + 期望状态 + 发起人/被请求方 + 变更时刻与失效时刻)。 /// 取消令牌。 /// 更新后的关系副本;CAS 失败或记录不存在返回 null。 - Task RenewRequestAsync(long tenantId, long appId, FriendshipRenewal renewal, CancellationToken cancellationToken = default); + Task RenewRequestAsync(FriendshipRenewal renewal, CancellationToken cancellationToken = default); /// /// 列出某玩家的全部关系记录(任意状态;好友列表与待答复请求列表的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 关系副本列表。 - Task> ListByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task> ListByPlayerAsync(long playerId, CancellationToken cancellationToken = default); /// /// 列出作用域内处于指定状态的全部关系(超期扫描的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 关系状态。 /// 取消令牌。 /// 关系副本列表。 - Task> ListByStateAsync(long tenantId, long appId, OnlineFriendshipState state, CancellationToken cancellationToken = default); + Task> ListByStateAsync(OnlineFriendshipState state, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/IOnlineGroupStore.cs b/Capability/GameFrameX.Capability.Online.Social/IOnlineGroupStore.cs index 35e722902..e1cde978d 100644 --- a/Capability/GameFrameX.Capability.Online.Social/IOnlineGroupStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/IOnlineGroupStore.cs @@ -58,12 +58,10 @@ public interface IOnlineGroupStore /// /// 按作用域与群组标识查找群记录。 /// - /// 租户标识。 - /// App 标识。 /// 群组标识。 /// 取消令牌。 /// 群记录副本;不存在返回 null。 - Task FindAsync(long tenantId, long appId, string groupId, CancellationToken cancellationToken = default); + Task FindAsync(string groupId, CancellationToken cancellationToken = default); /// /// 以 CAS 语义整体替换群记录(成员、邀请、角色、Metadata 等一切变更的唯一入口)。 @@ -73,7 +71,7 @@ public interface IOnlineGroupStore /// UpdatedAtTime 以入参为准(入参 <= 0 时取当前时刻)。 /// /// - /// 替换后的群记录(其 GroupId/TenantId/AppId 定位目标行;Revision 由存储层推进)。 + /// 替换后的群记录(其 GroupId 定位目标行;Revision 由存储层推进)。 /// 期望的当前版本号(调用方读取快照时的 Revision)。 /// 取消令牌。 /// 落库后的群记录副本;CAS 失败或记录不存在返回 null。 @@ -82,20 +80,16 @@ public interface IOnlineGroupStore /// /// 列出某玩家所属的全部群组(含已解散群组)。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 群记录副本列表。 - Task> ListByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task> ListByPlayerAsync(long playerId, CancellationToken cancellationToken = default); /// /// 列出作用域内处于指定状态的全部群组(超期邀请扫描的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 群组状态。 /// 取消令牌。 /// 群记录副本列表。 - Task> ListByStateAsync(long tenantId, long appId, OnlineGroupState state, CancellationToken cancellationToken = default); + Task> ListByStateAsync(OnlineGroupState state, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/IOnlineNotificationStore.cs b/Capability/GameFrameX.Capability.Online.Social/IOnlineNotificationStore.cs index 1187579ec..21dd010b7 100644 --- a/Capability/GameFrameX.Capability.Online.Social/IOnlineNotificationStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/IOnlineNotificationStore.cs @@ -65,13 +65,11 @@ public interface IOnlineNotificationStore /// /// 按通知标识查找(标识在「作用域 + 接收者」内定位,故查询必须带接收者)。 /// - /// 租户标识。 - /// App 标识。 /// 接收者玩家标识。 /// 通知标识。 /// 取消令牌。 /// 通知副本;不存在返回 null。 - Task FindAsync(long tenantId, long appId, long playerId, string notificationId, CancellationToken cancellationToken = default); + Task FindAsync(long playerId, string notificationId, CancellationToken cancellationToken = default); /// /// 以 CAS 语义整体替换通知记录(推送落定 / 已读 / 过期走此入口)。 @@ -98,20 +96,16 @@ public interface IOnlineNotificationStore /// /// 列出某接收者的全部通知(任意状态;通知列表与离线补发的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 接收者玩家标识。 /// 取消令牌。 /// 通知副本列表。 - Task> ListByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task> ListByPlayerAsync(long playerId, CancellationToken cancellationToken = default); /// /// 列出作用域内处于指定状态的全部通知(超期扫描与重试扫描的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 通知状态。 /// 取消令牌。 /// 通知副本列表。 - Task> ListByStateAsync(long tenantId, long appId, OnlineNotificationState state, CancellationToken cancellationToken = default); + Task> ListByStateAsync(OnlineNotificationState state, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/IOnlineReportStore.cs b/Capability/GameFrameX.Capability.Online.Social/IOnlineReportStore.cs index 580c0369b..a8ec119d8 100644 --- a/Capability/GameFrameX.Capability.Online.Social/IOnlineReportStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/IOnlineReportStore.cs @@ -66,12 +66,10 @@ public interface IOnlineReportStore /// /// 按案件标识查找。 /// - /// 租户标识。 - /// App 标识。 /// 案件标识。 /// 取消令牌。 /// 案件副本;不存在返回 null。 - Task FindAsync(long tenantId, long appId, string reportId, CancellationToken cancellationToken = default); + Task FindAsync(string reportId, CancellationToken cancellationToken = default); /// /// 以 CAS 语义改写案件状态与处置结果;未结案组合索引的维护必须与状态判定在同一临界区完成。 @@ -89,20 +87,16 @@ public interface IOnlineReportStore /// /// 列出某举报人提交的案件(玩家侧「我的举报」入口)。 /// - /// 租户标识。 - /// App 标识。 /// 举报人。 /// 取消令牌。 /// 案件副本列表。 - Task> ListByReporterAsync(long tenantId, long appId, long reporterId, CancellationToken cancellationToken = default); + Task> ListByReporterAsync(long reporterId, CancellationToken cancellationToken = default); /// /// 列出作用域内处于指定状态的案件(Admin 待办队列输入)。 /// - /// 租户标识。 - /// App 标识。 /// 案件状态。 /// 取消令牌。 /// 案件副本列表。 - Task> ListByStateAsync(long tenantId, long appId, OnlineReportState state, CancellationToken cancellationToken = default); + Task> ListByStateAsync(OnlineReportState state, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/IOnlineSocialGraphStore.cs b/Capability/GameFrameX.Capability.Online.Social/IOnlineSocialGraphStore.cs index 1a1ea1248..009cdbf62 100644 --- a/Capability/GameFrameX.Capability.Online.Social/IOnlineSocialGraphStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/IOnlineSocialGraphStore.cs @@ -58,45 +58,37 @@ public interface IOnlineSocialGraphStore /// /// 按方向键查找屏蔽记录。 /// - /// 租户标识。 - /// App 标识。 /// 屏蔽发起人。 /// 被屏蔽玩家。 /// 取消令牌。 /// 屏蔽记录副本;不存在返回 null。 - Task FindBlockAsync(long tenantId, long appId, long ownerId, long blockedPlayerId, CancellationToken cancellationToken = default); + Task FindBlockAsync(long ownerId, long blockedPlayerId, CancellationToken cancellationToken = default); /// /// 解除屏蔽(仅归属玩家本人可解除;解除不存在的记录视为幂等成功)。 /// - /// 租户标识。 - /// App 标识。 /// 屏蔽发起人。 /// 被屏蔽玩家。 /// 取消令牌。 /// 实际删除了记录返回 true;原本不存在返回 false。 - Task RemoveBlockAsync(long tenantId, long appId, long ownerId, long blockedPlayerId, CancellationToken cancellationToken = default); + Task RemoveBlockAsync(long ownerId, long blockedPlayerId, CancellationToken cancellationToken = default); /// /// 判定两名玩家之间**任一方向**是否存在屏蔽(裁决的唯一原子判据)。 /// - /// 租户标识。 - /// App 标识。 /// 一侧玩家标识。 /// 另一侧玩家标识。 /// 取消令牌。 /// 任一方向存在屏蔽返回 true。 - Task IsBlockedEitherWayAsync(long tenantId, long appId, long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default); + Task IsBlockedEitherWayAsync(long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default); /// /// 列出某玩家发起的全部屏蔽(展示与解除界面输入)。 /// - /// 租户标识。 - /// App 标识。 /// 屏蔽发起人。 /// 取消令牌。 /// 屏蔽记录副本列表。 - Task> ListBlocksAsync(long tenantId, long appId, long ownerId, CancellationToken cancellationToken = default); + Task> ListBlocksAsync(long ownerId, CancellationToken cancellationToken = default); /// /// 以(归属玩家,被静音玩家)为唯一键「不存在则创建」静音记录:键已存在时返回既有记录且不写入。 @@ -109,34 +101,28 @@ public interface IOnlineSocialGraphStore /// /// 按方向键查找静音记录。 /// - /// 租户标识。 - /// App 标识。 /// 静音发起人。 /// 被静音玩家。 /// 取消令牌。 /// 静音记录副本;不存在返回 null。 - Task FindMuteAsync(long tenantId, long appId, long ownerId, long mutedPlayerId, CancellationToken cancellationToken = default); + Task FindMuteAsync(long ownerId, long mutedPlayerId, CancellationToken cancellationToken = default); /// /// 解除静音。 /// - /// 租户标识。 - /// App 标识。 /// 静音发起人。 /// 被静音玩家。 /// 取消令牌。 /// 实际删除了记录返回 true;原本不存在返回 false。 - Task RemoveMuteAsync(long tenantId, long appId, long ownerId, long mutedPlayerId, CancellationToken cancellationToken = default); + Task RemoveMuteAsync(long ownerId, long mutedPlayerId, CancellationToken cancellationToken = default); /// /// 列出某玩家发起的全部静音。 /// - /// 租户标识。 - /// App 标识。 /// 静音发起人。 /// 取消令牌。 /// 静音记录副本列表。 - Task> ListMutesAsync(long tenantId, long appId, long ownerId, CancellationToken cancellationToken = default); + Task> ListMutesAsync(long ownerId, CancellationToken cancellationToken = default); /// /// 以处罚标识为唯一键「不存在则创建」处罚记录。 @@ -161,12 +147,10 @@ public interface IOnlineSocialGraphStore /// /// 按处罚标识查找。 /// - /// 租户标识。 - /// App 标识。 /// 处罚标识。 /// 取消令牌。 /// 处罚副本;不存在返回 null。 - Task FindPunishmentAsync(long tenantId, long appId, string punishmentId, CancellationToken cancellationToken = default); + Task FindPunishmentAsync(string punishmentId, CancellationToken cancellationToken = default); /// /// 以 CAS 语义整体替换处罚记录(施加后的补写与撤销都走此入口)。 @@ -180,20 +164,16 @@ public interface IOnlineSocialGraphStore /// /// 列出某玩家在给定时刻**确实生效**的全部处罚(裁决服务的唯一处罚输入)。 /// - /// 租户标识。 - /// App 标识。 /// 生效处罚查询载荷(玩家定位 + 判定时刻;预留过滤维度扩展位)。 /// 取消令牌。 /// 生效中的处罚副本列表(已撤销、未到生效时刻、已失效的均不返回)。 - Task> ListActivePunishmentsAsync(long tenantId, long appId, ActivePunishmentQuery query, CancellationToken cancellationToken = default); + Task> ListActivePunishmentsAsync(ActivePunishmentQuery query, CancellationToken cancellationToken = default); /// /// 列出某玩家的全部处罚记录(含已撤销与已失效;Admin 复查与玩家申诉的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 被处罚玩家。 /// 取消令牌。 /// 处罚副本列表。 - Task> ListPunishmentsByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default); + Task> ListPunishmentsByPlayerAsync(long playerId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineChatStore.cs b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineChatStore.cs index 88b4531f1..be8097de1 100644 --- a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineChatStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineChatStore.cs @@ -88,7 +88,7 @@ public Task SaveChannelIfAbsentAsync(OnlineChatChannel channe throw new ArgumentNullException(nameof(channel)); } - var key = BuildChannelKey(channel.TenantId, channel.AppId, channel.ChannelId); + var key = BuildChannelKey(channel.ChannelId); lock (_syncRoot) { OnlineChatChannel existing; @@ -110,14 +110,12 @@ public Task SaveChannelIfAbsentAsync(OnlineChatChannel channe /// /// Looks up a record in the in-memory channel table by scope and channel id, returning a copy. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 频道标识 / Channel id /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 频道记录副本;不存在返回 null / Copy of the channel record; null if absent - public Task FindChannelAsync(long tenantId, long appId, string channelId, CancellationToken cancellationToken = default) + public Task FindChannelAsync(string channelId, CancellationToken cancellationToken = default) { - var key = BuildChannelKey(tenantId, appId, channelId); + var key = BuildChannelKey(channelId); lock (_syncRoot) { OnlineChatChannel found; @@ -148,7 +146,7 @@ public Task AppendAsync(OnlineChatMessage message, Cancellati throw new ArgumentNullException(nameof(message)); } - var channelKey = BuildChannelKey(message.TenantId, message.AppId, message.ChannelId); + var channelKey = BuildChannelKey(message.ChannelId); var messageKey = channelKey + ":" + (message.MessageId ?? string.Empty); lock (_syncRoot) { @@ -209,20 +207,18 @@ public Task AppendAsync(OnlineChatMessage message, Cancellati /// /// Resolves a message through the in-memory dedupe index by sender dedupe key; returns null immediately when the dedupe key is empty. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 频道标识 / Channel id /// 发送方去重键 / Sender dedupe key /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 命中的消息副本;无去重键或未命中返回 null / Copy of the matched message; null for an empty dedupe key or no match - public Task FindByDedupeKeyAsync(long tenantId, long appId, string channelId, string dedupeKey, CancellationToken cancellationToken = default) + public Task FindByDedupeKeyAsync(string channelId, string dedupeKey, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(dedupeKey)) { return Task.FromResult(null); } - var channelKey = BuildChannelKey(tenantId, appId, channelId); + var channelKey = BuildChannelKey(channelId); lock (_syncRoot) { string messageId; @@ -245,15 +241,13 @@ public Task FindByDedupeKeyAsync(long tenantId, long appId, s /// /// Looks up a record in the in-memory message table by scope, channel and message id, returning a copy. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 频道标识 / Channel id /// 消息标识 / Message id /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 消息副本;不存在返回 null / Copy of the message; null if absent - public Task FindMessageAsync(long tenantId, long appId, string channelId, string messageId, CancellationToken cancellationToken = default) + public Task FindMessageAsync(string channelId, string messageId, CancellationToken cancellationToken = default) { - var key = BuildChannelKey(tenantId, appId, channelId) + ":" + (messageId ?? string.Empty); + var key = BuildChannelKey(channelId) + ":" + (messageId ?? string.Empty); lock (_syncRoot) { OnlineChatMessage found; @@ -272,12 +266,10 @@ public Task FindMessageAsync(long tenantId, long appId, strin /// /// Rewrites the in-memory message state with CAS semantics inside the critical section: leaves no write trace and returns null when the current state mismatches the expected one or the record is absent. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 消息状态 CAS 迁移载荷(频道、消息标识、期望/目标状态、变更时刻、撤回人) / Message state CAS transition payload (channel, message id, expected/target state, change time, recaller) /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 更新后的消息副本;CAS 失败或记录不存在返回 null / Copy of the updated message; null on CAS failure or missing record - public Task UpdateMessageStateAsync(long tenantId, long appId, ChatMessageStateTransition transition, CancellationToken cancellationToken = default) + public Task UpdateMessageStateAsync(ChatMessageStateTransition transition, CancellationToken cancellationToken = default) { var channelId = transition.ChannelId; var messageId = transition.MessageId; @@ -285,7 +277,7 @@ public Task UpdateMessageStateAsync(long tenantId, long appId var newState = transition.NewState; var nowUnixMilliseconds = transition.NowUnixMilliseconds; var recalledByPlayerId = transition.RecalledByPlayerId; - var key = BuildChannelKey(tenantId, appId, channelId) + ":" + (messageId ?? string.Empty); + var key = BuildChannelKey(channelId) + ":" + (messageId ?? string.Empty); lock (_syncRoot) { OnlineChatMessage current; @@ -313,18 +305,16 @@ public Task UpdateMessageStateAsync(long tenantId, long appId /// /// Locates the first entry strictly after the cursor via binary search on the per-channel ordered index inside the critical section, then takes the first limit items in ascending order. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 读取游标载荷(频道、位点发送时刻、位点序号、最多返回条数) / Read cursor payload (channel, cursor sent-at time, cursor sequence, limit) /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 严格位于游标之后、按 (SentAtTime, Sequence) 升序排列的消息副本列表 / Message copies strictly after the cursor, sorted ascending by (SentAtTime, Sequence) - public Task> ReadAfterAsync(long tenantId, long appId, ChatReadCursor cursor, CancellationToken cancellationToken = default) + public Task> ReadAfterAsync(ChatReadCursor cursor, CancellationToken cancellationToken = default) { var channelId = cursor.ChannelId; var afterSentAtTime = cursor.AfterSentAtTime; var afterSequence = cursor.AfterSequence; var limit = cursor.Limit; - var channelKey = BuildChannelKey(tenantId, appId, channelId); + var channelKey = BuildChannelKey(channelId); var pageSize = limit > 0 ? limit : 1; var result = new List(); lock (_syncRoot) @@ -351,18 +341,16 @@ public Task> ReadAfterAsync(long tenantId, long /// /// Counts unread messages after the cursor by binary-searching the per-channel ordered index inside the critical section, excluding those sent by the reader and recalled (non-Normal) ones. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 读取游标载荷(频道与已读位点;Limit 字段不消费) / Read cursor payload (channel and read position; the Limit field is not consumed) /// 读取者(本人发的消息不计未读) / Reader (own messages are not counted as unread) /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 未读条数 / Unread count - public Task CountUnreadAsync(long tenantId, long appId, ChatReadCursor cursor, long readerPlayerId, CancellationToken cancellationToken = default) + public Task CountUnreadAsync(ChatReadCursor cursor, long readerPlayerId, CancellationToken cancellationToken = default) { var channelId = cursor.ChannelId; var afterSentAtTime = cursor.AfterSentAtTime; var afterSequence = cursor.AfterSequence; - var channelKey = BuildChannelKey(tenantId, appId, channelId); + var channelKey = BuildChannelKey(channelId); var count = 0; lock (_syncRoot) { @@ -411,7 +399,7 @@ public Task SaveReadMarkAsync(OnlineChatReadMark readMark, C throw new ArgumentNullException(nameof(readMark)); } - var key = BuildReadMarkKey(readMark.TenantId, readMark.AppId, readMark.PlayerId, readMark.ChannelId); + var key = BuildReadMarkKey(readMark.PlayerId, readMark.ChannelId); lock (_syncRoot) { OnlineChatReadMark existing; @@ -433,15 +421,13 @@ public Task SaveReadMarkAsync(OnlineChatReadMark readMark, C /// /// Looks up the read mark in the in-memory mark table by scope, player and channel id, returning a copy. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 频道标识 / Channel id /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 已读位点副本;从未标记过返回 null / Copy of the read mark; null if never marked - public Task FindReadMarkAsync(long tenantId, long appId, long playerId, string channelId, CancellationToken cancellationToken = default) + public Task FindReadMarkAsync(long playerId, string channelId, CancellationToken cancellationToken = default) { - var key = BuildReadMarkKey(tenantId, appId, playerId, channelId); + var key = BuildReadMarkKey(playerId, channelId); lock (_syncRoot) { OnlineChatReadMark found; @@ -524,25 +510,21 @@ private static int FindFirstIndexAfter(IList keys, long afterSentAt /// /// 构造频道索引键(作用域 + 频道标识)。 /// - /// 租户标识。 - /// App 标识。 /// 频道标识。 /// 索引键。 - private static string BuildChannelKey(long tenantId, long appId, string channelId) + private static string BuildChannelKey(string channelId) { - return "chan:" + tenantId + ":" + appId + ":" + (channelId ?? string.Empty); + return "chan:" + (channelId ?? string.Empty); } /// /// 构造已读位点索引键(作用域 + 玩家 + 频道标识)。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 频道标识。 /// 索引键。 - private static string BuildReadMarkKey(long tenantId, long appId, long playerId, string channelId) + private static string BuildReadMarkKey(long playerId, string channelId) { - return "rmk:" + tenantId + ":" + appId + ":" + playerId + ":" + (channelId ?? string.Empty); + return "rmk:" + playerId + ":" + (channelId ?? string.Empty); } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineFriendStore.cs b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineFriendStore.cs index 4ff7a0008..606282bf6 100644 --- a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineFriendStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineFriendStore.cs @@ -27,6 +27,8 @@ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== +using GameFrameX.Capability.Online.Abstractions.Keys; + namespace GameFrameX.Capability.Online.Social; /// @@ -68,7 +70,7 @@ public Task SaveIfAbsentAsync(OnlineFriendship friendship, Can throw new ArgumentNullException(nameof(friendship)); } - var pairKey = BuildPairKey(friendship.TenantId, friendship.AppId, friendship.LowPlayerId, friendship.HighPlayerId); + var pairKey = OnlineRowKey.Friendship(friendship.LowPlayerId, friendship.HighPlayerId); lock (_syncRoot) { OnlineFriendship existing; @@ -91,18 +93,16 @@ public Task SaveIfAbsentAsync(OnlineFriendship friendship, Can /// /// Canonicalizes the two players into the undirected pair first, then looks up the in-memory friendship table by index key and returns a copy (either direction of the arguments hits the same record). /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 一侧玩家标识(无需预先规范化) / One-side player id (no pre-canonicalization needed) /// 另一侧玩家标识(无需预先规范化) / Other-side player id (no pre-canonicalization needed) /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 关系副本;不存在返回 null / Copy of the friendship; null if absent - public Task FindAsync(long tenantId, long appId, long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default) + public Task FindAsync(long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default) { long low; long high; OnlineFriendship.Canonicalize(leftPlayerId, rightPlayerId, out low, out high); - var pairKey = BuildPairKey(tenantId, appId, low, high); + var pairKey = OnlineRowKey.Friendship(low, high); lock (_syncRoot) { OnlineFriendship found; @@ -121,12 +121,10 @@ public Task FindAsync(long tenantId, long appId, long leftPlay /// /// Rewrites the in-memory friendship state with CAS semantics inside the critical section: leaves no write trace and returns null on scope mismatch, expected-state mismatch or missing record. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 状态迁移载荷(关系定位 + 期望/目标状态 + 变更时刻与答复标记) / State transition payload (friendship locator + expected/target states + change time and responded flag) /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 更新后的关系副本;CAS 失败或记录不存在返回 null / Copy of the updated friendship; null on CAS failure or missing record - public Task UpdateStateAsync(long tenantId, long appId, FriendshipStateTransition transition, CancellationToken cancellationToken = default) + public Task UpdateStateAsync(FriendshipStateTransition transition, CancellationToken cancellationToken = default) { var friendshipId = transition.FriendshipId; var expectedState = transition.ExpectedState; @@ -148,11 +146,6 @@ public Task UpdateStateAsync(long tenantId, long appId, Friend return Task.FromResult(null); } - if (current.TenantId != tenantId || current.AppId != appId) - { - return Task.FromResult(null); - } - if (current.State != expectedState) { // CAS 失败:不留任何写入痕迹,调用方据 null 判定「状态已被并发改写」。 @@ -177,14 +170,12 @@ public Task UpdateStateAsync(long tenantId, long appId, Friend /// /// Performs "read both sides' established counts → judge the limit → write" within one critical section: rejects with zero writes when either side has reached the limit, eliminating the TOCTOU window where concurrent accepts each read limit-1 and both land over the limit. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 状态迁移载荷(关系定位 + 期望/目标状态 + 变更时刻与答复标记) / State transition payload (friendship locator + expected/target states + change time and responded flag) /// 已建立好友数上限(<= 0 表示不启用上限判定) / Established friend limit (<= 0 disables the limit check) /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 迁移结果:成功携带更新后的副本;上限拒绝置 FriendLimitReached;CAS 失败两者皆空 / Transition outcome: updated copy on success; FriendLimitReached on limit rejection; both empty on CAS failure /// 当 为 null 时抛出 / Thrown when is null - public Task UpdateStateWithFriendLimitAsync(long tenantId, long appId, FriendshipStateTransition transition, int establishedFriendLimit, CancellationToken cancellationToken = default) + public Task UpdateStateWithFriendLimitAsync(FriendshipStateTransition transition, int establishedFriendLimit, CancellationToken cancellationToken = default) { if (transition == null) { @@ -208,7 +199,7 @@ public Task UpdateStateWithFriendLimitAsync( return Task.FromResult(OnlineFriendStateTransitionOutcome.FromCasConflict()); } - if (current.TenantId != tenantId || current.AppId != appId || current.State != expectedState) + if (current.State != expectedState) { return Task.FromResult(OnlineFriendStateTransitionOutcome.FromCasConflict()); } @@ -216,8 +207,8 @@ public Task UpdateStateWithFriendLimitAsync( if (newState == OnlineFriendshipState.Accepted && establishedFriendLimit > 0) { // 计数与写入同一临界区:本条此刻尚处 Requested(未计入),两侧任一满员即整体拒绝、零写入。 - if (CountEstablishedInLock(tenantId, appId, current.RequesterId) >= establishedFriendLimit - || CountEstablishedInLock(tenantId, appId, current.AddresseeId) >= establishedFriendLimit) + if (CountEstablishedInLock(current.RequesterId) >= establishedFriendLimit + || CountEstablishedInLock(current.AddresseeId) >= establishedFriendLimit) { return Task.FromResult(OnlineFriendStateTransitionOutcome.FromFriendLimitReached()); } @@ -240,12 +231,10 @@ public Task UpdateStateWithFriendLimitAsync( /// /// Re-initiates a quiescent friendship as a pending request with CAS semantics, writing state, direction and expiry together onto the same record within one critical section. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 重新发起载荷(关系标识、期望状态、发起人、被请求方、变更时刻、失效时刻) / Renewal payload (friendship id, expected state, requester, addressee, change time, expiry) /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 更新后的关系副本;CAS 失败或记录不存在返回 null / Copy of the updated friendship; null on CAS failure or missing record - public Task RenewRequestAsync(long tenantId, long appId, FriendshipRenewal renewal, CancellationToken cancellationToken = default) + public Task RenewRequestAsync(FriendshipRenewal renewal, CancellationToken cancellationToken = default) { var friendshipId = renewal.FriendshipId; var expectedState = renewal.ExpectedState; @@ -268,7 +257,7 @@ public Task RenewRequestAsync(long tenantId, long appId, Frien return Task.FromResult(null); } - if (current.TenantId != tenantId || current.AppId != appId || current.State != expectedState) + if (current.State != expectedState) { return Task.FromResult(null); } @@ -285,18 +274,15 @@ public Task RenewRequestAsync(long tenantId, long appId, Frien /// /// 在已持有 临界区的前提下,全表扫描统计某玩家已建立(Accepted)的关系数。 /// - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 已建立的关系数。 - private int CountEstablishedInLock(long tenantId, long appId, long playerId) + private int CountEstablishedInLock(long playerId) { var count = 0; foreach (var pair in _friendshipsByPair) { var friendship = pair.Value; - if (friendship.TenantId == tenantId && friendship.AppId == appId - && friendship.State == OnlineFriendshipState.Accepted + if (friendship.State == OnlineFriendshipState.Accepted && friendship.Contains(playerId)) { count++; @@ -312,12 +298,10 @@ private int CountEstablishedInLock(long tenantId, long appId, long playerId) /// /// Lists all friendship records in the scope containing the given player (any state) via a full-table linear scan inside the critical section. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 关系副本列表 / List of friendship copies - public Task> ListByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -325,11 +309,6 @@ public Task> ListByPlayerAsync(long tenantId, lo foreach (var pair in _friendshipsByPair) { var friendship = pair.Value; - if (friendship.TenantId != tenantId || friendship.AppId != appId) - { - continue; - } - if (friendship.Contains(playerId)) { result.Add(friendship.Copy()); @@ -346,12 +325,10 @@ public Task> ListByPlayerAsync(long tenantId, lo /// /// Lists all friendship records in the scope with the given state via a full-table linear scan inside the critical section. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 关系状态 / Friendship state /// 取消令牌(同步内存实现,忽略此参数) / Cancellation token (ignored by this synchronous in-memory implementation) /// 关系副本列表 / List of friendship copies - public Task> ListByStateAsync(long tenantId, long appId, OnlineFriendshipState state, CancellationToken cancellationToken = default) + public Task> ListByStateAsync(OnlineFriendshipState state, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -359,7 +336,7 @@ public Task> ListByStateAsync(long tenantId, lon foreach (var pair in _friendshipsByPair) { var friendship = pair.Value; - if (friendship.TenantId == tenantId && friendship.AppId == appId && friendship.State == state) + if (friendship.State == state) { result.Add(friendship.Copy()); } @@ -369,16 +346,5 @@ public Task> ListByStateAsync(long tenantId, lon return Task.FromResult>(result); } - /// - /// 构造无向对索引键(作用域 + 规范化玩家对)。 - /// - /// 租户标识。 - /// App 标识。 - /// 低标识侧玩家。 - /// 高标识侧玩家。 - /// 索引键。 - private static string BuildPairKey(long tenantId, long appId, long lowPlayerId, long highPlayerId) - { - return "friend:" + tenantId + ":" + appId + ":" + lowPlayerId + ":" + highPlayerId; - } + } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineGroupStore.cs b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineGroupStore.cs index e6eb89942..32ff477ad 100644 --- a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineGroupStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineGroupStore.cs @@ -67,7 +67,7 @@ public Task SaveIfAbsentAsync(OnlineGroup group, CancellationToken throw new ArgumentNullException(nameof(group)); } - var key = BuildKey(group.TenantId, group.AppId, group.GroupId); + var key = BuildKey(group.GroupId); lock (_syncRoot) { OnlineGroup existing; @@ -88,14 +88,12 @@ public Task SaveIfAbsentAsync(OnlineGroup group, CancellationToken /// /// Finds a group record in the in-memory table by scope and group id. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 群组标识 / Group id /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 群记录副本;不存在返回 null / Copy of the group record, or null if absent - public Task FindAsync(long tenantId, long appId, string groupId, CancellationToken cancellationToken = default) + public Task FindAsync(string groupId, CancellationToken cancellationToken = default) { - var key = BuildKey(tenantId, appId, groupId); + var key = BuildKey(groupId); lock (_syncRoot) { OnlineGroup found; @@ -116,7 +114,7 @@ public Task FindAsync(long tenantId, long appId, string groupId, Ca /// when the revision matches, bumping it by one; a mismatching revision or a missing /// record fails as a whole, leaving no trace. /// - /// 替换后的群记录(其 GroupId/TenantId/AppId 定位目标行)/ The replacement group record (its GroupId/TenantId/AppId locate the target row) + /// 替换后的群记录(其 GroupId 定位目标行)/ The replacement group record (its GroupId locates the target row) /// 期望的当前版本号 / The expected current revision /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 落库后的群记录副本;CAS 失败或记录不存在返回 null / Copy of the stored group record, or null on CAS failure or missing record @@ -128,7 +126,7 @@ public Task ReplaceAsync(OnlineGroup group, int expectedRevision, C throw new ArgumentNullException(nameof(group)); } - var key = BuildKey(group.TenantId, group.AppId, group.GroupId); + var key = BuildKey(group.GroupId); lock (_syncRoot) { OnlineGroup current; @@ -157,12 +155,10 @@ public Task ReplaceAsync(OnlineGroup group, int expectedRevision, C /// /// Linearly scans the whole table to list all groups the player belongs to, including dissolved ones. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 群记录副本列表 / List of group record copies - public Task> ListByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -170,11 +166,6 @@ public Task> ListByPlayerAsync(long tenantId, long ap foreach (var pair in _groupsById) { var group = pair.Value; - if (group.TenantId != tenantId || group.AppId != appId) - { - continue; - } - if (group.Contains(playerId)) { result.Add(group.Copy()); @@ -191,12 +182,10 @@ public Task> ListByPlayerAsync(long tenantId, long ap /// /// Linearly scans the whole table to list all groups in the scope with the given state. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 群组状态 / Group state /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 群记录副本列表 / List of group record copies - public Task> ListByStateAsync(long tenantId, long appId, OnlineGroupState state, CancellationToken cancellationToken = default) + public Task> ListByStateAsync(OnlineGroupState state, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -204,7 +193,7 @@ public Task> ListByStateAsync(long tenantId, long app foreach (var pair in _groupsById) { var group = pair.Value; - if (group.TenantId == tenantId && group.AppId == appId && group.State == state) + if (group.State == state) { result.Add(group.Copy()); } @@ -217,13 +206,11 @@ public Task> ListByStateAsync(long tenantId, long app /// /// 构造群组索引键(作用域 + 群组标识)。 /// - /// 租户标识。 - /// App 标识。 /// 群组标识。 /// 索引键。 - private static string BuildKey(long tenantId, long appId, string groupId) + private static string BuildKey(string groupId) { - return "group:" + tenantId + ":" + appId + ":" + (groupId ?? string.Empty); + return "group:" + (groupId ?? string.Empty); } /// 取当前 UTC 毫秒时刻(入参未携带变更时刻时的兜底)。 diff --git a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineNotificationStore.cs b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineNotificationStore.cs index f283fd27e..c6fc58e05 100644 --- a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineNotificationStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineNotificationStore.cs @@ -74,8 +74,8 @@ public Task SaveIfAbsentAsync(OnlineNotification notificatio throw new ArgumentNullException(nameof(notification)); } - var idKey = BuildIdKey(notification.TenantId, notification.AppId, notification.PlayerId, notification.NotificationId); - var dedupeKey = BuildDedupeKey(notification.TenantId, notification.AppId, notification.PlayerId, notification.DedupeKey); + var idKey = BuildIdKey(notification.PlayerId, notification.NotificationId); + var dedupeKey = BuildDedupeKey(notification.PlayerId, notification.DedupeKey); lock (_syncRoot) { string existingIdKey; @@ -103,15 +103,13 @@ public Task SaveIfAbsentAsync(OnlineNotification notificatio /// /// Finds a notification in the in-memory table by scope, recipient and notification id. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 接收者玩家标识 / Recipient player id /// 通知标识 / Notification id /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 通知副本;不存在返回 null / Copy of the notification, or null if absent - public Task FindAsync(long tenantId, long appId, long playerId, string notificationId, CancellationToken cancellationToken = default) + public Task FindAsync(long playerId, string notificationId, CancellationToken cancellationToken = default) { - var idKey = BuildIdKey(tenantId, appId, playerId, notificationId); + var idKey = BuildIdKey(playerId, notificationId); lock (_syncRoot) { OnlineNotification found; @@ -144,7 +142,7 @@ public Task ReplaceAsync(OnlineNotification notification, On throw new ArgumentNullException(nameof(notification)); } - var idKey = BuildIdKey(notification.TenantId, notification.AppId, notification.PlayerId, notification.NotificationId); + var idKey = BuildIdKey(notification.PlayerId, notification.NotificationId); lock (_syncRoot) { OnlineNotification current; @@ -172,12 +170,10 @@ public Task ReplaceAsync(OnlineNotification notification, On /// /// Linearly scans the whole table to list all notifications of a recipient in any state. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 接收者玩家标识 / Recipient player id /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 通知副本列表 / List of notification copies - public Task> ListByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -185,7 +181,7 @@ public Task> ListByPlayerAsync(long tenantId, foreach (var pair in _notificationsByIdKey) { var notification = pair.Value; - if (notification.TenantId == tenantId && notification.AppId == appId && notification.PlayerId == playerId) + if (notification.PlayerId == playerId) { result.Add(notification.Copy()); } @@ -201,12 +197,10 @@ public Task> ListByPlayerAsync(long tenantId, /// /// Linearly scans the whole table to list all notifications in the scope with the given state. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 通知状态 / Notification state /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 通知副本列表 / List of notification copies - public Task> ListByStateAsync(long tenantId, long appId, OnlineNotificationState state, CancellationToken cancellationToken = default) + public Task> ListByStateAsync(OnlineNotificationState state, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -214,7 +208,7 @@ public Task> ListByStateAsync(long tenantId, l foreach (var pair in _notificationsByIdKey) { var notification = pair.Value; - if (notification.TenantId == tenantId && notification.AppId == appId && notification.State == state) + if (notification.State == state) { result.Add(notification.Copy()); } @@ -227,14 +221,12 @@ public Task> ListByStateAsync(long tenantId, l /// /// 构造通知标识索引键(作用域 + 接收者 + 通知标识)。 /// - /// 租户标识。 - /// App 标识。 /// 接收者玩家标识。 /// 通知标识。 /// 索引键。 - private static string BuildIdKey(long tenantId, long appId, long playerId, string notificationId) + private static string BuildIdKey(long playerId, string notificationId) { - return "ntf:" + tenantId + ":" + appId + ":" + playerId + ":" + (notificationId ?? string.Empty); + return "ntf:" + playerId + ":" + (notificationId ?? string.Empty); } /// @@ -244,13 +236,11 @@ private static string BuildIdKey(long tenantId, long appId, long playerId, strin /// 去重只约束「同一接收者的同一业务动作」。 /// /// - /// 租户标识。 - /// App 标识。 /// 接收者玩家标识。 /// 去重键。 /// 索引键。 - private static string BuildDedupeKey(long tenantId, long appId, long playerId, string dedupeKey) + private static string BuildDedupeKey(long playerId, string dedupeKey) { - return "ntfd:" + tenantId + ":" + appId + ":" + playerId + ":" + (dedupeKey ?? string.Empty); + return "ntfd:" + playerId + ":" + (dedupeKey ?? string.Empty); } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineReportStore.cs b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineReportStore.cs index 9a84cbb05..132f867d6 100644 --- a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineReportStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineReportStore.cs @@ -71,7 +71,7 @@ public Task SaveIfAbsentAsync(OnlineReportCase reportCase, Can throw new ArgumentNullException(nameof(reportCase)); } - var key = BuildKey(reportCase.TenantId, reportCase.AppId, reportCase.ReportId); + var key = BuildKey(reportCase.ReportId); lock (_syncRoot) { // 第一层:按案件标识重放(客户端带服务端已返回标识的重试收敛到同一条)。 @@ -83,12 +83,12 @@ public Task SaveIfAbsentAsync(OnlineReportCase reportCase, Can // 第二层:未结案组合唯一性——同一举报人对同一被举报人在同一场景下的 // Submitted/Reviewing 案件只能有一条;重复提交返回既有案件,不落新案。 - var combinationKey = BuildActiveCombinationKey(reportCase.TenantId, reportCase.AppId, reportCase.ReporterId, reportCase.ReportedPlayerId, reportCase.Scene); + var combinationKey = BuildActiveCombinationKey(reportCase.ReporterId, reportCase.ReportedPlayerId, reportCase.Scene); string activeCaseId; if (_activeCaseIdByCombination.TryGetValue(combinationKey, out activeCaseId)) { OnlineReportCase active; - if (_casesById.TryGetValue(BuildKey(reportCase.TenantId, reportCase.AppId, activeCaseId), out active)) + if (_casesById.TryGetValue(BuildKey(activeCaseId), out active)) { return Task.FromResult(active.Copy()); } @@ -108,14 +108,12 @@ public Task SaveIfAbsentAsync(OnlineReportCase reportCase, Can /// /// Finds a report case in the in-memory table by scope and case id. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 案件标识 / Case id /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 案件副本;不存在返回 null / Copy of the report case, or null if absent - public Task FindAsync(long tenantId, long appId, string reportId, CancellationToken cancellationToken = default) + public Task FindAsync(string reportId, CancellationToken cancellationToken = default) { - var key = BuildKey(tenantId, appId, reportId); + var key = BuildKey(reportId); lock (_syncRoot) { OnlineReportCase found; @@ -147,7 +145,7 @@ public Task ReplaceAsync(OnlineReportCase reportCase, OnlineRe throw new ArgumentNullException(nameof(reportCase)); } - var key = BuildKey(reportCase.TenantId, reportCase.AppId, reportCase.ReportId); + var key = BuildKey(reportCase.ReportId); lock (_syncRoot) { OnlineReportCase current; @@ -174,7 +172,7 @@ public Task ReplaceAsync(OnlineReportCase reportCase, OnlineRe // 组合索引与 CAS 同一临界区维护:进入终态释放占位(终态后可就同一组合新建案件); // 仅当该索引仍指向本案件时才允许改写——旧终态更新不得释放已归属后续新案的占位。 - var combinationKey = BuildActiveCombinationKey(stored.TenantId, stored.AppId, stored.ReporterId, stored.ReportedPlayerId, stored.Scene); + var combinationKey = BuildActiveCombinationKey(stored.ReporterId, stored.ReportedPlayerId, stored.Scene); string indexedCaseId; if (_activeCaseIdByCombination.TryGetValue(combinationKey, out indexedCaseId) && string.Equals(indexedCaseId, stored.ReportId, StringComparison.Ordinal)) { @@ -194,12 +192,10 @@ public Task ReplaceAsync(OnlineReportCase reportCase, OnlineRe /// /// Linearly scans the whole table to list all cases submitted by a reporter. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 举报人标识 / Reporter id /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 案件副本列表 / List of report case copies - public Task> ListByReporterAsync(long tenantId, long appId, long reporterId, CancellationToken cancellationToken = default) + public Task> ListByReporterAsync(long reporterId, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -207,7 +203,7 @@ public Task> ListByReporterAsync(long tenantId, foreach (var pair in _casesById) { var reportCase = pair.Value; - if (reportCase.TenantId == tenantId && reportCase.AppId == appId && reportCase.ReporterId == reporterId) + if (reportCase.ReporterId == reporterId) { result.Add(reportCase.Copy()); } @@ -223,12 +219,10 @@ public Task> ListByReporterAsync(long tenantId, /// /// Linearly scans the whole table to list cases in the scope with the given state (input for the admin pending queue). /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 案件状态 / Case state /// 取消令牌(本实现同步完成,不消费该令牌)/ Cancellation token (unused; this implementation completes synchronously) /// 案件副本列表 / List of report case copies - public Task> ListByStateAsync(long tenantId, long appId, OnlineReportState state, CancellationToken cancellationToken = default) + public Task> ListByStateAsync(OnlineReportState state, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -236,7 +230,7 @@ public Task> ListByStateAsync(long tenantId, lon foreach (var pair in _casesById) { var reportCase = pair.Value; - if (reportCase.TenantId == tenantId && reportCase.AppId == appId && reportCase.State == state) + if (reportCase.State == state) { result.Add(reportCase.Copy()); } @@ -249,27 +243,23 @@ public Task> ListByStateAsync(long tenantId, lon /// /// 构造案件索引键(作用域 + 案件标识)。 /// - /// 租户标识。 - /// App 标识。 /// 案件标识。 /// 索引键。 - private static string BuildKey(long tenantId, long appId, string reportId) + private static string BuildKey(string reportId) { - return "rpt:" + tenantId + ":" + appId + ":" + (reportId ?? string.Empty); + return "rpt:" + (reportId ?? string.Empty); } /// /// 构造未结案组合唯一键(作用域 + 举报人 + 被举报人 + 场景)。 /// - /// 租户标识。 - /// App 标识。 /// 举报人。 /// 被举报人。 /// 举报场景。 /// 组合唯一键。 - private static string BuildActiveCombinationKey(long tenantId, long appId, long reporterId, long reportedPlayerId, OnlineReportScene scene) + private static string BuildActiveCombinationKey(long reporterId, long reportedPlayerId, OnlineReportScene scene) { - return "rpt-active:" + tenantId + ":" + appId + ":" + reporterId + ":" + reportedPlayerId + ":" + (int)scene; + return "rpt-active:" + reporterId + ":" + reportedPlayerId + ":" + (int)scene; } /// diff --git a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineSocialGraphStore.cs b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineSocialGraphStore.cs index 486198210..a797f4c1d 100644 --- a/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineSocialGraphStore.cs +++ b/Capability/GameFrameX.Capability.Online.Social/InMemoryOnlineSocialGraphStore.cs @@ -72,7 +72,7 @@ public Task SaveBlockIfAbsentAsync(OnlineBlockEntry entry, Can throw new ArgumentNullException(nameof(entry)); } - var key = BuildDirectionKey("blk", entry.TenantId, entry.AppId, entry.OwnerId, entry.BlockedPlayerId); + var key = BuildDirectionKey("blk", entry.OwnerId, entry.BlockedPlayerId); lock (_syncRoot) { OnlineBlockEntry existing; @@ -94,15 +94,13 @@ public Task SaveBlockIfAbsentAsync(OnlineBlockEntry entry, Can /// /// Looks up the block record by direction key in the in-memory block table; returns a defensive copy on hit and null on miss. /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 屏蔽发起人 / Block owner /// 被屏蔽玩家 / Blocked player /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 屏蔽记录副本;不存在返回 null / Copy of the block entry; null when absent - public Task FindBlockAsync(long tenantId, long appId, long ownerId, long blockedPlayerId, CancellationToken cancellationToken = default) + public Task FindBlockAsync(long ownerId, long blockedPlayerId, CancellationToken cancellationToken = default) { - var key = BuildDirectionKey("blk", tenantId, appId, ownerId, blockedPlayerId); + var key = BuildDirectionKey("blk", ownerId, blockedPlayerId); lock (_syncRoot) { OnlineBlockEntry found; @@ -121,15 +119,13 @@ public Task FindBlockAsync(long tenantId, long appId, long own /// /// Removes the block record by direction key from the in-memory block table and reports whether a record was actually deleted; a missing record is not an error (idempotent). /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 屏蔽发起人 / Block owner /// 被屏蔽玩家 / Blocked player /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 实际删除了记录返回 true;原本不存在返回 false / true if a record was actually removed; false if it did not exist - public Task RemoveBlockAsync(long tenantId, long appId, long ownerId, long blockedPlayerId, CancellationToken cancellationToken = default) + public Task RemoveBlockAsync(long ownerId, long blockedPlayerId, CancellationToken cancellationToken = default) { - var key = BuildDirectionKey("blk", tenantId, appId, ownerId, blockedPlayerId); + var key = BuildDirectionKey("blk", ownerId, blockedPlayerId); lock (_syncRoot) { return Task.FromResult(_blocksByDirection.Remove(key)); @@ -142,16 +138,14 @@ public Task RemoveBlockAsync(long tenantId, long appId, long ownerId, long /// /// Checks both direction keys of the in-memory block table inside a single critical section to decide whether either player has blocked the other (the sole atomic criterion for adjudication). /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 一侧玩家标识 / One player of the pair /// 另一侧玩家标识 / The other player of the pair /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 任一方向存在屏蔽返回 true / true if a block exists in either direction - public Task IsBlockedEitherWayAsync(long tenantId, long appId, long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default) + public Task IsBlockedEitherWayAsync(long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default) { - var forwardKey = BuildDirectionKey("blk", tenantId, appId, leftPlayerId, rightPlayerId); - var backwardKey = BuildDirectionKey("blk", tenantId, appId, rightPlayerId, leftPlayerId); + var forwardKey = BuildDirectionKey("blk", leftPlayerId, rightPlayerId); + var backwardKey = BuildDirectionKey("blk", rightPlayerId, leftPlayerId); lock (_syncRoot) { // 两个方向必须同临界区判定:拆开会让并发屏蔽挤进两次查询之间,产生放行窗口。 @@ -165,12 +159,10 @@ public Task IsBlockedEitherWayAsync(long tenantId, long appId, long leftPl /// /// Linearly scans the whole in-memory block table to list every block initiated by the given owner and returns a list of defensive copies. /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 屏蔽发起人 / Block owner /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 屏蔽记录副本列表(无记录时为空列表) / List of block entry copies (empty when none) - public Task> ListBlocksAsync(long tenantId, long appId, long ownerId, CancellationToken cancellationToken = default) + public Task> ListBlocksAsync(long ownerId, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -178,7 +170,7 @@ public Task> ListBlocksAsync(long tenantId, long foreach (var pair in _blocksByDirection) { var entry = pair.Value; - if (entry.TenantId == tenantId && entry.AppId == appId && entry.OwnerId == ownerId) + if (entry.OwnerId == ownerId) { result.Add(entry.Copy()); } @@ -205,7 +197,7 @@ public Task SaveMuteIfAbsentAsync(OnlineMuteEntry entry, Cancel throw new ArgumentNullException(nameof(entry)); } - var key = BuildDirectionKey("mut", entry.TenantId, entry.AppId, entry.OwnerId, entry.MutedPlayerId); + var key = BuildDirectionKey("mut", entry.OwnerId, entry.MutedPlayerId); lock (_syncRoot) { OnlineMuteEntry existing; @@ -227,15 +219,13 @@ public Task SaveMuteIfAbsentAsync(OnlineMuteEntry entry, Cancel /// /// Looks up the mute record by direction key in the in-memory mute table; returns a defensive copy on hit and null on miss. /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 静音发起人 / Mute owner /// 被静音玩家 / Muted player /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 静音记录副本;不存在返回 null / Copy of the mute entry; null when absent - public Task FindMuteAsync(long tenantId, long appId, long ownerId, long mutedPlayerId, CancellationToken cancellationToken = default) + public Task FindMuteAsync(long ownerId, long mutedPlayerId, CancellationToken cancellationToken = default) { - var key = BuildDirectionKey("mut", tenantId, appId, ownerId, mutedPlayerId); + var key = BuildDirectionKey("mut", ownerId, mutedPlayerId); lock (_syncRoot) { OnlineMuteEntry found; @@ -254,15 +244,13 @@ public Task FindMuteAsync(long tenantId, long appId, long owner /// /// Removes the mute record by direction key from the in-memory mute table and reports whether a record was actually deleted; a missing record is not an error (idempotent). /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 静音发起人 / Mute owner /// 被静音玩家 / Muted player /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 实际删除了记录返回 true;原本不存在返回 false / true if a record was actually removed; false if it did not exist - public Task RemoveMuteAsync(long tenantId, long appId, long ownerId, long mutedPlayerId, CancellationToken cancellationToken = default) + public Task RemoveMuteAsync(long ownerId, long mutedPlayerId, CancellationToken cancellationToken = default) { - var key = BuildDirectionKey("mut", tenantId, appId, ownerId, mutedPlayerId); + var key = BuildDirectionKey("mut", ownerId, mutedPlayerId); lock (_syncRoot) { return Task.FromResult(_mutesByDirection.Remove(key)); @@ -275,12 +263,10 @@ public Task RemoveMuteAsync(long tenantId, long appId, long ownerId, long /// /// Linearly scans the whole in-memory mute table to list every mute initiated by the given owner and returns a list of defensive copies. /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 静音发起人 / Mute owner /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 静音记录副本列表(无记录时为空列表) / List of mute entry copies (empty when none) - public Task> ListMutesAsync(long tenantId, long appId, long ownerId, CancellationToken cancellationToken = default) + public Task> ListMutesAsync(long ownerId, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -288,7 +274,7 @@ public Task> ListMutesAsync(long tenantId, long a foreach (var pair in _mutesByDirection) { var entry = pair.Value; - if (entry.TenantId == tenantId && entry.AppId == appId && entry.OwnerId == ownerId) + if (entry.OwnerId == ownerId) { result.Add(entry.Copy()); } @@ -315,7 +301,7 @@ public Task SavePunishmentIfAbsentAsync(OnlinePunishment punis throw new ArgumentNullException(nameof(punishment)); } - var key = BuildPunishmentKey(punishment.TenantId, punishment.AppId, punishment.PunishmentId); + var key = BuildPunishmentKey(punishment.PunishmentId); lock (_syncRoot) { OnlinePunishment existing; @@ -337,14 +323,12 @@ public Task SavePunishmentIfAbsentAsync(OnlinePunishment punis /// /// Looks up the punishment by (scope, punishment identifier) key in the in-memory punishment table; returns a defensive copy on hit and null on miss. /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 处罚标识 / Punishment identifier /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 处罚副本;不存在返回 null / Copy of the punishment; null when absent - public Task FindPunishmentAsync(long tenantId, long appId, string punishmentId, CancellationToken cancellationToken = default) + public Task FindPunishmentAsync(string punishmentId, CancellationToken cancellationToken = default) { - var key = BuildPunishmentKey(tenantId, appId, punishmentId); + var key = BuildPunishmentKey(punishmentId); lock (_syncRoot) { OnlinePunishment found; @@ -375,7 +359,7 @@ public Task ReplacePunishmentAsync(OnlinePunishment punishment throw new ArgumentNullException(nameof(punishment)); } - var key = BuildPunishmentKey(punishment.TenantId, punishment.AppId, punishment.PunishmentId); + var key = BuildPunishmentKey(punishment.PunishmentId); lock (_syncRoot) { OnlinePunishment current; @@ -404,12 +388,10 @@ public Task ReplacePunishmentAsync(OnlinePunishment punishment /// /// Linearly scans the whole in-memory punishment table inside a single critical section, filters the player's punishments that are genuinely in effect at the given moment (not revoked, already effective, not yet expired), and returns a list of defensive copies. /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 生效处罚查询载荷(玩家标识与判定时刻) / Active punishment query payload (player id and judgment moment) /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 生效中的处罚副本列表(已撤销、未到生效时刻、已失效的均不返回) / List of copies of the punishments in effect (revoked, not-yet-effective, and expired ones are excluded) - public Task> ListActivePunishmentsAsync(long tenantId, long appId, ActivePunishmentQuery query, CancellationToken cancellationToken = default) + public Task> ListActivePunishmentsAsync(ActivePunishmentQuery query, CancellationToken cancellationToken = default) { var playerId = query.PlayerId; var nowUnixMilliseconds = query.NowUnixMilliseconds; @@ -420,7 +402,7 @@ public Task> ListActivePunishmentsAsync(long ten foreach (var pair in _punishmentsById) { var punishment = pair.Value; - if (punishment.TenantId != tenantId || punishment.AppId != appId || punishment.PlayerId != playerId) + if (punishment.PlayerId != playerId) { continue; } @@ -441,12 +423,10 @@ public Task> ListActivePunishmentsAsync(long ten /// /// Linearly scans the whole in-memory punishment table to list every punishment of the given player (including revoked and expired ones) and returns a list of defensive copies. /// - /// 租户标识 / Tenant identifier - /// App 标识 / App identifier /// 被处罚玩家 / Punished player /// 取消令牌(同步内存实现不使用) / Cancellation token (unused by the synchronous in-memory implementation) /// 处罚副本列表(无记录时为空列表) / List of punishment copies (empty when none) - public Task> ListPunishmentsByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListPunishmentsByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { var result = new List(); lock (_syncRoot) @@ -454,7 +434,7 @@ public Task> ListPunishmentsByPlayerAsync(long t foreach (var pair in _punishmentsById) { var punishment = pair.Value; - if (punishment.TenantId == tenantId && punishment.AppId == appId && punishment.PlayerId == playerId) + if (punishment.PlayerId == playerId) { result.Add(punishment.Copy()); } @@ -468,25 +448,21 @@ public Task> ListPunishmentsByPlayerAsync(long t /// 构造方向性记录索引键(作用域 + 归属玩家 + 目标玩家)。 /// /// 记录类别前缀(屏蔽 / 静音)。 - /// 租户标识。 - /// App 标识。 /// 归属玩家。 /// 目标玩家。 /// 索引键。 - private static string BuildDirectionKey(string prefix, long tenantId, long appId, long ownerId, long targetPlayerId) + private static string BuildDirectionKey(string prefix, long ownerId, long targetPlayerId) { - return prefix + ":" + tenantId + ":" + appId + ":" + ownerId + ":" + targetPlayerId; + return prefix + ":" + ownerId + ":" + targetPlayerId; } /// /// 构造处罚索引键(作用域 + 处罚标识)。 /// - /// 租户标识。 - /// App 标识。 /// 处罚标识。 /// 索引键。 - private static string BuildPunishmentKey(long tenantId, long appId, string punishmentId) + private static string BuildPunishmentKey(string punishmentId) { - return "pun:" + tenantId + ":" + appId + ":" + (punishmentId ?? string.Empty); + return "pun:" + (punishmentId ?? string.Empty); } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineBlockEntry.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineBlockEntry.cs index d917b9820..733877bd8 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineBlockEntry.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineBlockEntry.cs @@ -61,15 +61,7 @@ public sealed class OnlineBlockEntry /// public long BlockedPlayerId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置发起屏蔽时所在的区服标识(仅作事件信封与审计记录用; @@ -98,8 +90,6 @@ public OnlineBlockEntry Copy() EntryId = EntryId, OwnerId = OwnerId, BlockedPlayerId = BlockedPlayerId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Reason = Reason, CreatedAtTime = CreatedAtTime, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineChatAuditProjection.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineChatAuditProjection.cs index 42f82d45e..af1c7015a 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineChatAuditProjection.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineChatAuditProjection.cs @@ -107,11 +107,9 @@ public void OnEvent(OnlineEvent onlineEvent) /// /// 查询聊天审计消息(跨频道;新到旧分页)。 /// - /// 租户标识。 - /// App 标识。 /// 检索条件载荷(可选过滤 + 游标 + 页大小)。 /// 查询页(正文与参与者已回读补全)。 - public async Task QueryAsync(long tenantId, long appId, ChatAuditQuery query) + public async Task QueryAsync(ChatAuditQuery query) { if (query == null) { @@ -133,7 +131,7 @@ public async Task QueryAsync(long tenantId, long appId, ChatAudit for (var index = 0; index < ordered.Count; index++) { lastExamined = index; - var item = await TryComposeItemAsync(ordered[index], channelCache, tenantId, appId, channelKind, participantPlayerId, keyword, startTime, endTime).ConfigureAwait(false); + var item = await TryComposeItemAsync(ordered[index], channelCache, channelKind, participantPlayerId, keyword, startTime, endTime).ConfigureAwait(false); if (item != null) { items.Add(item); @@ -203,15 +201,13 @@ private List BuildOrderedSnapshot(string cursor) /// /// 消息引用。 /// 频道回读缓存(跨引用共享)。 - /// 租户标识。 - /// App 标识。 /// 频道类型过滤(null 表示不限)。 /// 参与者过滤(null 表示不限)。 /// 正文关键字过滤(null 或空表示不限)。 /// 起始时刻(UTC 毫秒;null 表示不限)。 /// 结束时刻(UTC 毫秒;null 表示不限)。 /// 审计条目;任一过滤不满足或消息已不存在返回 null。 - private async Task TryComposeItemAsync(MessageSentRef reference, Dictionary channelCache, long tenantId, long appId, OnlineChatChannelKind? channelKind, long? participantPlayerId, string keyword, long? startTime, long? endTime) + private async Task TryComposeItemAsync(MessageSentRef reference, Dictionary channelCache, OnlineChatChannelKind? channelKind, long? participantPlayerId, string keyword, long? startTime, long? endTime) { if (!MatchesTimeWindow(reference, startTime, endTime)) { @@ -226,7 +222,7 @@ private async Task TryComposeItemAsync(MessageSentRef reference, OnlineChatChannel channel; if (!channelCache.TryGetValue(reference.ChannelId, out channel)) { - channel = await _chatStore.FindChannelAsync(tenantId, appId, reference.ChannelId).ConfigureAwait(false); + channel = await _chatStore.FindChannelAsync(reference.ChannelId).ConfigureAwait(false); channelCache[reference.ChannelId] = channel; } @@ -236,7 +232,7 @@ private async Task TryComposeItemAsync(MessageSentRef reference, return null; } - var message = await _chatStore.FindMessageAsync(tenantId, appId, reference.ChannelId, reference.MessageId).ConfigureAwait(false); + var message = await _chatStore.FindMessageAsync(reference.ChannelId, reference.MessageId).ConfigureAwait(false); if (message == null) { return null; diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineChatChannel.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineChatChannel.cs index a41981f9a..d40ddced6 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineChatChannel.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineChatChannel.cs @@ -53,15 +53,7 @@ public sealed class OnlineChatChannel /// public string ChannelId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置频道类型。 @@ -139,8 +131,6 @@ public OnlineChatChannel Copy() var copy = new OnlineChatChannel { ChannelId = ChannelId, - TenantId = TenantId, - AppId = AppId, Kind = Kind, BoundId = BoundId, CreatedAtTime = CreatedAtTime, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineChatEvents.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineChatEvents.cs index 929def519..b3116ebc8 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineChatEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineChatEvents.cs @@ -65,8 +65,6 @@ public static class OnlineChatEvents /// /// 构造消息发送事件。 /// - /// 租户标识。 - /// App 标识。 /// 消息标识(可空;载荷落空字符串)。 /// 频道标识(可空;载荷落空字符串)。 /// 频道类型名。 @@ -75,7 +73,7 @@ public static class OnlineChatEvents /// 频道内序号。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateMessageSent(long tenantId, long appId, string messageId, string channelId, string channelKind, long senderId, long sentAtTime, long sequence, string correlationId = null) + public static OnlineEvent CreateMessageSent(string messageId, string channelId, string channelKind, long senderId, long sentAtTime, long sequence, string correlationId = null) { var payload = new MessageSentPayload { @@ -100,8 +98,6 @@ public static OnlineEvent CreateMessageSent(long tenantId, long appId, string me EventType = MessageSent, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = senderId, Source = Source, @@ -114,8 +110,6 @@ public static OnlineEvent CreateMessageSent(long tenantId, long appId, string me /// /// 构造消息撤回事件。 /// - /// 租户标识。 - /// App 标识。 /// 消息标识(可空;载荷落空字符串)。 /// 频道标识(可空;载荷落空字符串)。 /// 原发送者。 @@ -123,7 +117,7 @@ public static OnlineEvent CreateMessageSent(long tenantId, long appId, string me /// 撤回时刻(UTC 毫秒)。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateMessageRecalled(long tenantId, long appId, string messageId, string channelId, long senderId, long recalledByPlayerId, long recalledAtTime, string correlationId = null) + public static OnlineEvent CreateMessageRecalled(string messageId, string channelId, long senderId, long recalledByPlayerId, long recalledAtTime, string correlationId = null) { var payload = new MessageRecalledPayload { @@ -146,8 +140,6 @@ public static OnlineEvent CreateMessageRecalled(long tenantId, long appId, strin EventType = MessageRecalled, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = recalledByPlayerId, Source = Source, @@ -160,8 +152,6 @@ public static OnlineEvent CreateMessageRecalled(long tenantId, long appId, strin /// /// 构造已读位点更新事件(消费端据此清红点)。 /// - /// 租户标识。 - /// App 标识。 /// 频道标识(可空;载荷落空字符串)。 /// 玩家标识。 /// 最后已读消息标识(可空;载荷落空字符串)。 @@ -169,7 +159,7 @@ public static OnlineEvent CreateMessageRecalled(long tenantId, long appId, strin /// 最后已读位置的频道内序号。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateReadMarkUpdated(long tenantId, long appId, string channelId, long playerId, string lastReadMessageId, long lastReadSentAtTime, long lastReadSequence, string correlationId = null) + public static OnlineEvent CreateReadMarkUpdated(string channelId, long playerId, string lastReadMessageId, long lastReadSentAtTime, long lastReadSequence, string correlationId = null) { var payload = new ReadMarkUpdatedPayload { @@ -192,8 +182,6 @@ public static OnlineEvent CreateReadMarkUpdated(long tenantId, long appId, strin EventType = ReadMarkUpdated, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = playerId, Source = Source, @@ -206,14 +194,12 @@ public static OnlineEvent CreateReadMarkUpdated(long tenantId, long appId, strin /// /// 构造审核插件执行失败事件(放行留痕:这条事件标记出了「未经审核即放行」的时间窗)。 /// - /// 租户标识。 - /// App 标识。 /// 发送者。 /// 频道标识。 /// 插件失败原因(异常消息;供排障)。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateModerationFailed(long tenantId, long appId, long playerId, string channelId, string reason, string correlationId = null) + public static OnlineEvent CreateModerationFailed(long playerId, string channelId, string reason, string correlationId = null) { var payload = new ModerationFailedPayload { @@ -233,8 +219,6 @@ public static OnlineEvent CreateModerationFailed(long tenantId, long appId, long EventType = ModerationFailed, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = playerId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineChatRateLimiter.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineChatRateLimiter.cs index 21e27d0a6..f0bb89d85 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineChatRateLimiter.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineChatRateLimiter.cs @@ -78,16 +78,14 @@ public OnlineChatRateLimiter(int maxMessages, int windowSeconds) /// /// 尝试获取一次发送配额。 /// - /// 租户标识。 - /// App 标识。 /// 发送者。 /// 频道标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 允许返回 true;超限返回 false。 - public bool TryAcquire(long tenantId, long appId, long playerId, string channelId, long nowUnixMilliseconds = 0) + public bool TryAcquire(long playerId, string channelId, long nowUnixMilliseconds = 0) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var key = tenantId + ":" + appId + ":" + playerId + ":" + (channelId ?? string.Empty); + var key = playerId + ":" + (channelId ?? string.Empty); lock (_syncRoot) { diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineChatReadMark.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineChatReadMark.cs index 4eb298d5b..921e48d26 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineChatReadMark.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineChatReadMark.cs @@ -40,15 +40,7 @@ namespace GameFrameX.Capability.Online.Social; /// public sealed class OnlineChatReadMark { - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置玩家标识。 @@ -108,8 +100,6 @@ public OnlineChatReadMark Copy() { return new OnlineChatReadMark { - TenantId = TenantId, - AppId = AppId, PlayerId = PlayerId, ChannelId = ChannelId, LastReadMessageId = LastReadMessageId, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineChatService.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineChatService.cs index df81ee497..beeb7b13c 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineChatService.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineChatService.cs @@ -163,16 +163,14 @@ public void AttachChannelMembershipProbes(IEnumerable /// - /// 租户标识。 - /// App 标识。 /// 频道类型。 /// 私聊一侧玩家(仅 使用)。 /// 私聊另一侧玩家(仅 使用)。 /// 绑定主体标识(Party 的 PartyId / Group 的 GroupId)。 /// 频道标识。 - public static string BuildChannelId(long tenantId, long appId, OnlineChatChannelKind kind, long leftPlayerId, long rightPlayerId, string boundId) + public static string BuildChannelId(OnlineChatChannelKind kind, long leftPlayerId, long rightPlayerId, string boundId) { - var scopePrefix = ChannelIdPrefix + tenantId + ":" + appId + ":"; + var scopePrefix = ChannelIdPrefix; if (kind == OnlineChatChannelKind.Global) { return scopePrefix + "global"; @@ -212,7 +210,7 @@ public Task> OpenDirectChannelAsync(OnlineScope return Task.FromResult(OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "私聊对端玩家无效")); } - var channelId = BuildChannelId(scope.TenantId, scope.AppId, OnlineChatChannelKind.Direct, scope.PlayerId, otherPlayerId, null); + var channelId = BuildChannelId(OnlineChatChannelKind.Direct, scope.PlayerId, otherPlayerId, null); return OpenChannelAsync(scope, OnlineChatChannelKind.Direct, channelId, string.Empty, scope.PlayerId, otherPlayerId, cancellationToken); } @@ -242,7 +240,7 @@ public Task> OpenBoundChannelAsync(OnlineScope s return Task.FromResult(OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "绑定主体标识不能为空")); } - var channelId = BuildChannelId(scope.TenantId, scope.AppId, kind, 0, 0, boundId); + var channelId = BuildChannelId(kind, 0, 0, boundId); return OpenChannelAsync(scope, kind, channelId, boundId, 0, 0, cancellationToken); } @@ -260,7 +258,7 @@ public Task> OpenGlobalChannelAsync(OnlineScope return Task.FromResult(failure); } - var channelId = BuildChannelId(scope.TenantId, scope.AppId, OnlineChatChannelKind.Global, 0, 0, null); + var channelId = BuildChannelId(OnlineChatChannelKind.Global, 0, 0, null); return OpenChannelAsync(scope, OnlineChatChannelKind.Global, channelId, string.Empty, 0, 0, cancellationToken); } @@ -300,7 +298,7 @@ public async Task> SendAsync(OnlineScope scope, // 重发短路:命中即返回既有消息,不再走裁决 / 频控 / 审核(「同一逻辑发送只落一条」)。 // 顺序不可后移——移到最后则重放要先过频控,窗口期内重发会拿到 RateLimitExceeded, // 客户端据此判定「发送失败」而消息其实早已入库。 - var replayed = await _store.FindByDedupeKeyAsync(scope.TenantId, scope.AppId, channelId, dedupeKey, cancellationToken).ConfigureAwait(false); + var replayed = await _store.FindByDedupeKeyAsync(channelId, dedupeKey, cancellationToken).ConfigureAwait(false); if (replayed != null) { return OnlineResult.Ok(replayed); @@ -313,7 +311,7 @@ public async Task> SendAsync(OnlineScope scope, return OnlineResult.Fail(decision.Code, decision.Reason); } - if (!_rateLimiter.TryAcquire(scope.TenantId, scope.AppId, scope.PlayerId, channelId)) + if (!_rateLimiter.TryAcquire(scope.PlayerId, channelId)) { return OnlineResult.Fail(OnlineErrorCode.RateLimitExceeded, "发送过于频繁"); } @@ -322,8 +320,6 @@ public async Task> SendAsync(OnlineScope scope, var draft = new OnlineChatMessage { MessageId = "msg-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, ChannelId = channelId, ChannelKind = channel.Kind, SenderId = scope.PlayerId, @@ -347,7 +343,7 @@ public async Task> SendAsync(OnlineScope scope, { // 只有真的新增才发事件:并发重放会在存储临界区内被去重键拦下并返回既有消息, // 无条件发布会让「消息已存在」这件事对外表现为第二次 MessageSent。 - await _eventPublisher.PublishAsync(OnlineChatEvents.CreateMessageSent(stored.TenantId, stored.AppId, stored.MessageId, stored.ChannelId, stored.ChannelKind.ToString(), stored.SenderId, stored.SentAtTime, stored.Sequence, correlationId), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineChatEvents.CreateMessageSent(stored.MessageId, stored.ChannelId, stored.ChannelKind.ToString(), stored.SenderId, stored.SentAtTime, stored.Sequence, correlationId), cancellationToken).ConfigureAwait(false); } return OnlineResult.Ok(stored); @@ -386,7 +382,7 @@ public async Task> GetHistoryAsync(OnlineSco } // 多取一条用于判定 HasMore,避免为「是否还有下一页」再查一次存储。 - var fetched = await _store.ReadAfterAsync(scope.TenantId, scope.AppId, new ChatReadCursor { ChannelId = channelId, AfterSentAtTime = afterSentAtTime, AfterSequence = afterSequence, Limit = effectivePageSize + 1, }, cancellationToken).ConfigureAwait(false); + var fetched = await _store.ReadAfterAsync(new ChatReadCursor { ChannelId = channelId, AfterSentAtTime = afterSentAtTime, AfterSequence = afterSequence, Limit = effectivePageSize + 1, }, cancellationToken).ConfigureAwait(false); var hasMore = fetched.Count > effectivePageSize; var pageMessages = new List(); var lastMessageId = string.Empty; @@ -428,10 +424,10 @@ public async Task> GetUnreadCountAsync(OnlineScope scope, stri return OnlineResult.Fail(authorized.Code, authorized.Message); } - var mark = await _store.FindReadMarkAsync(scope.TenantId, scope.AppId, scope.PlayerId, channelId, cancellationToken).ConfigureAwait(false); + var mark = await _store.FindReadMarkAsync(scope.PlayerId, channelId, cancellationToken).ConfigureAwait(false); var afterSentAtTime = mark == null ? 0 : mark.LastReadSentAtTime; var afterSequence = mark == null ? 0 : mark.LastReadSequence; - var count = await _store.CountUnreadAsync(scope.TenantId, scope.AppId, new ChatReadCursor { ChannelId = channelId, AfterSentAtTime = afterSentAtTime, AfterSequence = afterSequence, }, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var count = await _store.CountUnreadAsync(new ChatReadCursor { ChannelId = channelId, AfterSentAtTime = afterSentAtTime, AfterSequence = afterSequence, }, scope.PlayerId, cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(count); } @@ -452,13 +448,13 @@ public async Task> MarkReadAsync(OnlineScope sc return OnlineResult.Fail(authorized.Code, authorized.Message); } - var message = await _store.FindMessageAsync(scope.TenantId, scope.AppId, channelId, messageId, cancellationToken).ConfigureAwait(false); + var message = await _store.FindMessageAsync(channelId, messageId, cancellationToken).ConfigureAwait(false); if (message == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "消息不存在"); } - var mark = await _store.FindReadMarkAsync(scope.TenantId, scope.AppId, scope.PlayerId, channelId, cancellationToken).ConfigureAwait(false); + var mark = await _store.FindReadMarkAsync(scope.PlayerId, channelId, cancellationToken).ConfigureAwait(false); if (mark != null && mark.IsNotAfterPosition(message.SentAtTime, message.Sequence)) { // 位点只进不退:乱序到达的旧「已读」不得把位点推回去(否则红点会莫名其妙重新亮起)。 @@ -467,8 +463,6 @@ public async Task> MarkReadAsync(OnlineScope sc var updated = new OnlineChatReadMark { - TenantId = scope.TenantId, - AppId = scope.AppId, PlayerId = scope.PlayerId, ChannelId = channelId, LastReadMessageId = message.MessageId ?? string.Empty, @@ -481,7 +475,7 @@ public async Task> MarkReadAsync(OnlineScope sc { // 上面的读-比-写与本次写入不在同一临界区:期间已被更晚的位点抢写(或并发重复标记)。 // 收敛到既有位点,且**不发事件**——位点并没有被这次调用改动。 - var converged = await _store.FindReadMarkAsync(scope.TenantId, scope.AppId, scope.PlayerId, channelId, cancellationToken).ConfigureAwait(false); + var converged = await _store.FindReadMarkAsync(scope.PlayerId, channelId, cancellationToken).ConfigureAwait(false); if (converged == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "已读位点不存在"); @@ -490,7 +484,7 @@ public async Task> MarkReadAsync(OnlineScope sc return OnlineResult.Ok(converged); } - await _eventPublisher.PublishAsync(OnlineChatEvents.CreateReadMarkUpdated(stored.TenantId, stored.AppId, stored.ChannelId, stored.PlayerId, stored.LastReadMessageId, stored.LastReadSentAtTime, stored.LastReadSequence, correlationId), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineChatEvents.CreateReadMarkUpdated(stored.ChannelId, stored.PlayerId, stored.LastReadMessageId, stored.LastReadSentAtTime, stored.LastReadSequence, correlationId), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(stored); } @@ -511,7 +505,7 @@ public async Task> RecallAsync(OnlineScope scope return OnlineResult.Fail(authorized.Code, authorized.Message); } - var message = await _store.FindMessageAsync(scope.TenantId, scope.AppId, channelId, messageId, cancellationToken).ConfigureAwait(false); + var message = await _store.FindMessageAsync(channelId, messageId, cancellationToken).ConfigureAwait(false); if (message == null || message.SenderId != scope.PlayerId) { // 反预言:非发送者看不到这条消息(也谈不上撤回)。 @@ -530,11 +524,11 @@ public async Task> RecallAsync(OnlineScope scope return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "已超出撤回窗口"); } - var updated = await _store.UpdateMessageStateAsync(scope.TenantId, scope.AppId, new ChatMessageStateTransition { ChannelId = channelId, MessageId = messageId, ExpectedState = OnlineChatMessageState.Normal, NewState = OnlineChatMessageState.Recalled, NowUnixMilliseconds = now, RecalledByPlayerId = scope.PlayerId, }, cancellationToken).ConfigureAwait(false); + var updated = await _store.UpdateMessageStateAsync(new ChatMessageStateTransition { ChannelId = channelId, MessageId = messageId, ExpectedState = OnlineChatMessageState.Normal, NewState = OnlineChatMessageState.Recalled, NowUnixMilliseconds = now, RecalledByPlayerId = scope.PlayerId, }, cancellationToken).ConfigureAwait(false); if (updated == null) { // CAS 失败 = 已被并发撤回;重读后按当前事实返回,保证收敛。 - var current = await _store.FindMessageAsync(scope.TenantId, scope.AppId, channelId, messageId, cancellationToken).ConfigureAwait(false); + var current = await _store.FindMessageAsync(channelId, messageId, cancellationToken).ConfigureAwait(false); if (current == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "消息不存在"); @@ -543,7 +537,7 @@ public async Task> RecallAsync(OnlineScope scope return OnlineResult.Ok(RedactRecalled(current)); } - await _eventPublisher.PublishAsync(OnlineChatEvents.CreateMessageRecalled(updated.TenantId, updated.AppId, updated.MessageId, updated.ChannelId, updated.SenderId, updated.RecalledByPlayerId, updated.RecalledAtTime, correlationId), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineChatEvents.CreateMessageRecalled(updated.MessageId, updated.ChannelId, updated.SenderId, updated.RecalledByPlayerId, updated.RecalledAtTime, correlationId), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(RedactRecalled(updated)); } @@ -565,7 +559,7 @@ public async Task> ReportAsync(OnlineScope scope, return OnlineResult.Fail(authorized.Code, authorized.Message); } - var message = await _store.FindMessageAsync(scope.TenantId, scope.AppId, channelId, messageId, cancellationToken).ConfigureAwait(false); + var message = await _store.FindMessageAsync(channelId, messageId, cancellationToken).ConfigureAwait(false); if (message == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "消息不存在"); @@ -598,7 +592,7 @@ private async Task> OpenChannelAsync(OnlineScope return membership; } - var existing = await _store.FindChannelAsync(scope.TenantId, scope.AppId, channelId, cancellationToken).ConfigureAwait(false); + var existing = await _store.FindChannelAsync(channelId, cancellationToken).ConfigureAwait(false); if (existing != null) { return OnlineResult.Ok(existing); @@ -614,8 +608,6 @@ private async Task> OpenChannelAsync(OnlineScope var prototype = new OnlineChatChannel { ChannelId = channelId, - TenantId = scope.TenantId, - AppId = scope.AppId, Kind = kind, BoundId = boundId ?? string.Empty, Participants = participants, @@ -644,7 +636,7 @@ private async Task> AuthorizeChannelAsync(Online return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "频道标识不能为空"); } - var channel = await _store.FindChannelAsync(scope.TenantId, scope.AppId, channelId, cancellationToken).ConfigureAwait(false); + var channel = await _store.FindChannelAsync(channelId, cancellationToken).ConfigureAwait(false); if (channel == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "频道不存在"); @@ -697,7 +689,7 @@ private async Task> CheckMembershipAsync(OnlineS foreach (var probe in _membershipProbes) { - var isMember = await probe.IsChannelMemberAsync(scope.TenantId, scope.AppId, kind, boundId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var isMember = await probe.IsChannelMemberAsync(kind, boundId, scope.PlayerId, cancellationToken).ConfigureAwait(false); if (isMember) { return null; @@ -724,7 +716,7 @@ private async Task EvaluateSendAsync(OnlineScope scope, On return OnlineSocialDecision.Deny(OnlineErrorCode.ResourceNotFound, "频道不存在"); } - return await _decisionService.EvaluateAsync(scope.TenantId, scope.AppId, scope.PlayerId, otherPlayerId, OnlineSocialInteractionPurpose.DirectMessage, cancellationToken).ConfigureAwait(false); + return await _decisionService.EvaluateAsync(scope.PlayerId, otherPlayerId, OnlineSocialInteractionPurpose.DirectMessage, cancellationToken).ConfigureAwait(false); } return await _decisionService.EvaluateSendAsync(scope, cancellationToken).ConfigureAwait(false); @@ -748,7 +740,7 @@ private async Task> CheckModerationAsync(OnlineC catch (Exception exception) { // 审核服务故障不得导致聊天不可用:放行 + 留痕(放行窗口可由该事件回扫)。 - await _eventPublisher.PublishAsync(OnlineChatEvents.CreateModerationFailed(draft.TenantId, draft.AppId, draft.SenderId, draft.ChannelId, exception.Message, correlationId), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineChatEvents.CreateModerationFailed(draft.SenderId, draft.ChannelId, exception.Message, correlationId), cancellationToken).ConfigureAwait(false); return null; } diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendDomainFace.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendDomainFace.cs index 3e9107c10..996ef34a6 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendDomainFace.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendDomainFace.cs @@ -375,14 +375,14 @@ private static OnlineResult NotFound() } /// - /// 以同三元组 + 指定玩家位构造作用域(直接添加语义以被请求方身份补接受时使用)。 + /// 以同区服键 + 指定玩家位构造作用域(直接添加语义以被请求方身份补接受时使用)。 /// /// 源作用域。 /// 玩家位。 /// 新作用域。 private static OnlineScope WithPlayer(OnlineScope scope, long playerId) { - return new OnlineScope(scope.TenantId, scope.AppId, scope.ServerId, playerId); + return new OnlineScope(scope.ServerId, playerId); } /// diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs index f68a7693f..8dd19c682 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs @@ -59,20 +59,18 @@ public static class OnlineFriendLegacyMigration /// 执行旧好友数据迁移(社交能力模块在激活期、好友域桥发布后调用)。 /// /// 好友域服务(真实写路径的唯一属主)。 - /// 租户标识(宿主 OnlineScope 三元组)。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// 迁移汇总(已建立关系数 / 待答申请数 / 失败数)。 - public static async Task<(int Established, int Pending, int Failed)> MigrateAsync(OnlineFriendService friends, long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public static async Task<(int Established, int Pending, int Failed)> MigrateAsync(OnlineFriendService friends, long serverId, CancellationToken cancellationToken = default) { var domain = new OnlineFriendDomainFace(friends); // ① 域 120 旧链:FriendRelationState Status=0 → 已建立关系(Establish = 申请 + 立即接受,幂等收敛)。 - var (established, relationFailed) = await MigrateEstablishedRelationsAsync(domain, tenantId, appId, serverId, cancellationToken).ConfigureAwait(false); + var (established, relationFailed) = await MigrateEstablishedRelationsAsync(domain, serverId, cancellationToken).ConfigureAwait(false); // ② 域 660 旧链:FriendState 档案 Outgoing → 待答申请(对已建立的对幂等无效果)。 - var (pending, profileFailed) = await MigratePendingRequestsAsync(domain, tenantId, appId, serverId, cancellationToken).ConfigureAwait(false); + var (pending, profileFailed) = await MigratePendingRequestsAsync(domain, serverId, cancellationToken).ConfigureAwait(false); var failed = relationFailed + profileFailed; return (established, pending, failed); @@ -83,12 +81,10 @@ public static class OnlineFriendLegacyMigration /// (Establish = 申请 + 立即接受,幂等收敛);单条失败计数并继续(containment)。 /// /// Online 好友域契约面。 - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// (已建立关系数,失败数)。 - private static async Task<(int Established, int Failed)> MigrateEstablishedRelationsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, CancellationToken cancellationToken) + private static async Task<(int Established, int Failed)> MigrateEstablishedRelationsAsync(OnlineFriendDomainFace domain, long serverId, CancellationToken cancellationToken) { var established = 0; var failed = 0; @@ -102,7 +98,7 @@ public static class OnlineFriendLegacyMigration continue; } - var result = await domain.EstablishAsync(PlayerScope(tenantId, appId, serverId, low), high, cancellationToken).ConfigureAwait(false); + var result = await domain.EstablishAsync(PlayerScope(serverId, low), high, cancellationToken).ConfigureAwait(false); if (result.IsSuccess && result.Data.After == OnlineFriendRelationKind.Friend) { established++; @@ -121,12 +117,10 @@ public static class OnlineFriendLegacyMigration /// (对已建立的对幂等无效果)。 /// /// Online 好友域契约面。 - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// (待答申请数,失败数)。 - private static async Task<(int Pending, int Failed)> MigratePendingRequestsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, CancellationToken cancellationToken) + private static async Task<(int Pending, int Failed)> MigratePendingRequestsAsync(OnlineFriendDomainFace domain, long serverId, CancellationToken cancellationToken) { var pending = 0; var failed = 0; @@ -145,7 +139,7 @@ public static class OnlineFriendLegacyMigration continue; } - var (entryPending, entryFailed) = await MigrateOutgoingRequestsAsync(domain, tenantId, appId, serverId, profile, cancellationToken).ConfigureAwait(false); + var (entryPending, entryFailed) = await MigrateOutgoingRequestsAsync(domain, serverId, profile, cancellationToken).ConfigureAwait(false); pending += entryPending; failed += entryFailed; } @@ -159,13 +153,11 @@ public static class OnlineFriendLegacyMigration /// 单条失败计数并继续(containment)。 /// /// Online 好友域契约面。 - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 旧 660 好友档案。 /// 取消令牌。 /// (待答申请数,失败数)。 - private static async Task<(int Pending, int Failed)> MigrateOutgoingRequestsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, FriendProfileState profile, CancellationToken cancellationToken) + private static async Task<(int Pending, int Failed)> MigrateOutgoingRequestsAsync(OnlineFriendDomainFace domain, long serverId, FriendProfileState profile, CancellationToken cancellationToken) { var pending = 0; var failed = 0; @@ -176,7 +168,7 @@ public static class OnlineFriendLegacyMigration continue; } - var result = await domain.RequestAsync(PlayerScope(tenantId, appId, serverId, profile.PlayerId), targetPlayerId, cancellationToken).ConfigureAwait(false); + var result = await domain.RequestAsync(PlayerScope(serverId, profile.PlayerId), targetPlayerId, cancellationToken).ConfigureAwait(false); if (result.IsSuccess) { pending++; @@ -191,15 +183,13 @@ public static class OnlineFriendLegacyMigration } /// - /// 构造玩家作用域(三元组取宿主 OnlineScope 值,玩家位为迁移主体)。 + /// 构造玩家作用域(区服键取宿主 OnlineScope 值,玩家位为迁移主体)。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 玩家标识。 /// 生效作用域。 - private static OnlineScope PlayerScope(long tenantId, long appId, long serverId, long playerId) + private static OnlineScope PlayerScope(long serverId, long playerId) { - return new OnlineScope(tenantId, appId, serverId, playerId); + return new OnlineScope(serverId, playerId); } } diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendService.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendService.cs index 28e28b1ac..516b83187 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendService.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendService.cs @@ -132,7 +132,7 @@ public async Task>> Searc return OnlineResult>.Ok(new List()); } - var found = await _directory.SearchByNameAsync(scope.TenantId, scope.AppId, keyword.Trim(), _searchLimit, cancellationToken).ConfigureAwait(false); + var found = await _directory.SearchByNameAsync(keyword.Trim(), _searchLimit, cancellationToken).ConfigureAwait(false); var result = new List(); foreach (var entry in found) { @@ -180,7 +180,7 @@ public async Task> RequestAsync(OnlineScope scope } var now = Now(); - var existing = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var existing = await _store.FindAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (existing != null) { return await ConvergeExistingAsync(existing, scope, correlationId, now, cancellationToken).ConfigureAwait(false); @@ -199,8 +199,6 @@ public async Task> RequestAsync(OnlineScope scope var prototype = new OnlineFriendship { FriendshipId = "frd-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, LowPlayerId = low, HighPlayerId = high, @@ -224,8 +222,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateFriendshipChanged( effective.RequesterId, effective.AddresseeId, effective.State.ToString(), - effective.TenantId, - effective.AppId, effective.ServerId, OnlineSocialEvents.FriendshipRequested, correlationId), cancellationToken).ConfigureAwait(false); @@ -274,7 +270,7 @@ public async Task> RemoveAsync(OnlineScope scope, return failure; } - var friendship = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var friendship = await _store.FindAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (friendship == null || !friendship.Contains(scope.PlayerId)) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "好友关系不存在"); @@ -291,11 +287,11 @@ public async Task> RemoveAsync(OnlineScope scope, return OnlineResult.Fail(OnlineErrorCode.StateOperationForbidden, "当前关系状态不允许删除:" + friendship.State); } - var removed = await _store.UpdateStateAsync(scope.TenantId, scope.AppId, new FriendshipStateTransition { FriendshipId = friendship.FriendshipId, ExpectedState = friendship.State, NewState = OnlineFriendshipState.Removed, NowUnixMilliseconds = Now(), Responded = false, }, cancellationToken).ConfigureAwait(false); + var removed = await _store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = friendship.FriendshipId, ExpectedState = friendship.State, NewState = OnlineFriendshipState.Removed, NowUnixMilliseconds = Now(), Responded = false, }, cancellationToken).ConfigureAwait(false); if (removed == null) { // CAS 失败 = 状态被并发改写;重读后按当前事实返回,不报错。 - var current = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var current = await _store.FindAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (current == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "好友关系不存在"); @@ -309,8 +305,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateFriendshipChanged( removed.RequesterId, removed.AddresseeId, removed.State.ToString(), - removed.TenantId, - removed.AppId, removed.ServerId, OnlineSocialEvents.FriendshipRemoved, correlationId), cancellationToken).ConfigureAwait(false); @@ -331,7 +325,7 @@ public async Task>> ListFriendsA return failure; } - var all = await _store.ListByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var all = await _store.ListByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); var friendIds = new List(); var establishedAtTimeByPlayer = new Dictionary(); CollectEstablishedFriends(all, scope.PlayerId, friendIds, establishedAtTimeByPlayer); @@ -390,7 +384,7 @@ private async Task ResolveFriendDirectoryAsync(OnlineScope scope, List fri return; } - var entries = await _directory.FindAsync(scope.TenantId, scope.AppId, friendIds, cancellationToken).ConfigureAwait(false); + var entries = await _directory.FindAsync(friendIds, cancellationToken).ConfigureAwait(false); foreach (var entry in entries) { names[entry.PlayerId] = entry.Name; @@ -416,7 +410,7 @@ private async Task> BuildFriendSummariesAsync(OnlineSc var online = false; if (_presenceProbe != null) { - online = await _presenceProbe.IsOnlineAsync(scope.TenantId, scope.AppId, friendId, cancellationToken).ConfigureAwait(false); + online = await _presenceProbe.IsOnlineAsync(friendId, cancellationToken).ConfigureAwait(false); } string name; @@ -455,7 +449,7 @@ public async Task>> ListPendingRequ return failure; } - var all = await _store.ListByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var all = await _store.ListByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); var result = new List(); foreach (var friendship in all) { @@ -487,7 +481,7 @@ public async Task>> ListRelationsAs return failure; } - var all = await _store.ListByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var all = await _store.ListByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); return OnlineResult>.Ok(all); } @@ -510,22 +504,20 @@ public async Task> FindAsync(OnlineScope scope, l return failure; } - var found = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var found = await _store.FindAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(found); } /// /// 扫描并终结超期未答复的好友请求(置 ,可重新发起)。 /// - /// 租户标识。 - /// App 标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 /// 本次终结的请求数。 - public async Task> SweepExpiredAsync(long tenantId, long appId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task> SweepExpiredAsync(long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : Now(); - var pending = await _store.ListByStateAsync(tenantId, appId, OnlineFriendshipState.Requested, cancellationToken).ConfigureAwait(false); + var pending = await _store.ListByStateAsync(OnlineFriendshipState.Requested, cancellationToken).ConfigureAwait(false); var affected = 0; foreach (var friendship in pending) { @@ -534,7 +526,7 @@ public async Task> SweepExpiredAsync(long tenantId, long appId continue; } - var expired = await _store.UpdateStateAsync(tenantId, appId, new FriendshipStateTransition { FriendshipId = friendship.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, NewState = OnlineFriendshipState.Expired, NowUnixMilliseconds = now, Responded = false, }, cancellationToken).ConfigureAwait(false); + var expired = await _store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = friendship.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, NewState = OnlineFriendshipState.Expired, NowUnixMilliseconds = now, Responded = false, }, cancellationToken).ConfigureAwait(false); if (expired != null) { await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateFriendshipChanged( @@ -542,8 +534,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateFriendshipChanged( expired.RequesterId, expired.AddresseeId, expired.State.ToString(), - expired.TenantId, - expired.AppId, expired.ServerId, OnlineSocialEvents.FriendshipExpired, null), cancellationToken).ConfigureAwait(false); @@ -593,7 +583,7 @@ private async Task IsFriendLimitReachedAsync(OnlineScope scope, long first /// 已建立的好友关系数。 private async Task CountEstablishedAsync(OnlineScope scope, long playerId, CancellationToken cancellationToken) { - var all = await _store.ListByPlayerAsync(scope.TenantId, scope.AppId, playerId, cancellationToken).ConfigureAwait(false); + var all = await _store.ListByPlayerAsync(playerId, cancellationToken).ConfigureAwait(false); var count = 0; foreach (var candidate in all) { @@ -658,8 +648,6 @@ private async Task> AnswerAsync(OnlineScope scope // 「上限-1」而双双落库超限。拒绝仍落在**写侧**(关系建立的那一刻),而不是读取侧静默截断 // (静默截断的危害见下:被截掉的好友在列表里凭空消失且无错误信号可申诉)。 var outcome = await _store.UpdateStateWithFriendLimitAsync( - scope.TenantId, - scope.AppId, new FriendshipStateTransition { FriendshipId = friendshipId, ExpectedState = friendship.State, NewState = target, NowUnixMilliseconds = now, Responded = true, }, _friendLimit, cancellationToken).ConfigureAwait(false); @@ -672,7 +660,7 @@ private async Task> AnswerAsync(OnlineScope scope } else { - updated = await _store.UpdateStateAsync(scope.TenantId, scope.AppId, new FriendshipStateTransition { FriendshipId = friendshipId, ExpectedState = friendship.State, NewState = target, NowUnixMilliseconds = now, Responded = true, }, cancellationToken).ConfigureAwait(false); + updated = await _store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = friendshipId, ExpectedState = friendship.State, NewState = target, NowUnixMilliseconds = now, Responded = true, }, cancellationToken).ConfigureAwait(false); } if (updated == null) @@ -693,8 +681,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateFriendshipChanged( updated.RequesterId, updated.AddresseeId, updated.State.ToString(), - updated.TenantId, - updated.AppId, updated.ServerId, eventKind, correlationId), cancellationToken).ConfigureAwait(false); @@ -710,7 +696,7 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateFriendshipChanged( /// 关系副本;不存在返回 null。 private async Task FindByIdAsync(OnlineScope scope, string friendshipId, CancellationToken cancellationToken) { - var all = await _store.ListByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var all = await _store.ListByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); foreach (var friendship in all) { if (string.Equals(friendship.FriendshipId, friendshipId, StringComparison.Ordinal)) @@ -753,8 +739,6 @@ private async Task> ConvergeExistingAsync(OnlineF } var renewed = await _store.RenewRequestAsync( - scope.TenantId, - scope.AppId, new FriendshipRenewal { FriendshipId = existing.FriendshipId, @@ -769,7 +753,7 @@ private async Task> ConvergeExistingAsync(OnlineF if (renewed == null) { // CAS 失败 = 并发发起/答复抢先;重读后返回当前事实,保证收敛。 - var current = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var current = await _store.FindAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (current == null) { return OnlineResult.Fail(OnlineErrorCode.DependencyUnavailable, "好友关系读取失败"); @@ -783,8 +767,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateFriendshipChanged( renewed.RequesterId, renewed.AddresseeId, renewed.State.ToString(), - renewed.TenantId, - renewed.AppId, renewed.ServerId, OnlineSocialEvents.FriendshipRequested, correlationId), cancellationToken).ConfigureAwait(false); diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendship.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendship.cs index ea339241a..3bb4896d8 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendship.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendship.cs @@ -36,8 +36,8 @@ namespace GameFrameX.Capability.Online.Social; /// ① **唯一键是无向对**——/ 由 /// 规范化(低标识在前),A→B 与 B→A 命中同一条记录, /// 因此「重复请求」在存储层就无第二条可落; -/// ② 本类型不承载作用域内的 ServerId 唯一性——好友关系是跨区服成立的,键为 Tenant + App + 无向对, -/// 不含 ServerId(「键 = Tenant+App+Player,不含 Server」); 仅记录 +/// ② 本类型不承载作用域内的 ServerId 唯一性——好友关系是跨区服成立的全局关系,键为无向对, +/// 不含 ServerId(全局域键,键 = 玩家对); 仅记录 /// 关系建立时的来源区服,供审计与投递路由参考; /// ③ 只能经 迁移; /// ④ 是方向事实,关系被接受后**不翻转**——「谁先发起」是审计语义, @@ -51,15 +51,7 @@ public sealed class OnlineFriendship /// public string FriendshipId { get; set; } - /// - /// 获取或设置租户标识(数据隔离根边界)。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识(数据隔离根边界)。 - /// - public long AppId { get; set; } /// /// 获取或设置关系建立时的来源区服标识(仅审计与投递路由参考,不参与唯一键)。 @@ -174,8 +166,6 @@ public OnlineFriendship Copy() return new OnlineFriendship { FriendshipId = FriendshipId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, LowPlayerId = LowPlayerId, HighPlayerId = HighPlayerId, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineGroup.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineGroup.cs index 6d57c33d1..89f403d72 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineGroup.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineGroup.cs @@ -49,15 +49,7 @@ public sealed class OnlineGroup /// public string GroupId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } /// /// 获取或设置群主标识(建群者,群内唯一)。 @@ -122,8 +114,6 @@ public OnlineGroup Copy() var copy = new OnlineGroup { GroupId = GroupId, - TenantId = TenantId, - AppId = AppId, OwnerId = OwnerId, Name = Name, MaxMembers = MaxMembers, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineGroupInvite.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineGroupInvite.cs index bdb4ed21d..97e6f0531 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineGroupInvite.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineGroupInvite.cs @@ -43,15 +43,7 @@ public sealed class OnlineGroupInvite /// public string InviteId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } /// /// 获取或设置所属群组标识(邀请集合内冗余承载,便于事件载荷自解释,不参与唯一键)。 @@ -97,8 +89,6 @@ public OnlineGroupInvite Copy() return new OnlineGroupInvite { InviteId = InviteId, - TenantId = TenantId, - AppId = AppId, GroupId = GroupId, InviterId = InviterId, InviteeId = InviteeId, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineGroupService.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineGroupService.cs index 548d6efe7..4ce151052 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineGroupService.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineGroupService.cs @@ -107,8 +107,6 @@ public async Task> CreateAsync(OnlineScope scope, stri var group = new OnlineGroup { GroupId = "grp-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, OwnerId = scope.PlayerId, Name = name.Trim(), Metadata = new Dictionary(StringComparer.Ordinal), @@ -190,8 +188,6 @@ public async Task> InviteAsync(OnlineScope scope var invite = new OnlineGroupInvite { InviteId = "ginv-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, GroupId = group.GroupId, InviterId = scope.PlayerId, InviteeId = inviteeId, @@ -628,21 +624,19 @@ public async Task>> ListMembersAsy /// 一律返回 false(不认领),由对应的归属域应答。 /// /// - /// 租户标识。 - /// App 标识。 /// 频道类型。 /// 频道绑定的业务标识(本域为群组标识)。 /// 待裁决玩家。 /// 取消令牌。 /// 是成员且群组仍可发言返回 true。 - public async Task IsChannelMemberAsync(long tenantId, long appId, OnlineChatChannelKind kind, string boundId, long playerId, CancellationToken cancellationToken = default) + public async Task IsChannelMemberAsync(OnlineChatChannelKind kind, string boundId, long playerId, CancellationToken cancellationToken = default) { if (kind != OnlineChatChannelKind.Group || string.IsNullOrEmpty(boundId)) { return false; } - var group = await _store.FindAsync(tenantId, appId, boundId, cancellationToken).ConfigureAwait(false); + var group = await _store.FindAsync(boundId, cancellationToken).ConfigureAwait(false); if (group == null || group.State != OnlineGroupState.Active) { return false; @@ -665,7 +659,7 @@ public async Task>> ListMyGroupsAsync(On return failure; } - var groups = await _store.ListByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var groups = await _store.ListByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); return OnlineResult>.Ok(groups); } @@ -741,15 +735,13 @@ public async Task> UpdateMetadataAsync(OnlineScope sco /// /// 扫描并终结超期待答复邀请(置 ;群组状态不受影响)。 /// - /// 租户标识。 - /// App 标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 /// 本次置为过期的邀请条数。 - public async Task> SweepExpiredInvitesAsync(long tenantId, long appId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task> SweepExpiredInvitesAsync(long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : Now(); - var groups = await _store.ListByStateAsync(tenantId, appId, OnlineGroupState.Active, cancellationToken).ConfigureAwait(false); + var groups = await _store.ListByStateAsync(OnlineGroupState.Active, cancellationToken).ConfigureAwait(false); var affected = 0; foreach (var group in groups) { @@ -917,7 +909,7 @@ private async Task ReplaceWithReplayAsync(OnlineGroup snapshot, Fun return saved; } - var current = await _store.FindAsync(snapshot.TenantId, snapshot.AppId, snapshot.GroupId, cancellationToken).ConfigureAwait(false); + var current = await _store.FindAsync(snapshot.GroupId, cancellationToken).ConfigureAwait(false); if (current == null) { return null; @@ -1081,7 +1073,7 @@ private Task FindAsync(OnlineScope scope, string groupId, Cancellat return Task.FromResult(null); } - return _store.FindAsync(scope.TenantId, scope.AppId, groupId, cancellationToken); + return _store.FindAsync(groupId, cancellationToken); } /// @@ -1228,8 +1220,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateGroupChanged( group.State.ToString(), group.Members == null ? 0 : group.Members.Count, group.Revision, - group.TenantId, - group.AppId, action, correlationId), cancellationToken).ConfigureAwait(false); } diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineMuteEntry.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineMuteEntry.cs index a88b73bc8..f05e1c312 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineMuteEntry.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineMuteEntry.cs @@ -60,15 +60,7 @@ public sealed class OnlineMuteEntry /// public long MutedPlayerId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置发起静音时所在的区服标识(仅作事件信封与审计记录用;**不参与存储键**)。 @@ -106,8 +98,6 @@ public OnlineMuteEntry Copy() EntryId = EntryId, OwnerId = OwnerId, MutedPlayerId = MutedPlayerId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, ExpiresAtTime = ExpiresAtTime, CreatedAtTime = CreatedAtTime, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineNotification.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineNotification.cs index cd5100d91..c42eca3d3 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineNotification.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineNotification.cs @@ -49,15 +49,7 @@ public sealed class OnlineNotification /// public string NotificationId { get; set; } - /// - /// 获取或设置租户标识(数据隔离根边界)。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识(数据隔离根边界)。 - /// - public long AppId { get; set; } /// /// 获取或设置通知产生时的来源区服标识(仅审计与投递路由参考,不参与唯一键)。 @@ -150,8 +142,6 @@ public OnlineNotification Copy() return new OnlineNotification { NotificationId = NotificationId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, PlayerId = PlayerId, Kind = Kind, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineNotificationEvents.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineNotificationEvents.cs index 0a13455fc..df585d27a 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineNotificationEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineNotificationEvents.cs @@ -52,8 +52,6 @@ public static class OnlineNotificationEvents /// /// 构造通知状态变更事件。 /// - /// 租户标识。 - /// App 标识。 /// 来源区服标识。 /// 接收者玩家标识。 /// 通知标识(可空;载荷落空字符串)。 @@ -62,7 +60,7 @@ public static class OnlineNotificationEvents /// 累计推送尝试次数。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateNotificationChanged(long tenantId, long appId, long serverId, long playerId, string notificationId, string kind, string state, int attemptCount, string correlationId = null) + public static OnlineEvent CreateNotificationChanged(long serverId, long playerId, string notificationId, string kind, string state, int attemptCount, string correlationId = null) { var payload = new NotificationChangedPayload { @@ -86,8 +84,6 @@ public static OnlineEvent CreateNotificationChanged(long tenantId, long appId, l EventType = NotificationChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = playerId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineNotificationService.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineNotificationService.cs index 4c67bd492..f99c0669d 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineNotificationService.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineNotificationService.cs @@ -142,8 +142,6 @@ public async Task> EnqueueAsync(OnlineScope sco var prototype = new OnlineNotification { NotificationId = "ntf-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, PlayerId = scope.PlayerId, Kind = kind, @@ -171,9 +169,9 @@ public async Task> EnqueueAsync(OnlineScope sco return OnlineResult.Ok(effective); } - await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(effective.TenantId, effective.AppId, effective.ServerId, effective.PlayerId, effective.NotificationId, effective.Kind.ToString(), effective.State.ToString(), effective.AttemptCount, correlationId), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(effective.ServerId, effective.PlayerId, effective.NotificationId, effective.Kind.ToString(), effective.State.ToString(), effective.AttemptCount, correlationId), cancellationToken).ConfigureAwait(false); - var dispatched = await TryDispatchAsync(scope.TenantId, scope.AppId, scope.PlayerId, effective.NotificationId, cancellationToken).ConfigureAwait(false); + var dispatched = await TryDispatchAsync(scope.PlayerId, effective.NotificationId, cancellationToken).ConfigureAwait(false); if (dispatched.IsSuccess && dispatched.Data != null) { // 推送已尝试:返回落定后的状态(Delivered / Retrying / Failed),入队本身仍是成功的。 @@ -208,20 +206,18 @@ public async Task> EnqueueAsync(OnlineScope sco /// 并**原样返回、绝不推给玩家**(过期丢弃、不误导玩家)。 /// /// - /// 租户标识。 - /// App 标识。 /// 接收者玩家标识。 /// 通知标识。 /// 取消令牌。 /// 推送尝试后的通知记录。 - public async Task> TryDispatchAsync(long tenantId, long appId, long playerId, string notificationId, CancellationToken cancellationToken = default) + public async Task> TryDispatchAsync(long playerId, string notificationId, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(notificationId)) { return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "通知标识不能为空"); } - var current = await _store.FindAsync(tenantId, appId, playerId, notificationId, cancellationToken).ConfigureAwait(false); + var current = await _store.FindAsync(playerId, notificationId, cancellationToken).ConfigureAwait(false); if (current == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "通知不存在"); @@ -235,7 +231,7 @@ public async Task> TryDispatchAsync(long tenant var now = Now(); // 过期兜底独立成方法:命中即就地终结并返回,未到期返回 null 交回主流程继续推送。 - var expiredResult = await TerminateIfExpiredAsync(tenantId, appId, playerId, current, now, cancellationToken).ConfigureAwait(false); + var expiredResult = await TerminateIfExpiredAsync(playerId, current, now, cancellationToken).ConfigureAwait(false); if (expiredResult != null) { return expiredResult; @@ -259,10 +255,10 @@ public async Task> TryDispatchAsync(long tenant if (queued == null) { // CAS 失败 = 状态被并发改写(如过期扫描抢先);重读后按当前事实返回,不报错。 - return await ConvergeAsync(tenantId, appId, playerId, notificationId, cancellationToken).ConfigureAwait(false); + return await ConvergeAsync(playerId, notificationId, cancellationToken).ConfigureAwait(false); } - await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(queued.TenantId, queued.AppId, queued.ServerId, queued.PlayerId, queued.NotificationId, queued.Kind.ToString(), queued.State.ToString(), queued.AttemptCount, null), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(queued.ServerId, queued.PlayerId, queued.NotificationId, queued.Kind.ToString(), queued.State.ToString(), queued.AttemptCount, null), cancellationToken).ConfigureAwait(false); var outcome = await DispatchAsync(queued, cancellationToken).ConfigureAwait(false); var settled = SettleDispatchOutcome(queued, outcome); @@ -275,10 +271,10 @@ public async Task> TryDispatchAsync(long tenant var result = await _store.ReplaceAsync(settled, OnlineNotificationState.Queued, queued.AttemptCount, cancellationToken).ConfigureAwait(false); if (result == null) { - return await ConvergeAsync(tenantId, appId, playerId, notificationId, cancellationToken).ConfigureAwait(false); + return await ConvergeAsync(playerId, notificationId, cancellationToken).ConfigureAwait(false); } - await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(result.TenantId, result.AppId, result.ServerId, result.PlayerId, result.NotificationId, result.Kind.ToString(), result.State.ToString(), result.AttemptCount, null), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(result.ServerId, result.PlayerId, result.NotificationId, result.Kind.ToString(), result.State.ToString(), result.AttemptCount, null), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(result); } @@ -303,7 +299,7 @@ public async Task> MarkReadAsync(OnlineScope sc return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "通知标识不能为空"); } - var notification = await _store.FindAsync(scope.TenantId, scope.AppId, scope.PlayerId, notificationId, cancellationToken).ConfigureAwait(false); + var notification = await _store.FindAsync(scope.PlayerId, notificationId, cancellationToken).ConfigureAwait(false); if (notification == null || notification.PlayerId != scope.PlayerId) { // 反预言:非接收者(含越权猜标识)看不到这条通知的存在,不泄露他人通知规模。 @@ -334,10 +330,10 @@ public async Task> MarkReadAsync(OnlineScope sc var updated = await _store.ReplaceAsync(read, OnlineNotificationState.Delivered, notification.AttemptCount, cancellationToken).ConfigureAwait(false); if (updated == null) { - return await ConvergeAsync(scope.TenantId, scope.AppId, scope.PlayerId, notificationId, cancellationToken).ConfigureAwait(false); + return await ConvergeAsync(scope.PlayerId, notificationId, cancellationToken).ConfigureAwait(false); } - await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(updated.TenantId, updated.AppId, updated.ServerId, updated.PlayerId, updated.NotificationId, updated.Kind.ToString(), updated.State.ToString(), updated.AttemptCount, correlationId), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(updated.ServerId, updated.PlayerId, updated.NotificationId, updated.Kind.ToString(), updated.State.ToString(), updated.AttemptCount, correlationId), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(updated); } @@ -360,7 +356,7 @@ public async Task>> ListAsync(Onl return failure; } - var all = await _store.ListByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var all = await _store.ListByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); var result = new List(); foreach (var notification in all) { @@ -396,7 +392,7 @@ public async Task>> BackfillAsync return failure; } - var all = await _store.ListByPlayerAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var all = await _store.ListByPlayerAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); var result = new List(); foreach (var notification in all) { @@ -405,7 +401,7 @@ public async Task>> BackfillAsync continue; } - var dispatched = await TryDispatchAsync(scope.TenantId, scope.AppId, scope.PlayerId, notification.NotificationId, cancellationToken).ConfigureAwait(false); + var dispatched = await TryDispatchAsync(scope.PlayerId, notification.NotificationId, cancellationToken).ConfigureAwait(false); if (dispatched.IsSuccess && dispatched.Data != null) { result.Add(dispatched.Data); @@ -427,18 +423,16 @@ public async Task>> BackfillAsync /// 租约已耗尽的在途记录(推送出口随进程消失的死在途)照常终结,这是死在途回收的唯一路径。 /// /// - /// 租户标识。 - /// App 标识。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 /// 本次终结的通知条数。 - public async Task> SweepExpiredAsync(long tenantId, long appId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task> SweepExpiredAsync(long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : Now(); var affected = 0; foreach (var state in NonTerminalStates) { - var pending = await _store.ListByStateAsync(tenantId, appId, state, cancellationToken).ConfigureAwait(false); + var pending = await _store.ListByStateAsync(state, cancellationToken).ConfigureAwait(false); foreach (var notification in pending) { if (notification.ExpiresAtTime <= 0 || notification.ExpiresAtTime > now) @@ -464,7 +458,7 @@ public async Task> SweepExpiredAsync(long tenantId, long appId continue; } - await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(updated.TenantId, updated.AppId, updated.ServerId, updated.PlayerId, updated.NotificationId, updated.Kind.ToString(), updated.State.ToString(), updated.AttemptCount, null), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(updated.ServerId, updated.PlayerId, updated.NotificationId, updated.Kind.ToString(), updated.State.ToString(), updated.AttemptCount, null), cancellationToken).ConfigureAwait(false); affected++; } } @@ -481,12 +475,10 @@ public async Task> SweepExpiredAsync(long tenantId, long appId /// 与离线补发并发时不会重复投递。 /// /// - /// 租户标识。 - /// App 标识。 /// 本轮最多尝试条数(<= 0 时不重投)。 /// 取消令牌。 /// 本轮实际尝试条数。 - public async Task> RetryPendingAsync(long tenantId, long appId, int maxCount = 100, CancellationToken cancellationToken = default) + public async Task> RetryPendingAsync(int maxCount = 100, CancellationToken cancellationToken = default) { var limit = maxCount > 0 ? maxCount : 0; var attempted = 0; @@ -497,8 +489,8 @@ public async Task> RetryPendingAsync(long tenantId, long appId // (实测尝试数会从 1 直接跳到 3),重试预算形同虚设。故按本轮游标去重。 var attemptedIds = new HashSet(StringComparer.Ordinal); // 待重试优先于已失败:前者还差一次推送,后者可能已不可达。 - attempted += await RetryBatchAsync(tenantId, appId, OnlineNotificationState.Retrying, limit - attempted, attemptedIds, cancellationToken).ConfigureAwait(false); - attempted += await RetryBatchAsync(tenantId, appId, OnlineNotificationState.Failed, limit - attempted, attemptedIds, cancellationToken).ConfigureAwait(false); + attempted += await RetryBatchAsync(OnlineNotificationState.Retrying, limit - attempted, attemptedIds, cancellationToken).ConfigureAwait(false); + attempted += await RetryBatchAsync(OnlineNotificationState.Failed, limit - attempted, attemptedIds, cancellationToken).ConfigureAwait(false); } return OnlineResult.Ok(attempted); @@ -508,14 +500,12 @@ public async Task> RetryPendingAsync(long tenantId, long appId /// 过期兜底(仅由 调用):到期通知就地终结为 /// 并原样返回,绝不推给玩家。 /// - /// 租户标识。 - /// App 标识。 /// 接收者玩家标识。 /// 推送入口读到的当前通知快照。 /// 当前时刻(UTC 毫秒)。 /// 取消令牌。 /// 命中过期兜底时返回终结结果(含 CAS 失败后的收敛结果);未设有效期或未到期返回 null,由调用方继续推送主流程。 - private async Task> TerminateIfExpiredAsync(long tenantId, long appId, long playerId, OnlineNotification current, long nowUnixMilliseconds, CancellationToken cancellationToken) + private async Task> TerminateIfExpiredAsync(long playerId, OnlineNotification current, long nowUnixMilliseconds, CancellationToken cancellationToken) { if (current.ExpiresAtTime <= 0 || current.ExpiresAtTime > nowUnixMilliseconds) { @@ -538,10 +528,10 @@ private async Task> TerminateIfExpiredAsync(lon var terminated = await _store.ReplaceAsync(expired, current.State, current.AttemptCount, cancellationToken).ConfigureAwait(false); if (terminated == null) { - return await ConvergeAsync(tenantId, appId, playerId, current.NotificationId, cancellationToken).ConfigureAwait(false); + return await ConvergeAsync(playerId, current.NotificationId, cancellationToken).ConfigureAwait(false); } - await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(terminated.TenantId, terminated.AppId, terminated.ServerId, terminated.PlayerId, terminated.NotificationId, terminated.Kind.ToString(), terminated.State.ToString(), terminated.AttemptCount, null), cancellationToken).ConfigureAwait(false); + await _eventPublisher.PublishAsync(OnlineNotificationEvents.CreateNotificationChanged(terminated.ServerId, terminated.PlayerId, terminated.NotificationId, terminated.Kind.ToString(), terminated.State.ToString(), terminated.AttemptCount, null), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(terminated); } @@ -614,15 +604,13 @@ private async Task DispatchAsync(OnlineNotifi /// /// CAS 失败后的收敛点:重读当前事实并按其返回(不报错、不覆盖并发结果)。 /// - /// 租户标识。 - /// App 标识。 /// 接收者玩家标识。 /// 通知标识。 /// 取消令牌。 /// 当前生效的通知记录。 - private async Task> ConvergeAsync(long tenantId, long appId, long playerId, string notificationId, CancellationToken cancellationToken) + private async Task> ConvergeAsync(long playerId, string notificationId, CancellationToken cancellationToken) { - var current = await _store.FindAsync(tenantId, appId, playerId, notificationId, cancellationToken).ConfigureAwait(false); + var current = await _store.FindAsync(playerId, notificationId, cancellationToken).ConfigureAwait(false); if (current == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "通知不存在"); @@ -634,21 +622,19 @@ private async Task> ConvergeAsync(long tenantId /// /// 重投指定状态的一批通知(受剩余批次配额约束)。 /// - /// 租户标识。 - /// App 标识。 /// 目标状态。 /// 本轮剩余配额。 /// 本轮已处理的通知标识游标(同一轮内不得重复推送,跨批次去重)。 /// 取消令牌。 /// 本轮实际尝试条数。 - private async Task RetryBatchAsync(long tenantId, long appId, OnlineNotificationState state, int limit, HashSet attemptedIds, CancellationToken cancellationToken) + private async Task RetryBatchAsync(OnlineNotificationState state, int limit, HashSet attemptedIds, CancellationToken cancellationToken) { if (limit <= 0) { return 0; } - var batch = await _store.ListByStateAsync(tenantId, appId, state, cancellationToken).ConfigureAwait(false); + var batch = await _store.ListByStateAsync(state, cancellationToken).ConfigureAwait(false); var attempted = 0; foreach (var notification in batch) { @@ -664,7 +650,7 @@ private async Task RetryBatchAsync(long tenantId, long appId, OnlineNotific } attempted++; - await TryDispatchAsync(tenantId, appId, notification.PlayerId, notification.NotificationId, cancellationToken).ConfigureAwait(false); + await TryDispatchAsync(notification.PlayerId, notification.NotificationId, cancellationToken).ConfigureAwait(false); } return attempted; diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlinePunishment.cs b/Capability/GameFrameX.Capability.Online.Social/OnlinePunishment.cs index 901c5e9b3..3e62bbac5 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlinePunishment.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlinePunishment.cs @@ -49,15 +49,7 @@ public sealed class OnlinePunishment /// public string PunishmentId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置被处罚玩家。 @@ -153,8 +145,6 @@ public OnlinePunishment Copy() return new OnlinePunishment { PunishmentId = PunishmentId, - TenantId = TenantId, - AppId = AppId, PlayerId = PlayerId, Kind = Kind, Reason = Reason, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlinePunishmentRequest.cs b/Capability/GameFrameX.Capability.Online.Social/OnlinePunishmentRequest.cs index cf854d737..355063773 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlinePunishmentRequest.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlinePunishmentRequest.cs @@ -38,17 +38,7 @@ namespace GameFrameX.Capability.Online.Social; /// public sealed class OnlinePunishmentRequest { - /// - /// 获取或设置租户标识。 - /// - /// Gets or sets the tenant id. - public long TenantId { get; init; } - /// - /// 获取或设置 App 标识。 - /// - /// Gets or sets the app id. - public long AppId { get; init; } /// /// 获取或设置被处罚玩家标识。 diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlinePunishmentService.cs b/Capability/GameFrameX.Capability.Online.Social/OnlinePunishmentService.cs index caf639775..4a48d3a41 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlinePunishmentService.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlinePunishmentService.cs @@ -85,8 +85,6 @@ public async Task> ApplyAsync(OnlinePunishmentReq throw new ArgumentNullException(nameof(request)); } - var tenantId = request.TenantId; - var appId = request.AppId; var playerId = request.PlayerId; var kind = request.Kind; var reason = request.Reason; @@ -95,7 +93,7 @@ public async Task> ApplyAsync(OnlinePunishmentReq var adminId = request.AdminId; var adminCaseId = request.AdminCaseId; var correlationId = request.CorrelationId; - if (tenantId <= 0 || appId <= 0 || playerId <= 0) + if (playerId <= 0) { return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "处罚定位参数无效"); } @@ -121,8 +119,6 @@ public async Task> ApplyAsync(OnlinePunishmentReq var prototype = new OnlinePunishment { PunishmentId = "pun-" + Guid.NewGuid().ToString("N"), - TenantId = tenantId, - AppId = appId, PlayerId = playerId, Kind = kind, Reason = reason.Trim(), @@ -147,8 +143,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreatePunishmentChanged( stored.Kind.ToString(), stored.EffectiveAtTime, stored.ExpiresAtTime, - stored.TenantId, - stored.AppId, OnlineSocialEvents.PunishmentApplied, correlationId), cancellationToken).ConfigureAwait(false); } @@ -159,16 +153,14 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreatePunishmentChanged( /// /// 撤销处罚(重复撤销幂等成功)。 /// - /// 租户标识。 - /// App 标识。 /// 处罚标识。 /// 执行撤销的 Admin 标识。 /// 关联标识(可空)。 /// 取消令牌。 /// 撤销后的处罚记录。 - public async Task> RevokeAsync(long tenantId, long appId, string punishmentId, long adminId, string correlationId = null, CancellationToken cancellationToken = default) + public async Task> RevokeAsync(string punishmentId, long adminId, string correlationId = null, CancellationToken cancellationToken = default) { - if (tenantId <= 0 || appId <= 0 || string.IsNullOrEmpty(punishmentId)) + if (string.IsNullOrEmpty(punishmentId)) { return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "处罚定位参数无效"); } @@ -178,7 +170,7 @@ public async Task> RevokeAsync(long tenantId, lon return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "缺少执行撤销的管理员标识"); } - var punishment = await _graphStore.FindPunishmentAsync(tenantId, appId, punishmentId, cancellationToken).ConfigureAwait(false); + var punishment = await _graphStore.FindPunishmentAsync(punishmentId, cancellationToken).ConfigureAwait(false); if (punishment == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "处罚记录不存在"); @@ -201,7 +193,7 @@ public async Task> RevokeAsync(long tenantId, lon if (effective == null) { // CAS 失败 = 已被并发撤销 / 改写;重读后按当前事实返回,保证收敛。 - var current = await _graphStore.FindPunishmentAsync(tenantId, appId, punishmentId, cancellationToken).ConfigureAwait(false); + var current = await _graphStore.FindPunishmentAsync(punishmentId, cancellationToken).ConfigureAwait(false); if (current == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "处罚记录不存在"); @@ -216,8 +208,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreatePunishmentChanged( effective.Kind.ToString(), effective.EffectiveAtTime, effective.ExpiresAtTime, - effective.TenantId, - effective.AppId, OnlineSocialEvents.PunishmentRevoked, correlationId), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(effective); @@ -226,42 +216,38 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreatePunishmentChanged( /// /// 查询某玩家在给定时刻**确实生效**的处罚(Admin 复查与申诉核对的输入)。 /// - /// 租户标识。 - /// App 标识。 /// 被处罚玩家。 /// 判定时刻(UTC 毫秒;0 取系统时钟)。 /// 取消令牌。 /// 生效中的处罚列表。 - public async Task>> ListActiveAsync(long tenantId, long appId, long playerId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + public async Task>> ListActiveAsync(long playerId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) { - if (tenantId <= 0 || appId <= 0 || playerId <= 0) + if (playerId <= 0) { // 与 ApplyAsync / RevokeAsync 同口径:定位参数先校验,读接口不留免检口子。 return OnlineResult>.Fail(OnlineErrorCode.ParameterInvalid, "处罚定位参数无效"); } var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : Now(); - var active = await _graphStore.ListActivePunishmentsAsync(tenantId, appId, new ActivePunishmentQuery { PlayerId = playerId, NowUnixMilliseconds = now, }, cancellationToken).ConfigureAwait(false); + var active = await _graphStore.ListActivePunishmentsAsync(new ActivePunishmentQuery { PlayerId = playerId, NowUnixMilliseconds = now, }, cancellationToken).ConfigureAwait(false); return OnlineResult>.Ok(active); } /// /// 查询某玩家的全部处罚历史(含已撤销与已失效)。 /// - /// 租户标识。 - /// App 标识。 /// 被处罚玩家。 /// 取消令牌。 /// 处罚记录列表。 - public async Task>> ListHistoryAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public async Task>> ListHistoryAsync(long playerId, CancellationToken cancellationToken = default) { - if (tenantId <= 0 || appId <= 0 || playerId <= 0) + if (playerId <= 0) { // 与 ApplyAsync / RevokeAsync 同口径:定位参数先校验,读接口不留免检口子。 return OnlineResult>.Fail(OnlineErrorCode.ParameterInvalid, "处罚定位参数无效"); } - var all = await _graphStore.ListPunishmentsByPlayerAsync(tenantId, appId, playerId, cancellationToken).ConfigureAwait(false); + var all = await _graphStore.ListPunishmentsByPlayerAsync(playerId, cancellationToken).ConfigureAwait(false); return OnlineResult>.Ok(all); } diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineReportCase.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineReportCase.cs index 61e662d2b..960baa914 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineReportCase.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineReportCase.cs @@ -46,15 +46,7 @@ public sealed class OnlineReportCase /// public string ReportId { get; set; } - /// - /// 获取或设置租户标识。 - /// - public long TenantId { get; set; } - /// - /// 获取或设置 App 标识。 - /// - public long AppId { get; set; } /// /// 获取或设置举报人。 @@ -140,8 +132,6 @@ public OnlineReportCase Copy() return new OnlineReportCase { ReportId = ReportId, - TenantId = TenantId, - AppId = AppId, ReporterId = ReporterId, ReportedPlayerId = ReportedPlayerId, Scene = Scene, diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineReportRateLimiter.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineReportRateLimiter.cs index 4e6f0acce..2a2e071d0 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineReportRateLimiter.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineReportRateLimiter.cs @@ -51,7 +51,7 @@ public sealed class OnlineReportRateLimiter /// 并发保护锁。 private readonly object _syncRoot = new(); - /// 双窗计数桶:键 = (租户, App, 举报人)。 + /// 双窗计数桶:键 = 举报人。 private readonly Dictionary _windows = new(StringComparer.Ordinal); /// 上一次惰性清扫时刻(UTC 毫秒)。 @@ -83,15 +83,13 @@ public OnlineReportRateLimiter(int maximumSubmissionsPerMinute, int maximumSubmi /// /// 尝试获取一次举报提交配额(两窗都在额度内才同时计数;任一超限则两窗都不消耗)。 /// - /// 租户标识。 - /// App 标识。 /// 举报人。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 允许返回 true;任一窗口超限返回 false。 - public bool TryAcquire(long tenantId, long appId, long reporterId, long nowUnixMilliseconds = 0) + public bool TryAcquire(long reporterId, long nowUnixMilliseconds = 0) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var key = tenantId + ":" + appId + ":" + reporterId; + var key = reporterId.ToString(System.Globalization.CultureInfo.InvariantCulture); lock (_syncRoot) { diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineReportTransition.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineReportTransition.cs index 56fd21027..1e595f93d 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineReportTransition.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineReportTransition.cs @@ -39,17 +39,7 @@ namespace GameFrameX.Capability.Online.Social; /// public sealed class OnlineReportTransition { - /// - /// 获取或设置租户标识。 - /// - /// Gets or sets the tenant id. - public long TenantId { get; init; } - /// - /// 获取或设置 App 标识。 - /// - /// Gets or sets the app id. - public long AppId { get; init; } /// /// 获取或设置案件标识。 diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs index be9859fd8..c0783d35c 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs @@ -141,7 +141,7 @@ public sealed class OnlineSocialCapabilityModule : ICapabilityModule, IAdminActi private OnlineSocialOptions _options; /// - /// 族基建作用域(Register 期解析;迁移玩家作用域三元组来源)。 + /// 族基建作用域(Register 期解析;迁移玩家作用域区服键来源)。 /// private OnlineScope _scope; @@ -225,11 +225,11 @@ public void Register(CapabilityRegistrationContext context) var scope = _scope; context.AddTickJob("notification-expiry-sweep", async ct => { - await _notifications.SweepExpiredAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _notifications.SweepExpiredAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); context.AddTickJob("friend-request-expiry-sweep", async ct => { - await _friends.SweepExpiredAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _friends.SweepExpiredAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); } @@ -255,7 +255,7 @@ public async Task ActivateAsync(CapabilityActivationContext context, Cancellatio // 旧好友数据一次性迁移(显式开关,默认关闭;只读单向 + 幂等 + 逐条 containment + 汇总)。 if (_options.Friend.MigrateLegacyFriendData) { - await OnlineFriendLegacyMigration.MigrateAsync(_friends, _scope.TenantId, _scope.AppId, _scope.ServerId, cancellationToken).ConfigureAwait(false); + await OnlineFriendLegacyMigration.MigrateAsync(_friends, _scope.ServerId, cancellationToken).ConfigureAwait(false); } } diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialDecisionService.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialDecisionService.cs index 6bae18109..3b2cacdcc 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialDecisionService.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialDecisionService.cs @@ -96,14 +96,12 @@ public OnlineSocialDecisionService(IOnlineSocialGraphStore graphStore, IOnlineRe /// /// 裁决一次定向社交互动( 的实现:Party / Matchmaking 的唯一入口)。 /// - /// 租户标识。 - /// App 标识。 /// 发起互动的玩家。 /// 互动的目标玩家。 /// 互动目的(决定裁决力度)。 /// 取消令牌。 /// 裁决结果。 - public async Task EvaluateAsync(long tenantId, long appId, long fromPlayerId, long toPlayerId, OnlineSocialInteractionPurpose purpose, CancellationToken cancellationToken = default) + public async Task EvaluateAsync(long fromPlayerId, long toPlayerId, OnlineSocialInteractionPurpose purpose, CancellationToken cancellationToken = default) { if (fromPlayerId <= 0 || toPlayerId <= 0) { @@ -115,13 +113,13 @@ public async Task EvaluateAsync(long tenantId, long appId, return OnlineSocialDecision.Deny(OnlineErrorCode.ParameterInvalid, "不能与自己发生定向互动"); } - var selfDecision = await EvaluatePunishmentsAsync(tenantId, appId, fromPlayerId, purpose, cancellationToken).ConfigureAwait(false); + var selfDecision = await EvaluatePunishmentsAsync(fromPlayerId, purpose, cancellationToken).ConfigureAwait(false); if (!selfDecision.Allowed) { return selfDecision; } - var blocked = await _graphStore.IsBlockedEitherWayAsync(tenantId, appId, fromPlayerId, toPlayerId, cancellationToken).ConfigureAwait(false); + var blocked = await _graphStore.IsBlockedEitherWayAsync(fromPlayerId, toPlayerId, cancellationToken).ConfigureAwait(false); if (blocked) { // 双向生效、不指明方向:屏蔽是单向私密事实,泄露方向等于把「谁屏蔽了谁」透给被屏蔽方。 @@ -144,7 +142,7 @@ public Task EvaluateSendAsync(OnlineScope scope, Cancellat return Task.FromResult(OnlineSocialDecision.Deny(OnlineErrorCode.ParameterInvalid, "缺少玩家主体位")); } - return EvaluatePunishmentsAsync(scope.TenantId, scope.AppId, scope.PlayerId, OnlineSocialInteractionPurpose.DirectMessage, cancellationToken); + return EvaluatePunishmentsAsync(scope.PlayerId, OnlineSocialInteractionPurpose.DirectMessage, cancellationToken); } /// @@ -169,7 +167,7 @@ public async Task> BlockAsync(OnlineScope scope, return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "被屏蔽玩家无效"); } - var existing = await _graphStore.FindBlockAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var existing = await _graphStore.FindBlockAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (existing != null) { return OnlineResult.Ok(existing); @@ -181,8 +179,6 @@ public async Task> BlockAsync(OnlineScope scope, EntryId = "blk-" + Guid.NewGuid().ToString("N"), OwnerId = scope.PlayerId, BlockedPlayerId = targetPlayerId, - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, Reason = reason ?? string.Empty, CreatedAtTime = now, @@ -199,8 +195,6 @@ public async Task> BlockAsync(OnlineScope scope, await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateBlockChanged( effective.OwnerId, effective.BlockedPlayerId, - effective.TenantId, - effective.AppId, effective.ServerId, OnlineSocialEvents.BlockAdded, correlationId), cancellationToken).ConfigureAwait(false); @@ -223,15 +217,13 @@ public async Task> UnblockAsync(OnlineScope scope, long targe return failure; } - var entry = await _graphStore.FindBlockAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); - var removed = await _graphStore.RemoveBlockAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var entry = await _graphStore.FindBlockAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var removed = await _graphStore.RemoveBlockAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (removed && entry != null) { await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateBlockChanged( entry.OwnerId, entry.BlockedPlayerId, - entry.TenantId, - entry.AppId, entry.ServerId, OnlineSocialEvents.BlockRemoved, correlationId), cancellationToken).ConfigureAwait(false); @@ -254,7 +246,7 @@ public async Task>> ListBlockedAsyn return failure; } - var entries = await _graphStore.ListBlocksAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var entries = await _graphStore.ListBlocksAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); return OnlineResult>.Ok(entries); } @@ -280,7 +272,7 @@ public async Task> MuteAsync(OnlineScope scope, lo return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "被静音玩家无效"); } - var existing = await _graphStore.FindMuteAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var existing = await _graphStore.FindMuteAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (existing != null) { return OnlineResult.Ok(existing); @@ -292,8 +284,6 @@ public async Task> MuteAsync(OnlineScope scope, lo EntryId = "mut-" + Guid.NewGuid().ToString("N"), OwnerId = scope.PlayerId, MutedPlayerId = targetPlayerId, - TenantId = scope.TenantId, - AppId = scope.AppId, ServerId = scope.ServerId, ExpiresAtTime = expiresAtTime, CreatedAtTime = now, @@ -309,8 +299,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateMuteChanged( effective.OwnerId, effective.MutedPlayerId, effective.ExpiresAtTime, - effective.TenantId, - effective.AppId, effective.ServerId, OnlineSocialEvents.MuteAdded, correlationId), cancellationToken).ConfigureAwait(false); @@ -333,16 +321,14 @@ public async Task> UnmuteAsync(OnlineScope scope, long target return failure; } - var entry = await _graphStore.FindMuteAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); - var removed = await _graphStore.RemoveMuteAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var entry = await _graphStore.FindMuteAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var removed = await _graphStore.RemoveMuteAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (removed && entry != null) { await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateMuteChanged( entry.OwnerId, entry.MutedPlayerId, entry.ExpiresAtTime, - entry.TenantId, - entry.AppId, entry.ServerId, OnlineSocialEvents.MuteRemoved, correlationId), cancellationToken).ConfigureAwait(false); @@ -365,7 +351,7 @@ public async Task>> ListMutedAsync(O return failure; } - var entries = await _graphStore.ListMutesAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var entries = await _graphStore.ListMutesAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); return OnlineResult>.Ok(entries); } @@ -384,7 +370,7 @@ public async Task> IsMutedAsync(OnlineScope scope, long targe return failure; } - var entry = await _graphStore.FindMuteAsync(scope.TenantId, scope.AppId, scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); + var entry = await _graphStore.FindMuteAsync(scope.PlayerId, targetPlayerId, cancellationToken).ConfigureAwait(false); if (entry == null) { return OnlineResult.Ok(false); @@ -441,7 +427,7 @@ public async Task> SubmitReportAsync(OnlineScope var now = Now(); // 频控先于新案件标识生成:超限不落案件、不发事件;合法提交尝试(含重复举报)都计数, // 防止脚本刷重复提交探测存储或绕过频控。 - if (!_reportRateLimiter.TryAcquire(scope.TenantId, scope.AppId, scope.PlayerId, now)) + if (!_reportRateLimiter.TryAcquire(scope.PlayerId, now)) { return OnlineResult.Fail(OnlineErrorCode.RateLimitExceeded, "举报提交过于频繁,请稍后再试"); } @@ -449,8 +435,6 @@ public async Task> SubmitReportAsync(OnlineScope var prototype = new OnlineReportCase { ReportId = "rpt-" + Guid.NewGuid().ToString("N"), - TenantId = scope.TenantId, - AppId = scope.AppId, ReporterId = scope.PlayerId, ReportedPlayerId = reportedPlayerId, Scene = scene, @@ -479,8 +463,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateReportChanged( effective.Reason.ToString(), effective.State.ToString(), effective.Resolution.ToString(), - effective.TenantId, - effective.AppId, correlationId), cancellationToken).ConfigureAwait(false); } @@ -503,7 +485,7 @@ public async Task> WithdrawReportAsync(OnlineScop return failure; } - var reportCase = await _reportStore.FindAsync(scope.TenantId, scope.AppId, reportId, cancellationToken).ConfigureAwait(false); + var reportCase = await _reportStore.FindAsync(reportId, cancellationToken).ConfigureAwait(false); if (reportCase == null || reportCase.ReporterId != scope.PlayerId) { // 反预言:非举报人看不到这条案件的存在。 @@ -527,7 +509,7 @@ public async Task>> ListMyReportsAs return failure; } - var cases = await _reportStore.ListByReporterAsync(scope.TenantId, scope.AppId, scope.PlayerId, cancellationToken).ConfigureAwait(false); + var cases = await _reportStore.ListByReporterAsync(scope.PlayerId, cancellationToken).ConfigureAwait(false); return OnlineResult>.Ok(cases); } @@ -544,20 +526,18 @@ public async Task> TransitionReportAsync(OnlineRe throw new ArgumentNullException(nameof(transition)); } - var tenantId = transition.TenantId; - var appId = transition.AppId; var reportId = transition.ReportId; var targetState = transition.TargetState; var resolution = transition.Resolution; var handlerAdminId = transition.HandlerAdminId; var adminCaseId = transition.AdminCaseId; var correlationId = transition.CorrelationId; - if (IsScopeLocatorInvalid(tenantId, appId) || string.IsNullOrEmpty(reportId)) + if (string.IsNullOrEmpty(reportId)) { return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "案件定位参数无效"); } - var reportCase = await _reportStore.FindAsync(tenantId, appId, reportId, cancellationToken).ConfigureAwait(false); + var reportCase = await _reportStore.FindAsync(reportId, cancellationToken).ConfigureAwait(false); if (reportCase == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "举报案件不存在"); @@ -569,35 +549,25 @@ public async Task> TransitionReportAsync(OnlineRe /// /// 按状态列出案件(Admin 待办队列输入)。 /// - /// 租户标识。 - /// App 标识。 /// 案件状态。 /// 取消令牌。 /// 案件列表。 - public async Task>> ListReportsByStateAsync(long tenantId, long appId, OnlineReportState state, CancellationToken cancellationToken = default) + public async Task>> ListReportsByStateAsync(OnlineReportState state, CancellationToken cancellationToken = default) { - if (IsScopeLocatorInvalid(tenantId, appId)) - { - // 与同族的 TransitionReportAsync 同口径:Admin 面的入口先校验定位参数,不留「读接口不校验」的口子。 - return OnlineResult>.Fail(OnlineErrorCode.ParameterInvalid, "案件定位参数无效"); - } - - var cases = await _reportStore.ListByStateAsync(tenantId, appId, state, cancellationToken).ConfigureAwait(false); + var cases = await _reportStore.ListByStateAsync(state, cancellationToken).ConfigureAwait(false); return OnlineResult>.Ok(cases); } /// /// 按玩家当前实际生效的处罚裁决(封禁拒绝全部目的,禁言只拒绝发言,未命中放行)。 /// - /// 租户标识。 - /// App 标识。 /// 被裁决玩家。 /// 互动目的。 /// 取消令牌。 /// 裁决结果。 - private async Task EvaluatePunishmentsAsync(long tenantId, long appId, long playerId, OnlineSocialInteractionPurpose purpose, CancellationToken cancellationToken) + private async Task EvaluatePunishmentsAsync(long playerId, OnlineSocialInteractionPurpose purpose, CancellationToken cancellationToken) { - var active = await _graphStore.ListActivePunishmentsAsync(tenantId, appId, new ActivePunishmentQuery { PlayerId = playerId, NowUnixMilliseconds = Now(), }, cancellationToken).ConfigureAwait(false); + var active = await _graphStore.ListActivePunishmentsAsync(new ActivePunishmentQuery { PlayerId = playerId, NowUnixMilliseconds = Now(), }, cancellationToken).ConfigureAwait(false); foreach (var punishment in active) { if (punishment.Kind == OnlinePunishmentKind.Ban) @@ -672,7 +642,7 @@ private async Task> ApplyReportTransitionAsync(On if (effective == null) { // CAS 失败 = 已被并发裁决 / 撤回抢先;重读后按当前事实返回,保证收敛。 - var current = await _reportStore.FindAsync(reportCase.TenantId, reportCase.AppId, reportCase.ReportId, cancellationToken).ConfigureAwait(false); + var current = await _reportStore.FindAsync(reportCase.ReportId, cancellationToken).ConfigureAwait(false); if (current == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "举报案件不存在"); @@ -689,8 +659,6 @@ await _eventPublisher.PublishAsync(OnlineSocialEvents.CreateReportChanged( effective.Reason.ToString(), effective.State.ToString(), effective.Resolution.ToString(), - effective.TenantId, - effective.AppId, correlationId), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(effective); } @@ -716,17 +684,6 @@ private static OnlineResult ValidateScope(OnlineScope scope) return null; } - /// - /// 判定租户与 App 定位是否无效(Admin 命令面无玩家主体位,只能靠作用域二元组定位)。 - /// - /// 租户标识。 - /// App 标识。 - /// 无效返回 true。 - private static bool IsScopeLocatorInvalid(long tenantId, long appId) - { - return tenantId <= 0 || appId <= 0; - } - /// 取当前 UTC 毫秒时刻。 /// UTC 毫秒时间戳。 private static long Now() diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialEvents.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialEvents.cs index 73d225053..297970ee1 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialEvents.cs @@ -129,13 +129,11 @@ public static class OnlineSocialEvents /// 请求方。 /// 被请求方。 /// 关系状态名。 - /// 租户标识。 - /// App 标识。 /// 发起区服标识。 /// 变更动作(取本类型的 Friendship* 常量)。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateFriendshipChanged(string friendshipId, long requesterId, long addresseeId, string state, long tenantId, long appId, long serverId, string action, string correlationId = null) + public static OnlineEvent CreateFriendshipChanged(string friendshipId, long requesterId, long addresseeId, string state, long serverId, string action, string correlationId = null) { var payload = new FriendshipChangedPayload { @@ -159,8 +157,6 @@ public static OnlineEvent CreateFriendshipChanged(string friendshipId, long requ EventType = FriendshipChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, // 关系是双边的,信封只放得下一个玩家位,取请求方(方向所有者); // 双方标识都在载荷与审计字段中,消费端不得只看 PlayerId。 @@ -177,13 +173,11 @@ public static OnlineEvent CreateFriendshipChanged(string friendshipId, long requ /// /// 屏蔽发起人。 /// 被屏蔽玩家。 - /// 租户标识。 - /// App 标识。 /// 发起区服标识。 /// 变更动作(取本文 / )。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateBlockChanged(long ownerId, long blockedPlayerId, long tenantId, long appId, long serverId, string action, string correlationId = null) + public static OnlineEvent CreateBlockChanged(long ownerId, long blockedPlayerId, long serverId, string action, string correlationId = null) { var payload = new BlockChangedPayload { @@ -203,8 +197,6 @@ public static OnlineEvent CreateBlockChanged(long ownerId, long blockedPlayerId, EventType = BlockChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, // 屏蔽是单向私密事实:事件只投递给屏蔽发起人,不通知被屏蔽方(否则等于告知「你被谁屏蔽了」)。 PlayerId = ownerId, @@ -221,13 +213,11 @@ public static OnlineEvent CreateBlockChanged(long ownerId, long blockedPlayerId, /// 静音发起人。 /// 被静音玩家。 /// 静音失效时刻(UTC 毫秒;0 表示永久)。 - /// 租户标识。 - /// App 标识。 /// 发起区服标识。 /// 变更动作(取本文 / )。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateMuteChanged(long ownerId, long mutedPlayerId, long expiresAtTime, long tenantId, long appId, long serverId, string action, string correlationId = null) + public static OnlineEvent CreateMuteChanged(long ownerId, long mutedPlayerId, long expiresAtTime, long serverId, string action, string correlationId = null) { var payload = new MuteChangedPayload { @@ -249,8 +239,6 @@ public static OnlineEvent CreateMuteChanged(long ownerId, long mutedPlayerId, lo EventType = MuteChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = ownerId, Source = Source, @@ -270,11 +258,9 @@ public static OnlineEvent CreateMuteChanged(long ownerId, long mutedPlayerId, lo /// 举报原因名。 /// 案件状态名(举报案件的全部变更都是状态迁移,故动作即迁移后的状态名,与 同值)。 /// 处置结果名。 - /// 租户标识。 - /// App 标识。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateReportChanged(string reportId, long reporterId, long reportedPlayerId, string scene, string reason, string state, string resolution, long tenantId, long appId, string correlationId = null) + public static OnlineEvent CreateReportChanged(string reportId, long reporterId, long reportedPlayerId, string scene, string reason, string state, string resolution, string correlationId = null) { var payload = new ReportChangedPayload { @@ -304,8 +290,6 @@ public static OnlineEvent CreateReportChanged(string reportId, long reporterId, EventType = ReportChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, // 举报是 App 级事实,事件面向 Admin 待办队列聚合,不按区服切分。 PlayerId = reporterId, @@ -324,12 +308,10 @@ public static OnlineEvent CreateReportChanged(string reportId, long reporterId, /// 处罚种类名。 /// 生效时刻(UTC 毫秒)。 /// 失效时刻(UTC 毫秒;0 表示永久)。 - /// 租户标识。 - /// App 标识。 /// 变更动作(取本文 / )。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreatePunishmentChanged(string punishmentId, long playerId, string kind, long effectiveAtTime, long expiresAtTime, long tenantId, long appId, string action, string correlationId = null) + public static OnlineEvent CreatePunishmentChanged(string punishmentId, long playerId, string kind, long effectiveAtTime, long expiresAtTime, string action, string correlationId = null) { var payload = new PunishmentChangedPayload { @@ -355,8 +337,6 @@ public static OnlineEvent CreatePunishmentChanged(string punishmentId, long play EventType = PunishmentChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = playerId, Source = Source, @@ -374,12 +354,10 @@ public static OnlineEvent CreatePunishmentChanged(string punishmentId, long play /// 群组状态名。 /// 变更后成员数。 /// 变更后群记录版本号(消费端据此判断是否漏事件)。 - /// 租户标识。 - /// App 标识。 /// 变更动作(取本类型的 Group* 常量)。 /// 关联标识(可空)。 /// 事件信封实例。 - public static OnlineEvent CreateGroupChanged(string groupId, long ownerId, string state, int memberCount, int revision, long tenantId, long appId, string action, string correlationId = null) + public static OnlineEvent CreateGroupChanged(string groupId, long ownerId, string state, int memberCount, int revision, string action, string correlationId = null) { var payload = new GroupChangedPayload { @@ -405,8 +383,6 @@ public static OnlineEvent CreateGroupChanged(string groupId, long ownerId, strin EventType = GroupChanged, OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, // 群组是 App 级事实(跨区服成立),信封 PlayerId 取群主作为归属锚点。 PlayerId = ownerId, diff --git a/Configs/app_config.json b/Configs/app_config.json index 162bffa4d..2b5fad123 100644 --- a/Configs/app_config.json +++ b/Configs/app_config.json @@ -17,13 +17,10 @@ "EnableRuntime": true, "EnableAdminApi": true, "EnableRoles": ["Game"], - "UseGameDbStores": true, - "Settings": {} + "UseGameDbStores": true }, "MinModuleId": 10, "MaxModuleId": 9999, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex" }, @@ -43,8 +40,6 @@ "MetricsPort": 29490, "MinModuleId": 10000, "MaxModuleId": 19999, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex" }, @@ -53,8 +48,6 @@ "ServerId": 5050, "InnerHost": "0.0.0.0", "InnerPort": 25050, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -64,8 +57,6 @@ "ServerId": 5030, "InnerHost": "0.0.0.0", "InnerPort": 25030, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -75,8 +66,6 @@ "ServerId": 5040, "InnerHost": "0.0.0.0", "InnerPort": 25040, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -86,8 +75,6 @@ "ServerId": 5000, "InnerHost": "0.0.0.0", "InnerPort": 25000, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -97,8 +84,6 @@ "ServerId": 5510, "InnerHost": "0.0.0.0", "InnerPort": 25510, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -108,8 +93,6 @@ "ServerId": 5590, "InnerHost": "0.0.0.0", "InnerPort": 25590, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -119,8 +102,6 @@ "ServerId": 5550, "InnerHost": "0.0.0.0", "InnerPort": 25550, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -130,8 +111,6 @@ "ServerId": 5570, "InnerHost": "0.0.0.0", "InnerPort": 25570, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -141,8 +120,6 @@ "ServerId": 7010, "InnerHost": "0.0.0.0", "InnerPort": 27010, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -152,8 +129,6 @@ "ServerId": 7020, "InnerHost": "0.0.0.0", "InnerPort": 27020, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -163,8 +138,6 @@ "ServerId": 7030, "InnerHost": "0.0.0.0", "InnerPort": 27030, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -174,8 +147,6 @@ "ServerId": 7040, "InnerHost": "0.0.0.0", "InnerPort": 27040, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -185,8 +156,6 @@ "ServerId": 7610, "InnerHost": "0.0.0.0", "InnerPort": 27610, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -196,8 +165,6 @@ "ServerId": 7620, "InnerHost": "0.0.0.0", "InnerPort": 27620, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 @@ -207,8 +174,6 @@ "ServerId": 8000, "InnerHost": "0.0.0.0", "InnerPort": 28000, - "OnlineTenantId": 1, - "OnlineAppId": 1, "DataBaseUrl": "mongodb://127.0.0.1:37017/?authSource=admin", "DataBaseName": "gameframex", "HttpPort": 0 diff --git a/GameFrameX.Hotfix/Logic/OnlineAuthorizedScopeReader.cs b/GameFrameX.Hotfix/Logic/OnlineAuthorizedScopeReader.cs index 7e165f51f..c9c31acda 100644 --- a/GameFrameX.Hotfix/Logic/OnlineAuthorizedScopeReader.cs +++ b/GameFrameX.Hotfix/Logic/OnlineAuthorizedScopeReader.cs @@ -52,9 +52,9 @@ internal static class OnlineAuthorizedScopeReader { /// - /// 读取授权作用域三元组(玩家位为 0,由调用方按请求主体填充)。 + /// 读取授权作用域区服键(玩家位为 0,由调用方按请求主体填充;单键化 D4 后无租户位/App 位)。 /// - /// 输出:授权作用域三元组(提供者桥缺席 / 已撤销时为 null)。 + /// 输出:授权作用域(提供者桥缺席 / 已撤销时为 null)。 /// 提供者在场且可达返回 true;缺席 / 撤销返回 false。 internal static bool TryGetAuthorizedScope(out OnlineScope authorizedScope) { @@ -79,14 +79,14 @@ internal static bool TryGetAuthorizedScope(out OnlineScope authorizedScope) } /// - /// 组装生效作用域(授权三元组 + 请求玩家位)。 + /// 组装生效作用域(授权区服键 + 请求玩家位)。 /// /// 请求主体玩家标识(会话绑定身份或 Token 解析身份)。 /// 生效作用域;提供者桥缺席 / 已撤销时为 null。 internal static OnlineScope BuildRequestScope(long playerId) { return TryGetAuthorizedScope(out var authorizedScope) - ? new OnlineScope(authorizedScope.TenantId, authorizedScope.AppId, authorizedScope.ServerId, playerId) + ? new OnlineScope(authorizedScope.ServerId, playerId) : null; } } diff --git a/GameFrameX.Launcher/Online/HostPlayerDirectory.cs b/GameFrameX.Launcher/Online/HostPlayerDirectory.cs index 9bd3b1f0f..361eabd78 100644 --- a/GameFrameX.Launcher/Online/HostPlayerDirectory.cs +++ b/GameFrameX.Launcher/Online/HostPlayerDirectory.cs @@ -65,15 +65,13 @@ public sealed class HostPlayerDirectory : IOnlinePlayerDirectory /// /// Searches local players by name keyword: the trimmed keyword is matched with a contains query on PlayerState.Name through GameDb, /// results are ordered by player ID and truncated to limit. A blank keyword or non-positive limit returns an empty list without querying. - /// Tenant and app IDs are not used for filtering because the host database holds a single server's players; ServerId comes from the current global setting (0 when absent). + /// The host database holds a single server's players; ServerId comes from the current global setting (0 when absent). /// - /// 租户 ID(本宿主实现不参与过滤) / Tenant ID (not used for filtering by this host implementation) - /// 应用 ID(本宿主实现不参与过滤) / App ID (not used for filtering by this host implementation) /// 名称关键字 / Name keyword /// 最大返回条数 / Maximum number of entries to return /// 取消令牌,透传给数据库查询 / Cancellation token passed to the database query /// 匹配的玩家目录条目列表,可能为空 / Matching player directory entries, possibly empty - public async Task> SearchByNameAsync(long tenantId, long appId, string keyword, int limit, CancellationToken cancellationToken = default) + public async Task> SearchByNameAsync(string keyword, int limit, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(keyword) || limit <= 0) { @@ -98,14 +96,12 @@ public async Task> SearchByNameAsync(l /// /// /// Looks up local players by ID through GameDb.FindByIdsAsync, drops states whose name is null and orders by player ID. - /// A null or empty ID list returns an empty list without querying. Tenant and app IDs are not used for filtering; ServerId comes from the current global setting (0 when absent). + /// A null or empty ID list returns an empty list without querying. ServerId comes from the current global setting (0 when absent). /// - /// 租户 ID(本宿主实现不参与过滤) / Tenant ID (not used for filtering by this host implementation) - /// 应用 ID(本宿主实现不参与过滤) / App ID (not used for filtering by this host implementation) /// 待查询的玩家 ID 列表 / Player IDs to look up /// 取消令牌,透传给数据库查询 / Cancellation token passed to the database query /// 存在且有名称的玩家目录条目列表,可能为空 / Directory entries for existing named players, possibly empty - public async Task> FindAsync(long tenantId, long appId, IReadOnlyList playerIds, CancellationToken cancellationToken = default) + public async Task> FindAsync(IReadOnlyList playerIds, CancellationToken cancellationToken = default) { if (playerIds == null || playerIds.Count == 0) { diff --git a/GameFrameX.Launcher/Online/OnlineCapabilityCompositionRoot.cs b/GameFrameX.Launcher/Online/OnlineCapabilityCompositionRoot.cs index b81b44166..dc10260b7 100644 --- a/GameFrameX.Launcher/Online/OnlineCapabilityCompositionRoot.cs +++ b/GameFrameX.Launcher/Online/OnlineCapabilityCompositionRoot.cs @@ -165,8 +165,6 @@ public static async Task ComposeIfEnabledAsync(AppSetting setting) EnableRuntime = online.EnableRuntime, HostOptions = new CapabilityHostOptions { - TenantId = setting.OnlineTenantId, - AppId = setting.OnlineAppId, ServerId = setting.ServerId, }, Filter = new CapabilityAssemblyFilter(online.Capabilities, online.Disable), @@ -315,7 +313,7 @@ private static bool IsRoleEnabled(OnlineCapabilityOptions online, string serverT } /// - /// 重建族配置段原始 JSON(族级键 + Settings 节点):族脊柱包读取 TenantId / AppId / ServerId 落授权作用域, + /// 重建族配置段原始 JSON(族级键 + Settings 节点):族脊柱包读取 ServerId 落授权作用域(单键化 D4), /// 机制 Options 绑定器读取 Settings.<能力Id> 做能力级参数覆盖;JsonElement 底层 = System.Text.Json ///(GameFrameX.Foundation.Json 5.0.0 实证引用 System.Text.Json,配置装载同为 System.Text.Json 反序列化)。 /// @@ -326,8 +324,6 @@ private static JsonElement BuildFamilyConfigurationSection(AppSetting setting) var online = setting.Online; var section = new Dictionary { - ["TenantId"] = setting.OnlineTenantId, - ["AppId"] = setting.OnlineAppId, ["ServerId"] = setting.ServerId, ["EnableRuntime"] = online.EnableRuntime, ["EnableAdminApi"] = online.EnableAdminApi, diff --git a/GameFrameX.Templates/templates/gfx-online/{{Name}}/EmptyPlayerDirectory.cs b/GameFrameX.Templates/templates/gfx-online/{{Name}}/EmptyPlayerDirectory.cs index a7f5f3a57..f5c478ff0 100644 --- a/GameFrameX.Templates/templates/gfx-online/{{Name}}/EmptyPlayerDirectory.cs +++ b/GameFrameX.Templates/templates/gfx-online/{{Name}}/EmptyPlayerDirectory.cs @@ -53,13 +53,11 @@ public sealed class EmptyPlayerDirectory : IOnlinePlayerDirectory /// Template default: the minimal Online host has no player store, so every name search returns an empty list. /// Replace this class when wiring real player data. /// - /// 租户 ID(未使用) / Tenant ID (unused) - /// 应用 ID(未使用) / App ID (unused) /// 名称关键字(未使用) / Name keyword (unused) /// 最大返回条数(未使用) / Maximum number of entries (unused) /// 取消令牌(未使用) / Cancellation token (unused) /// 已完成的空列表任务 / Completed task with an empty list - public Task> SearchByNameAsync(long tenantId, long appId, string keyword, int limit, CancellationToken cancellationToken = default) + public Task> SearchByNameAsync(string keyword, int limit, CancellationToken cancellationToken = default) { return Task.FromResult>(new List()); } @@ -71,12 +69,10 @@ public Task> SearchByNameAsync(long te /// Template default: the minimal Online host has no player store, so every ID lookup returns an empty list. /// Replace this class when wiring real player data. /// - /// 租户 ID(未使用) / Tenant ID (unused) - /// 应用 ID(未使用) / App ID (unused) /// 玩家 ID 列表(未使用) / Player IDs (unused) /// 取消令牌(未使用) / Cancellation token (unused) /// 已完成的空列表任务 / Completed task with an empty list - public Task> FindAsync(long tenantId, long appId, IReadOnlyList playerIds, CancellationToken cancellationToken = default) + public Task> FindAsync(IReadOnlyList playerIds, CancellationToken cancellationToken = default) { return Task.FromResult>(new List()); } diff --git a/GameFrameX.Templates/templates/gfx-online/{{Name}}/Program.cs b/GameFrameX.Templates/templates/gfx-online/{{Name}}/Program.cs index da830f06f..60e3cc8bf 100644 --- a/GameFrameX.Templates/templates/gfx-online/{{Name}}/Program.cs +++ b/GameFrameX.Templates/templates/gfx-online/{{Name}}/Program.cs @@ -50,27 +50,21 @@ // 已引用但被过滤排除 → 4003 CapabilityNotInstalled(载荷带已装清单)。 // 增减能力 = 只增删 csproj ProjectReference(引用集即装配集,无按包装配代码)。 -// 授权作用域三元组(演示值)。接入配置管道时改走嵌套强类型段 "Online": { ... }(禁平铺键, -// 能力族全局约定 2026-10-12)。 -const long tenantId = 1; -const long appId = 1; +// 授权作用域区服键(演示值;单键化 D4 后作用域只剩 ServerId)。接入配置管道时改走嵌套强类型段 +// "Online": { ... }(禁平铺键,能力族全局约定 2026-10-12)。 const long serverId = 1; -// 族配置段(演示值):族脊柱包从段内读取授权作用域三元组(TenantId / AppId / ServerId,缺失或非正数 +// 族配置段(演示值):族脊柱包从段内读取授权作用域区服键(ServerId,缺失或非正数 // = 装配期 fail-fast);机制只把其中的 Settings 子对象按字段绑定到各能力 Options(空 = 全部走包内默认参数, // 未知能力 Id / 未知字段 / 类型不符 = fail-fast)。接入配置管道后把 "Online" 段整段读成 JsonElement 传入; // 族级键(EnableRoles / Capabilities / Disable / UseGameDbStores 等)由宿主自行解析后落到 options(如 options.Filter)。 var familyConfigurationSection = JsonSerializer.SerializeToElement(new { - TenantId = tenantId, - AppId = appId, ServerId = serverId, Settings = new { }, }); var options = new CapabilityCompositionOptions(familyConfigurationSection, new ConsoleCapabilityAssemblyLog()); -options.HostOptions.TenantId = tenantId; -options.HostOptions.AppId = appId; options.HostOptions.ServerId = serverId; // 管理面:UseAdminApi 挂 admin 组装(action 注册 + 双向对账 + 元端点 list_capability_services / diff --git a/GameFrameX.Utility/Setting/AppSetting.cs b/GameFrameX.Utility/Setting/AppSetting.cs index 5287a38ac..738dcaa43 100644 --- a/GameFrameX.Utility/Setting/AppSetting.cs +++ b/GameFrameX.Utility/Setting/AppSetting.cs @@ -773,26 +773,6 @@ private static string MaskSensitiveValue(string value) [SettingFieldLevel(SettingFieldLevel.RoleLevel)] public string OnlineAdminApiPrefix { get; set; } = "online/admin"; - /// - /// Online 运行时授权租户标识(与 ServerId 构成作用域三元组,跨租户请求按 3002 拒绝) - /// - /// - /// Online runtime authorized tenant id (part of the scope triple; cross-tenant requests are rejected with 3002). - /// - [Option(nameof(OnlineTenantId), DefaultValue = 0L, Description = "Online 运行时授权租户标识,与 OnlineAppId、ServerId 构成作用域三元组,默认值为 0(未配置)")] - [SettingFieldLevel(SettingFieldLevel.ProcessLevel)] - public long OnlineTenantId { get; set; } - - /// - /// Online 运行时授权应用标识(跨 App 请求按 3003 拒绝) - /// - /// - /// Online runtime authorized app id (cross-app requests are rejected with 3003). - /// - [Option(nameof(OnlineAppId), DefaultValue = 0L, Description = "Online 运行时授权应用标识,默认值为 0(未配置)")] - [SettingFieldLevel(SettingFieldLevel.ProcessLevel)] - public long OnlineAppId { get; set; } - /// /// Online 能力配置段(角色配置内嵌套 "Online" 节点的强类型绑定,C294 键集重定) /// 双闸 EnableRuntime / EnableAdminApi、EnableRoles 名单、Capabilities 白名单 / Disable 排除表、 diff --git a/README.md b/README.md index f030caa4c..5a6f8f271 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,12 @@ GameFrameX Server is a high-performance, cross-platform game server framework bu - Health check: `http://localhost:28080/health` (liveness probe: `/alive`) - Check console logs to confirm successful startup + **Zero-JSON golden path**: start the server without writing any `Online.Settings` and the sample + RPS chain (matchmaking → match → settlement → reward grant → leaderboard) works out of the box — + `MatchSettledBoardId` projects onto the default board `match-settled` (pre-created during + assembly). To turn the projection off, explicitly blank + `online-competition.LeaderboardProjection.MatchSettledBoardId` under `Online.Settings`. + ### SQLite Provider Boundaries SQLite (`--DatabaseProvider=Sqlite`) is positioned for quick starts, development evaluation, and diff --git a/README.zh-CN.md b/README.zh-CN.md index 413c027cc..e2954197e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -157,6 +157,8 @@ GameFrameX Server 是基于 C# .NET 10.0 开发的高性能、跨平台游戏服 - 健康检查:`http://localhost:28080/health`(存活探针:`/alive`) - 查看控制台日志确认启动成功 + **零 JSON 默认通(黄金路径)**:不写任何 `Online.Settings` 配置直接起服,RPS 样例对局全链(撮合 → 对局 → 结算 → 发奖 → 上榜)默认贯通——`MatchSettledBoardId` 默认投影到默认榜 `match-settled`(装配期自动预建);如需关闭投影,在 `Online.Settings` 中将 `online-competition.LeaderboardProjection.MatchSettledBoardId` 显式置空即可。 + --- ## 使用示例 diff --git a/Tests/GameFrameX.Hotfix.Tests/FriendDomainBridgeTests.cs b/Tests/GameFrameX.Hotfix.Tests/FriendDomainBridgeTests.cs index acb3afdce..fdfec66e4 100644 --- a/Tests/GameFrameX.Hotfix.Tests/FriendDomainBridgeTests.cs +++ b/Tests/GameFrameX.Hotfix.Tests/FriendDomainBridgeTests.cs @@ -89,8 +89,6 @@ await HotfixBridgeHarness.RunWithFriendDomainAsync(face, async runtime => // 作用域玩家位 = 会话 playerId(R2),请求体 / 授权提供者的玩家位均不可覆盖。 Assert.NotNull(face.LastListFriendsScope); Assert.Equal(PlayerOne, face.LastListFriendsScope.PlayerId); - Assert.Equal(HotfixBridgeStubScopeProvider.TenantId, face.LastListFriendsScope.TenantId); - Assert.Equal(HotfixBridgeStubScopeProvider.AppId, face.LastListFriendsScope.AppId); Assert.Equal(HotfixBridgeStubScopeProvider.ServerId, face.LastListFriendsScope.ServerId); }); } diff --git a/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj b/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj index a9ce58c55..19a8f5f12 100644 --- a/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj +++ b/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj @@ -21,6 +21,15 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs b/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs new file mode 100644 index 000000000..05c7131a3 --- /dev/null +++ b/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs @@ -0,0 +1,198 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and related international regulations. +// 使用本项目须严格遵守相关法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with relevant 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 at the root 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 legal 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://www.cnb.cool/GameFrameX +// CNB Repository: https://www.cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Hosting.Core; +using GameFrameX.Capability.Online.Abstractions; +using GameFrameX.Capability.Online.Operations.HotfixRollback; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Competition.Leaderboard; +using GameFrameX.Hotfix.Logic.Game.RockPaperScissors; +using GameFrameX.Hotfix.Logic.Player.Friend; +using GameFrameX.Hotfix.Logic.ServerRole.Match; +using GameFrameX.Proto.Proto; +using Xunit; + +namespace GameFrameX.Hotfix.Tests; + +/// +/// 黄金路径桥断言(C460:好友(C244)→撮合(C246)→对局→上榜 全链经 Hotfix 桥薄适配器走通): +/// 真实 Online 能力族组合(零 Settings JSON——默认投影开箱即通),好友桥建立关系 → 撮合桥双玩家入队 → +/// 对局桥开局 / 出拳决胜 → 结算发奖投影 → 默认榜出现条目。桥契约槽位是进程级静态状态,入 +/// 与其余域桥用例串行。 +/// +[Collection(HotfixBridgeTestCollection.Name)] +public sealed class GoldenPathBridgeChainTests +{ + /// 测试区服标识(族配置段一致)。 + private const long ServerId = 1001; + + /// 玩家一(好友请求方 / 胜方,连出石头两轮)。 + private const long PlayerOne = 1001; + + /// 玩家二(好友接受方 / 负方,连出剪刀两轮)。 + private const long PlayerTwo = 1002; + + /// 房间标识(确定性对局标识派生入参)。 + private const long RoomId = 5001; + + /// 局号(同房同局幂等)。 + private const int Round = 1; + + /// 驱动的最大 tick 轮数(每轮覆盖撮合 / 对局 / 结算 / 投影重投 job)。 + private const int MaxTickRounds = 10; + + /// + /// 验证零 JSON 默认配置下桥全链:好友桥 → 撮合桥 → 对局桥 → 结算发奖 → 默认榜条目出现。 + /// + [Fact] + public async Task GoldenPath_ZeroSettings_FriendBridge_MatchBridge_RpsMatch_ProjectsOntoDefaultBoard() + { + CapabilityRuntime runtime = null; + try + { + var section = JsonDocument.Parse("{\"ServerId\":1001}").RootElement.Clone(); + var options = new CapabilityCompositionOptions(section, new HotfixBridgeAssemblyLog()) + { + HostOptions = new CapabilityHostOptions { ServerId = ServerId, SchedulerIntervalMilliseconds = 3600000, }, + Filter = new CapabilityAssemblyFilter(new[] { "online-foundation", "online-social", "online-matchmaking", "online-match", "online-assets", "online-competition" }), + }; + options.Override(new EmptyPlayerDirectoryStub()); + options.Override(new NoopHotfixRollbackExecutorStub()); + + runtime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), options); + await runtime.Host.StartAsync(); + + // —— 好友桥(C244):请求 → 接受 → 双方好友列表可见。 + var sendRequest = new RespFriendSendRequest(); + await FriendDomainBridge.SendRequestAsync(PlayerOne, PlayerTwo, sendRequest); + Assert.Equal(0, sendRequest.ErrorCode); + + var accept = new RespFriendAccept(); + await FriendDomainBridge.AcceptAsync(PlayerTwo, PlayerOne, accept); + Assert.Equal(0, accept.ErrorCode); + + var friendList = new RespFriendList(); + await FriendDomainBridge.QueryFriendListAsync(PlayerOne, friendList); + Assert.Equal(0, friendList.ErrorCode); + Assert.Contains(friendList.Friends, friend => friend.PlayerId == PlayerTwo); + + // —— 撮合桥(C246):双玩家入队 1v1 匹配池。 + foreach (var player in new[] { PlayerOne, PlayerTwo }) + { + var enqueueResponse = new RespMatchEnqueue(); + await MatchDomainBridge.EnqueueAsync(player, new ReqMatchEnqueue { Mode = MatchMode.OneVsOne, Rating = 1000, }, enqueueResponse); + Assert.Equal(0, enqueueResponse.ErrorCode); + } + + // —— 对局桥:开局(确定性对局标识)+ 双方各两轮出拳(石头胜剪刀两轮 = 决胜)。 + Assert.True(RockPaperScissorsMatchBridge.IsBridgeEnabled, "online-match 装配后对局桥应在场接管"); + + var startResponse = new RespStartRoomGame(); + var handled = await RockPaperScissorsMatchBridge.TryStartRoomGameAsync(PlayerOne, RoomId, Round, new List { PlayerOne, PlayerTwo }, startResponse); + Assert.True(handled); + Assert.Equal(0, startResponse.ErrorCode); + + for (var roundIndex = 0; roundIndex < 2; roundIndex++) + { + foreach (var player in new[] { PlayerOne, PlayerTwo }) + { + var gesture = player == PlayerOne ? (int)RockPaperScissorsGesture.Rock : (int)RockPaperScissorsGesture.Scissors; + var submitResponse = new RespSubmitRockPaperScissorsGesture(); + var (gestureHandled, _) = await RockPaperScissorsMatchBridge.TrySubmitGestureAsync(player, RoomId, Round, gesture, submitResponse); + Assert.True(gestureHandled); + Assert.Equal(0, submitResponse.ErrorCode); + } + + // 本轮双方已提交:驱动一轮 tick 裁决本轮,开启下一轮。 + await runtime.Host.Scheduler.TickAsync(); + } + + // —— 结算 → 发奖 → 投影:显式驱动调度轮直至默认榜出现条目。 + var leaderboardStore = runtime.Host.Services.GetService(); + OnlineLeaderboardEntry winnerEntry = null; + for (var tickRound = 0; tickRound < MaxTickRounds; tickRound++) + { + await runtime.Host.Scheduler.TickAsync(); + winnerEntry = await leaderboardStore.FindEntryAsync(OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, PlayerOne); + if (winnerEntry != null) + { + break; + } + } + + Assert.NotNull(winnerEntry); + var loserEntry = await leaderboardStore.FindEntryAsync(OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, PlayerTwo); + Assert.NotNull(loserEntry); + Assert.True(winnerEntry.Score >= loserEntry.Score, "winner score (" + winnerEntry.Score + ") should rank above loser score (" + loserEntry.Score + ")"); + } + finally + { + if (runtime != null) + { + await runtime.StopAsync(); + } + } + } + + /// + /// 空玩家目录桩(社交能力的展示名检索宿主扩展点:黄金路径不消费搜索结果)。 + /// + private sealed class EmptyPlayerDirectoryStub : IOnlinePlayerDirectory + { + /// 按名检索恒返回空(黄金路径不消费)。 + public Task> SearchByNameAsync(string keyword, int limit, CancellationToken cancellationToken = default) + { + return Task.FromResult>(Array.Empty()); + } + + /// 按标识批量解析恒返回空(好友列表展示名回退标识字面量)。 + public Task> FindAsync(IReadOnlyList playerIds, CancellationToken cancellationToken = default) + { + return Task.FromResult>(Array.Empty()); + } + } + + /// + /// 空操作热更回滚执行器桩(Online 运营能力的宿主扩展点:黄金路径不触发回滚)。 + /// + private sealed class NoopHotfixRollbackExecutorStub : IOnlineHotfixRollbackExecutor + { + /// 恒完成(黄金路径不触发回滚)。 + public Task RollbackAsync(string targetVersion, CancellationToken cancellationToken = default) + { + return Task.CompletedTask; + } + } +} diff --git a/Tests/GameFrameX.Hotfix.Tests/HotfixBridgeHarness.cs b/Tests/GameFrameX.Hotfix.Tests/HotfixBridgeHarness.cs index 976863b69..4798111af 100644 --- a/Tests/GameFrameX.Hotfix.Tests/HotfixBridgeHarness.cs +++ b/Tests/GameFrameX.Hotfix.Tests/HotfixBridgeHarness.cs @@ -85,8 +85,6 @@ private static async Task RunAsync(Func body) { HostOptions = new CapabilityHostOptions { - TenantId = HotfixBridgeStubScopeProvider.TenantId, - AppId = HotfixBridgeStubScopeProvider.AppId, ServerId = HotfixBridgeStubScopeProvider.ServerId, }, }; diff --git a/Tests/GameFrameX.Hotfix.Tests/HotfixBridgeStubScopeProvider.cs b/Tests/GameFrameX.Hotfix.Tests/HotfixBridgeStubScopeProvider.cs index 7c7f4b24c..70692e491 100644 --- a/Tests/GameFrameX.Hotfix.Tests/HotfixBridgeStubScopeProvider.cs +++ b/Tests/GameFrameX.Hotfix.Tests/HotfixBridgeStubScopeProvider.cs @@ -36,11 +36,6 @@ namespace GameFrameX.Hotfix.Tests; /// public sealed class HotfixBridgeStubScopeProvider : IOnlineAuthorizedScopeProvider { - /// 桩授权租户标识。 - public const long TenantId = 1; - - /// 桩授权应用标识。 - public const long AppId = 1; /// 桩授权区服标识。 public const long ServerId = 1001; @@ -48,13 +43,13 @@ public sealed class HotfixBridgeStubScopeProvider : IOnlineAuthorizedScopeProvid /// /// 授权作用域实例(全宿主单例语义)。 /// - private readonly OnlineScope _authorizedScope = new OnlineScope(TenantId, AppId, ServerId); + private readonly OnlineScope _authorizedScope = new OnlineScope(ServerId); /// - /// 获取桩授权作用域,固定返回租户 1、应用 1、区服 1001 构成的单例作用域。 + /// 获取桩授权作用域,固定返回区服 1001 构成的单例作用域。 /// /// - /// Gets the stub authorized scope; always returns the singleton scope built from tenant 1, application 1 and server 1001. + /// Gets the stub authorized scope; always returns the singleton scope built from server 1001. /// /// 固定的桩授权作用域 / Fixed stub authorized scope public OnlineScope AuthorizedScope diff --git a/Tests/GameFrameX.Hotfix.Tests/MatchDomainBridgeTests.cs b/Tests/GameFrameX.Hotfix.Tests/MatchDomainBridgeTests.cs index 6baa7cafb..3b583eb10 100644 --- a/Tests/GameFrameX.Hotfix.Tests/MatchDomainBridgeTests.cs +++ b/Tests/GameFrameX.Hotfix.Tests/MatchDomainBridgeTests.cs @@ -72,8 +72,6 @@ await HotfixBridgeHarness.RunWithMatchDomainAsync(face, async runtime => // 作用域玩家位 = 会话 playerId(R2),授权提供者的玩家位不可覆盖。 Assert.NotNull(face.LastEnqueueScope); Assert.Equal(PlayerOne, face.LastEnqueueScope.PlayerId); - Assert.Equal(HotfixBridgeStubScopeProvider.TenantId, face.LastEnqueueScope.TenantId); - Assert.Equal(HotfixBridgeStubScopeProvider.AppId, face.LastEnqueueScope.AppId); Assert.Equal(HotfixBridgeStubScopeProvider.ServerId, face.LastEnqueueScope.ServerId); Assert.Equal((int)MatchMode.OneVsOne, face.LastEnqueueMode); Assert.Equal(1000, face.LastEnqueueRating); @@ -395,7 +393,7 @@ public Task> EnterAsync(OnlineScope scope, })); } - public Task> ResolveAssignmentAsync(long tenantId, long appId, string assignmentId, CancellationToken cancellationToken = default) + public Task> ResolveAssignmentAsync(string assignmentId, CancellationToken cancellationToken = default) { CallCount++; return Task.FromResult(OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "stub")); diff --git a/Tests/GameFrameX.Tests/Online/BlockingOnlineSessionStore.cs b/Tests/GameFrameX.Tests/Online/BlockingOnlineSessionStore.cs index 100ff1108..ae5e1524f 100644 --- a/Tests/GameFrameX.Tests/Online/BlockingOnlineSessionStore.cs +++ b/Tests/GameFrameX.Tests/Online/BlockingOnlineSessionStore.cs @@ -51,9 +51,9 @@ public BlockingOnlineSessionStore(IOnlineSessionStore inner = null) } /// 并发计数透传内层(读路径不悬挂)。 - public Task> CountNonTerminalByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public Task> CountNonTerminalByScopeAsync(long serverId, CancellationToken cancellationToken = default) { - return _inner.CountNonTerminalByScopeAsync(tenantId, appId, serverId, cancellationToken); + return _inner.CountNonTerminalByScopeAsync(serverId, cancellationToken); } /// 布防:指定会话的写入此后全部悬挂,直至 。 @@ -111,14 +111,12 @@ public Task FindByTokenHashAsync(string tokenHash, CancellationTo } /// 列出玩家非终态会话(透传)。 - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 取消令牌。 /// 非终态会话列表。 - public Task> ListActiveByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListActiveByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListActiveByPlayerAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListActiveByPlayerAsync(playerId, cancellationToken); } /// 列出全部非终态会话(透传)。 diff --git a/Tests/GameFrameX.Tests/Online/CapabilityAdminCompositionTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityAdminCompositionTests.cs index 33182b7ca..3c40f58a0 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityAdminCompositionTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityAdminCompositionTests.cs @@ -89,7 +89,7 @@ private static CapabilityCompositionOptions CreateAdminOptions(params string[] e var port = FindFreeAdminPort(); var options = new CapabilityCompositionOptions(default, new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1 }, + HostOptions = new CapabilityHostOptions { ServerId = 1 }, Filter = new CapabilityAssemblyFilter(enabledIds), }; options.UseAdminApi(adminApiOptions => @@ -280,7 +280,7 @@ public async Task Compose_InvalidAdminApiOptions_FailsFast() { var options = new CapabilityCompositionOptions(default, new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1 }, + HostOptions = new CapabilityHostOptions { ServerId = 1 }, Filter = new CapabilityAssemblyFilter(new[] { "mech-first" }), }; options.UseAdminApi(adminApiOptions => @@ -311,7 +311,7 @@ public async Task Compose_NoPlaneEnabled_FailsFast() { var options = new CapabilityCompositionOptions(default, new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1 }, + HostOptions = new CapabilityHostOptions { ServerId = 1 }, Filter = new CapabilityAssemblyFilter(new[] { "mech-first" }), EnableRuntime = false, }; diff --git a/Tests/GameFrameX.Tests/Online/CapabilityDependencyCheckTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityDependencyCheckTests.cs index f37970ae6..62520eafb 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityDependencyCheckTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityDependencyCheckTests.cs @@ -90,7 +90,7 @@ private static CapabilityCompositionOptions CreateOptions(CollectingCapabilityAs { return new CapabilityCompositionOptions(default, log) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1, }, + HostOptions = new CapabilityHostOptions { ServerId = 1, }, Filter = new CapabilityAssemblyFilter(enabledIds, disabledIds), }; } diff --git a/Tests/GameFrameX.Tests/Online/CapabilityHostServiceAndHookTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityHostServiceAndHookTests.cs index a2220ec2a..86cbd33e1 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityHostServiceAndHookTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityHostServiceAndHookTests.cs @@ -133,7 +133,7 @@ private static CapabilityCompositionOptions CreateOptions(params string[] enable { return new CapabilityCompositionOptions(default, new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1, }, + HostOptions = new CapabilityHostOptions { ServerId = 1, }, Filter = new CapabilityAssemblyFilter(enabledIds), }; } @@ -555,7 +555,7 @@ private static CapabilityCompositionOptions CreateOptionsWithLog(CollectingCapab { return new CapabilityCompositionOptions(default, log) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1, }, + HostOptions = new CapabilityHostOptions { ServerId = 1, }, Filter = new CapabilityAssemblyFilter(enabledIds), }; } diff --git a/Tests/GameFrameX.Tests/Online/CapabilityHostingTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityHostingTests.cs index d7e715d07..0df9e63ad 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityHostingTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityHostingTests.cs @@ -56,7 +56,7 @@ private static CapabilityCompositionOptions CreateOptions(CollectingCapabilityAs { return new CapabilityCompositionOptions(default, log) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1, }, + HostOptions = new CapabilityHostOptions { ServerId = 1, }, Filter = new CapabilityAssemblyFilter(enabledIds, disabledIds), }; } @@ -246,9 +246,9 @@ public void DiscoverModules_FindsSlotModulesFromAssembly() } } - /// - /// 宿主选项非法(作用域三元组非正)即组合失败。 - /// + /// + /// 宿主选项非法(区服键非正)即组合失败。 + /// [Fact] public void Compose_InvalidHostOptions_FailsFast() { @@ -256,7 +256,7 @@ public void Compose_InvalidHostOptions_FailsFast() try { var options = CreateOptions(new CollectingCapabilityAssemblyLog(), new[] { "mech-first", }); - options.HostOptions = new CapabilityHostOptions { TenantId = 0, AppId = 1, ServerId = 1, }; + options.HostOptions = new CapabilityHostOptions { ServerId = 0, }; var exception = Assert.Throws(() => Compose(options)); diff --git a/Tests/GameFrameX.Tests/Online/CapabilityLifecycleAndBridgeTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityLifecycleAndBridgeTests.cs index 96d22f9a5..2fab930f2 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityLifecycleAndBridgeTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityLifecycleAndBridgeTests.cs @@ -142,7 +142,7 @@ private static CapabilityCompositionOptions CreateOptions(CollectingCapabilityAs { return new CapabilityCompositionOptions(default, log) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1, }, + HostOptions = new CapabilityHostOptions { ServerId = 1, }, Filter = new CapabilityAssemblyFilter(enabledIds), }; } diff --git a/Tests/GameFrameX.Tests/Online/CapabilityOptionsBindingTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityOptionsBindingTests.cs index 133388a03..5ac484902 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityOptionsBindingTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityOptionsBindingTests.cs @@ -81,7 +81,7 @@ private static CapabilityCompositionOptions CreateOptions(string familySectionJs var section = familySectionJson == null ? default : FamilySection(familySectionJson); return new CapabilityCompositionOptions(section, new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1 }, + HostOptions = new CapabilityHostOptions { ServerId = 1 }, Filter = new CapabilityAssemblyFilter(enabledIds), }; } diff --git a/Tests/GameFrameX.Tests/Online/CapabilitySchedulerTests.cs b/Tests/GameFrameX.Tests/Online/CapabilitySchedulerTests.cs index bd43a2832..b33082a5e 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilitySchedulerTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilitySchedulerTests.cs @@ -623,7 +623,7 @@ public async Task Compose_SchedulerClockAndObserver_AreHonored() }; var options = new CapabilityCompositionOptions(default, new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1, SchedulerIntervalMilliseconds = LoopIntervalMilliseconds }, + HostOptions = new CapabilityHostOptions { ServerId = 1, SchedulerIntervalMilliseconds = LoopIntervalMilliseconds }, Filter = new CapabilityAssemblyFilter(new[] { "mech-first" }), SchedulerClock = clock, SchedulerObserver = observer, diff --git a/Tests/GameFrameX.Tests/Online/CapabilityServiceSharingTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityServiceSharingTests.cs index c5dd51376..a2b9aedc7 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityServiceSharingTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityServiceSharingTests.cs @@ -84,7 +84,7 @@ private static CapabilityCompositionOptions CreateOptions(params string[] enable { return new CapabilityCompositionOptions(default, new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1 }, + HostOptions = new CapabilityHostOptions { ServerId = 1 }, Filter = new CapabilityAssemblyFilter(enabledIds), }; } diff --git a/Tests/GameFrameX.Tests/Online/FailingAssetStore.cs b/Tests/GameFrameX.Tests/Online/FailingAssetStore.cs index 46cad74bc..b37ebf441 100644 --- a/Tests/GameFrameX.Tests/Online/FailingAssetStore.cs +++ b/Tests/GameFrameX.Tests/Online/FailingAssetStore.cs @@ -112,15 +112,13 @@ public Task ApplyAsync(OnlineAssetChangeBatch batch, Can /// /// Forwards directly to the inner store to find the wallet account snapshot. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 货币代码 / Currency code /// 取消令牌 / The cancellation token /// 内部存储返回的账户快照(从未变更时为 null)/ The wallet account snapshot from the inner store (null when no change has occurred) - public Task FindWalletAsync(long tenantId, long appId, long playerId, string currencyId, CancellationToken cancellationToken = default) + public Task FindWalletAsync(long playerId, string currencyId, CancellationToken cancellationToken = default) { - return _inner.FindWalletAsync(tenantId, appId, playerId, currencyId, cancellationToken); + return _inner.FindWalletAsync(playerId, currencyId, cancellationToken); } /// @@ -129,15 +127,13 @@ public Task FindWalletAsync(long tenantId, long appId, long /// /// Forwards directly to the inner store to find the inventory stack snapshot. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 道具标识 / Item id /// 取消令牌 / The cancellation token /// 内部存储返回的库存快照(从未变更时为 null)/ The inventory stack snapshot from the inner store (null when no change has occurred) - public Task FindInventoryAsync(long tenantId, long appId, long playerId, string itemId, CancellationToken cancellationToken = default) + public Task FindInventoryAsync(long playerId, string itemId, CancellationToken cancellationToken = default) { - return _inner.FindInventoryAsync(tenantId, appId, playerId, itemId, cancellationToken); + return _inner.FindInventoryAsync(playerId, itemId, cancellationToken); } /// @@ -146,14 +142,12 @@ public Task FindInventoryAsync(long tenantId, long appId, /// /// Forwards directly to the inner store to list all wallet account snapshots of the player. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌 / The cancellation token /// 内部存储返回的账户快照列表 / The wallet account snapshot list from the inner store - public Task> ListWalletAccountsAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListWalletAccountsAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListWalletAccountsAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListWalletAccountsAsync(playerId, cancellationToken); } /// @@ -162,14 +156,12 @@ public Task> ListWalletAccountsAsync(long ten /// /// Forwards directly to the inner store to list all inventory stack snapshots of the player. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌 / The cancellation token /// 内部存储返回的库存快照列表 / The inventory stack snapshot list from the inner store - public Task> ListInventoryStacksAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListInventoryStacksAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListInventoryStacksAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListInventoryStacksAsync(playerId, cancellationToken); } /// @@ -206,29 +198,25 @@ public Task> FindLedgerEntriesByTransactionIdAs /// /// Forwards directly to the inner store to sum signed ledger deltas per asset. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌 / The cancellation token /// 内部存储返回的各资产账本累加 / The per-asset ledger sums from the inner store - public Task> SumLedgerDeltasByAssetAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> SumLedgerDeltasByAssetAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.SumLedgerDeltasByAssetAsync(tenantId, appId, playerId, cancellationToken); + return _inner.SumLedgerDeltasByAssetAsync(playerId, cancellationToken); } /// - /// 直接转发内部存储列举 (租户, App) 下发生过资产活动的玩家。 + /// 直接转发内部存储列举发生过资产活动的玩家。 /// /// - /// Forwards directly to the inner store to list players with asset activity under the (tenant, app) scope. + /// Forwards directly to the inner store to list players with asset activity. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 取消令牌 / The cancellation token /// 内部存储返回的玩家标识列表 / The player id list from the inner store - public Task> ListPlayerIdsAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListPlayerIdsAsync(CancellationToken cancellationToken = default) { - return _inner.ListPlayerIdsAsync(tenantId, appId, cancellationToken); + return _inner.ListPlayerIdsAsync(cancellationToken); } } } diff --git a/Tests/GameFrameX.Tests/Online/FriendBridgeVerificationSeed.cs b/Tests/GameFrameX.Tests/Online/FriendBridgeVerificationSeed.cs index 6a1baa82e..1d8bff09b 100644 --- a/Tests/GameFrameX.Tests/Online/FriendBridgeVerificationSeed.cs +++ b/Tests/GameFrameX.Tests/Online/FriendBridgeVerificationSeed.cs @@ -82,13 +82,13 @@ public static async Task SeedAsync(CapabilityHost host, IReadOnlyList continue; } - var requested = await friends.RequestAsync(new OnlineScope(host.TenantId, host.AppId, host.ServerId, requesterId), friendPlayerId); + var requested = await friends.RequestAsync(new OnlineScope(host.ServerId, requesterId), friendPlayerId); if (!requested.IsSuccess) { continue; } - var accepted = await friends.AcceptAsync(new OnlineScope(host.TenantId, host.AppId, host.ServerId, friendPlayerId), requested.Data.FriendshipId); + var accepted = await friends.AcceptAsync(new OnlineScope(host.ServerId, friendPlayerId), requested.Data.FriendshipId); if (!accepted.IsSuccess && accepted.Code != OnlineErrorCode.StateOperationForbidden) { continue; diff --git a/Tests/GameFrameX.Tests/Online/GameDbOnlineFriendStoreBackfillRaceTests.cs b/Tests/GameFrameX.Tests/Online/GameDbOnlineFriendStoreBackfillRaceTests.cs index 57dcdd6f6..6b4b386e6 100644 --- a/Tests/GameFrameX.Tests/Online/GameDbOnlineFriendStoreBackfillRaceTests.cs +++ b/Tests/GameFrameX.Tests/Online/GameDbOnlineFriendStoreBackfillRaceTests.cs @@ -50,8 +50,6 @@ namespace GameFrameX.Tests.Online; [Collection(nameof(GameDbStaticStateCollection))] public sealed class GameDbOnlineFriendStoreBackfillRaceTests : IDisposable { - private const long TenantId = 1; - private const long AppId = 10; /// /// 构造函数:重置门面静态状态,避免与其它用例互相影响。 @@ -87,7 +85,7 @@ public async Task UpdateState_BackfillLostToConcurrentWriter_ShouldNotApplyIlleg GameDb.SetDefault("friend_race_db"); var store = new GameDbOnlineFriendStore(); - var updated = await store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition + var updated = await store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = "fs-legacy-race", ExpectedState = OnlineFriendshipState.Requested, diff --git a/Tests/GameFrameX.Tests/Online/GameDbOnlineFriendStorePersistenceTests.cs b/Tests/GameFrameX.Tests/Online/GameDbOnlineFriendStorePersistenceTests.cs index 60ea2d984..1963977ba 100644 --- a/Tests/GameFrameX.Tests/Online/GameDbOnlineFriendStorePersistenceTests.cs +++ b/Tests/GameFrameX.Tests/Online/GameDbOnlineFriendStorePersistenceTests.cs @@ -36,7 +36,7 @@ namespace GameFrameX.Tests.Online; using GameFrameX.DataBase; using GameFrameX.DataBase.Abstractions; using GameFrameX.DataBase.Sqlite; -using Xunit; +using GameFrameX.Capability.Online.Abstractions.Keys; /// /// 好友关系 GameDb 适配层测试。 @@ -46,7 +46,7 @@ namespace GameFrameX.Tests.Online; /// the static GameDb facade over embedded SQLite (in-memory mode) and anchor the store contract: /// create-if-absent returning the existing record without overwriting, undirected-pair lookup in /// both directions, CAS state transitions, renewal rewriting state/direction/expiry together, -/// per-player and per-state listings with tenant isolation, and soft-deleted records leaving the +/// per-player and per-state listings, and soft-deleted records leaving the /// Requested listing. The restart-acceptance fact runs SQLite in file mode and simulates a process /// restart by closing the facade, re-initializing a fresh database service over the same file and /// constructing a brand-new adapter instance — the adapter holds no in-process data cache, so @@ -55,16 +55,6 @@ namespace GameFrameX.Tests.Online; [Collection("GameDbStaticStateCollection")] public sealed class GameDbOnlineFriendStorePersistenceTests { - /// - /// 测试作用域租户标识。 - /// - private const long TenantId = 7L; - - /// - /// 测试作用域 App 标识。 - /// - private const long AppId = 3L; - /// /// 门面初始化后必须归还(关闭 + 复位静态注册表;串行集合保证静态门面独占)。 /// @@ -117,8 +107,6 @@ private static OnlineFriendship BuildFriendship(long low, long high, OnlineFrien return new OnlineFriendship { FriendshipId = friendshipId, - TenantId = TenantId, - AppId = AppId, ServerId = 5, LowPlayerId = low, HighPlayerId = high, @@ -158,7 +146,7 @@ await WithSqliteFacadeAsync(async () => Assert.Equal(1001, duplicate.UpdatedAtTime); // 库内仅一行(ListByState 全状态面合计 1)。 - Assert.Single(await store.ListByPlayerAsync(TenantId, AppId, 11)); + Assert.Single(await store.ListByPlayerAsync(11)); }); } @@ -173,14 +161,13 @@ await WithSqliteFacadeAsync(async () => var store = new GameDbOnlineFriendStore(); await store.SaveIfAbsentAsync(BuildFriendship(11, 22, OnlineFriendshipState.Requested, "fs-1")); - var forward = await store.FindAsync(TenantId, AppId, 11, 22); - var backward = await store.FindAsync(TenantId, AppId, 22, 11); + var forward = await store.FindAsync(11, 22); + var backward = await store.FindAsync(22, 11); Assert.NotNull(forward); Assert.NotNull(backward); Assert.Equal("fs-1", forward.FriendshipId); Assert.Equal("fs-1", backward.FriendshipId); - Assert.Null(await store.FindAsync(TenantId, AppId, 11, 33)); - Assert.Null(await store.FindAsync(999, AppId, 11, 22)); + Assert.Null(await store.FindAsync(11, 33)); }); } @@ -196,7 +183,7 @@ await WithSqliteFacadeAsync(async () => var created = await store.SaveIfAbsentAsync(BuildFriendship(11, 22, OnlineFriendshipState.Requested, "fs-1")); // CAS 成功:Requested → Accepted,答复时刻回填。 - var accepted = await store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition + var accepted = await store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, @@ -210,7 +197,7 @@ await WithSqliteFacadeAsync(async () => Assert.Equal(5000, accepted.RespondedAtTime); // 期望态不符(仍以 Requested 为期望):返回 null,读回状态不变。 - var stale = await store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition + var stale = await store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, @@ -219,22 +206,13 @@ await WithSqliteFacadeAsync(async () => Responded = true, }); Assert.Null(stale); - var reloaded = await store.FindAsync(TenantId, AppId, 22, 11); + var reloaded = await store.FindAsync(22, 11); Assert.Equal(OnlineFriendshipState.Accepted, reloaded.State); Assert.Equal(5000, reloaded.UpdatedAtTime); - // 作用域不符:返回 null。 - Assert.Null(await store.UpdateStateAsync(999, AppId, new FriendshipStateTransition - { - FriendshipId = created.FriendshipId, - ExpectedState = OnlineFriendshipState.Accepted, - NewState = OnlineFriendshipState.Rejected, - NowUnixMilliseconds = 6000, - Responded = true, - })); // 记录不存在:返回 null。 - Assert.Null(await store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition + Assert.Null(await store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = "fs-missing", ExpectedState = OnlineFriendshipState.Requested, @@ -257,8 +235,8 @@ await WithSqliteFacadeAsync(async () => var store = new GameDbOnlineFriendStore(); var created = await store.SaveIfAbsentAsync(BuildFriendship(11, 22, OnlineFriendshipState.Requested, "fs-race")); - var first = store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, NewState = OnlineFriendshipState.Accepted, NowUnixMilliseconds = 5000, Responded = true, }); - var second = store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, NewState = OnlineFriendshipState.Accepted, NowUnixMilliseconds = 6000, Responded = true, }); + var first = store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, NewState = OnlineFriendshipState.Accepted, NowUnixMilliseconds = 5000, Responded = true, }); + var second = store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, NewState = OnlineFriendshipState.Accepted, NowUnixMilliseconds = 6000, Responded = true, }); var results = await Task.WhenAll(first, second); var winners = 0; @@ -273,7 +251,7 @@ await WithSqliteFacadeAsync(async () => Assert.Equal(1, winners); - var final = await store.FindAsync(TenantId, AppId, 11, 22); + var final = await store.FindAsync(11, 22); Assert.NotNull(final); Assert.Equal(OnlineFriendshipState.Accepted, final.State); @@ -299,7 +277,7 @@ await WithSqliteFacadeAsync(async () => var legacy = CreateFriendshipRow(9001, "fs-legacy", (int)OnlineFriendshipState.Requested, null, 1001); await GameDb.AddOrUpdateAsync(legacy); - var updated = await store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition { FriendshipId = "fs-legacy", ExpectedState = OnlineFriendshipState.Requested, NewState = OnlineFriendshipState.Accepted, NowUnixMilliseconds = 5000, Responded = true, }); + var updated = await store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = "fs-legacy", ExpectedState = OnlineFriendshipState.Requested, NewState = OnlineFriendshipState.Accepted, NowUnixMilliseconds = 5000, Responded = true, }); Assert.NotNull(updated); Assert.Equal(OnlineFriendshipState.Accepted, updated.State); @@ -321,7 +299,7 @@ await WithSqliteFacadeAsync(async () => var created = await store.SaveIfAbsentAsync(BuildFriendship(11, 22, OnlineFriendshipState.Requested, "fs-1")); // 先经 CAS 置为删除后的静止态(Removed)。 - await store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition + await store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Requested, @@ -331,7 +309,7 @@ await WithSqliteFacadeAsync(async () => }); // 重新发起:高标识侧为发起人,方向翻转 + 状态回 Requested + 有效期重置。 - var renewed = await store.RenewRequestAsync(TenantId, AppId, new FriendshipRenewal + var renewed = await store.RenewRequestAsync(new FriendshipRenewal { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Removed, @@ -348,7 +326,7 @@ await WithSqliteFacadeAsync(async () => Assert.Equal(12000, renewed.ExpiresAtTime); // 期望态不符:返回 null 且零写入。 - Assert.Null(await store.RenewRequestAsync(TenantId, AppId, new FriendshipRenewal + Assert.Null(await store.RenewRequestAsync(new FriendshipRenewal { FriendshipId = created.FriendshipId, ExpectedState = OnlineFriendshipState.Removed, @@ -357,7 +335,7 @@ await WithSqliteFacadeAsync(async () => NowUnixMilliseconds = 8000, ExpiresAtTime = 13000, })); - var reloaded = await store.FindAsync(TenantId, AppId, 11, 22); + var reloaded = await store.FindAsync(11, 22); Assert.Equal(OnlineFriendshipState.Requested, reloaded.State); Assert.Equal(22, reloaded.RequesterId); Assert.Equal(12000, reloaded.ExpiresAtTime); @@ -365,10 +343,10 @@ await WithSqliteFacadeAsync(async () => } /// - /// 玩家列举事实:低 / 高两侧均命中 + 跨租户隔离(他租户同对不串读)。 + /// 玩家列举事实:低 / 高两侧均命中 + 无关玩家不串读。 /// [Fact] - public async Task ListByPlayer_BothSidesAndTenantIsolation_ShouldFilter() + public async Task ListByPlayer_BothSides_ShouldFilterByPlayer() { await WithSqliteFacadeAsync(async () => { @@ -377,20 +355,13 @@ await WithSqliteFacadeAsync(async () => await store.SaveIfAbsentAsync(BuildFriendship(22, 33, OnlineFriendshipState.Requested, "fs-2")); // 双侧命中:22 同时在两条关系里,11 只在一条。 - Assert.Equal(2, (await store.ListByPlayerAsync(TenantId, AppId, 22)).Count); - var byLow = await store.ListByPlayerAsync(TenantId, AppId, 11); + Assert.Equal(2, (await store.ListByPlayerAsync(22)).Count); + var byLow = await store.ListByPlayerAsync(11); var single = Assert.Single(byLow); Assert.Equal("fs-1", single.FriendshipId); - // 跨租户隔离:他租户同对关系不可见。 - var otherTenant = BuildFriendship(11, 22, OnlineFriendshipState.Requested, "fs-other-tenant"); - otherTenant.TenantId = 999; - await store.SaveIfAbsentAsync(otherTenant); - Assert.Single(await store.ListByPlayerAsync(TenantId, AppId, 11)); - Assert.Single(await store.ListByPlayerAsync(999, AppId, 11)); - // 无关玩家:空列表。 - Assert.Empty(await store.ListByPlayerAsync(TenantId, AppId, 44)); + Assert.Empty(await store.ListByPlayerAsync(44)); }); } @@ -407,11 +378,11 @@ await WithSqliteFacadeAsync(async () => await store.SaveIfAbsentAsync(BuildFriendship(33, 44, OnlineFriendshipState.Requested, "fs-2")); await store.SaveIfAbsentAsync(BuildFriendship(55, 66, OnlineFriendshipState.Accepted, "fs-3")); - Assert.Equal(2, (await store.ListByStateAsync(TenantId, AppId, OnlineFriendshipState.Requested)).Count); - Assert.Single(await store.ListByStateAsync(TenantId, AppId, OnlineFriendshipState.Accepted)); + Assert.Equal(2, (await store.ListByStateAsync(OnlineFriendshipState.Requested)).Count); + Assert.Single(await store.ListByStateAsync(OnlineFriendshipState.Accepted)); // 软删 fs-1:Requested 面只剩 fs-2,Removed 面出现 fs-1(行物理长存)。 - await store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition + await store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = "fs-1", ExpectedState = OnlineFriendshipState.Requested, @@ -419,11 +390,11 @@ await WithSqliteFacadeAsync(async () => NowUnixMilliseconds = 8000, Responded = false, }); - var requested = await store.ListByStateAsync(TenantId, AppId, OnlineFriendshipState.Requested); + var requested = await store.ListByStateAsync(OnlineFriendshipState.Requested); var remaining = Assert.Single(requested); Assert.Equal("fs-2", remaining.FriendshipId); - Assert.Single(await store.ListByStateAsync(TenantId, AppId, OnlineFriendshipState.Removed)); - Assert.NotNull(await store.FindAsync(TenantId, AppId, 11, 22)); + Assert.Single(await store.ListByStateAsync(OnlineFriendshipState.Removed)); + Assert.NotNull(await store.FindAsync(11, 22)); }); } @@ -446,18 +417,18 @@ await WithSqliteFileFacadeAsync(dataFile, "c244-friend-restart-a", async () => await WithSqliteFileFacadeAsync(dataFile, "c244-friend-restart-b", async () => { var store = new GameDbOnlineFriendStore(); - var reloaded = await store.FindAsync(TenantId, AppId, 22, 11); + var reloaded = await store.FindAsync(22, 11); Assert.NotNull(reloaded); Assert.Equal("fs-1", reloaded.FriendshipId); Assert.Equal(OnlineFriendshipState.Requested, reloaded.State); Assert.Equal(11, reloaded.RequesterId); Assert.Equal(9000, reloaded.ExpiresAtTime); - Assert.Single(await store.ListByStateAsync(TenantId, AppId, OnlineFriendshipState.Requested)); + Assert.Single(await store.ListByStateAsync(OnlineFriendshipState.Requested)); // 重启后语义不变:重复保存仍返回既有(不覆盖),CAS 仍可推进状态。 var duplicate = await store.SaveIfAbsentAsync(BuildFriendship(11, 22, OnlineFriendshipState.Accepted, "fs-other")); Assert.Equal("fs-1", duplicate.FriendshipId); - var accepted = await store.UpdateStateAsync(TenantId, AppId, new FriendshipStateTransition + var accepted = await store.UpdateStateAsync(new FriendshipStateTransition { FriendshipId = "fs-1", ExpectedState = OnlineFriendshipState.Requested, @@ -476,7 +447,7 @@ await WithSqliteFileFacadeAsync(dataFile, "c244-friend-restart-b", async () => } /// - /// 构造好友关系行(玩家对 11/22、租户 / App / 区服固定;行标识、状态、版本与更新时刻可变)。 + /// 构造好友关系行(玩家对 11/22、区服固定;行标识、状态、版本与更新时刻可变)。 /// /// 行 Id。 /// 关系标识。 @@ -489,10 +460,8 @@ internal static OnlineFriendshipRowState CreateFriendshipRow(long id, string fri return new OnlineFriendshipRowState { Id = id, - UniqueKey = "friend:" + TenantId + ":" + AppId + ":11:22", + UniqueKey = OnlineRowKey.Friendship(11, 22), FriendshipId = friendshipId, - TenantId = TenantId, - AppId = AppId, ServerId = 5, LowPlayerId = 11, HighPlayerId = 22, diff --git a/Tests/GameFrameX.Tests/Online/GameDbOnlineMatchSettlementStorePersistenceTests.cs b/Tests/GameFrameX.Tests/Online/GameDbOnlineMatchSettlementStorePersistenceTests.cs index 5ef4bbc30..cbb096a4a 100644 --- a/Tests/GameFrameX.Tests/Online/GameDbOnlineMatchSettlementStorePersistenceTests.cs +++ b/Tests/GameFrameX.Tests/Online/GameDbOnlineMatchSettlementStorePersistenceTests.cs @@ -33,11 +33,6 @@ namespace GameFrameX.Tests.Online; [Collection("GameDbStaticStateCollection")] public sealed class GameDbOnlineMatchSettlementStorePersistenceTests : IDisposable { - /// 租户标识。 - private const long TenantId = 11L; - - /// App 标识。 - private const long AppId = 4L; /// 临时根目录(文件库落点)。 private readonly string _tempRoot = Path.Combine(Path.GetTempPath(), "gfx-c408-outbox-" + Guid.NewGuid().ToString("N")); @@ -81,7 +76,7 @@ await WithSqliteFileFacadeAsync(dataFile, "c408-reopen", async () => var store = new GameDbOnlineMatchSettlementStore(); // 结果面恢复:按对局可查回既有结果,重复提交不覆盖。 - var existing = await store.FindByMatchAsync(TenantId, AppId, "match-1"); + var existing = await store.FindByMatchAsync("match-1"); Assert.NotNull(existing); Assert.Equal("result-1", existing.MatchResultId); var replay = await store.CommitWithOutboxAsync(BuildSampleResult("result-1-other", "match-1")); @@ -174,8 +169,6 @@ private static OnlineMatchResult BuildSampleResult(string matchResultId, string { MatchResultId = matchResultId, MatchId = matchId, - TenantId = TenantId, - AppId = AppId, ServerId = 9, Mode = 1, Region = 1, diff --git a/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs b/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs new file mode 100644 index 000000000..12d220169 --- /dev/null +++ b/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs @@ -0,0 +1,134 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and related international regulations. +// 使用本项目须严格遵守相关法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with relevant 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 at the root 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 legal 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://www.cnb.cool/GameFrameX +// CNB Repository: https://www.cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Scope; +using GameFrameX.Capability.Online.Assets; +using GameFrameX.Capability.Online.Competition.Leaderboard; +using GameFrameX.Capability.Online.Match; +using Xunit; + +namespace GameFrameX.Tests.Online +{ + /// + /// 黄金路径端到端验收(C460:Options 默认值开箱即通): + /// 零 Online JSON(不写 Settings 键)的真实族组合——RPS 对局(桥服务开局 / 出拳)→ + /// 结算管线(match-settlement-tick)→ Grant 幂等发奖 → Match.Settled 投影写默认榜, + /// 断言钱包余额与默认榜条目同时出现;显式空白覆盖关闭投影的反例见投影器组合测试。 + /// + [Collection(CapabilityRuntimeCollection.Name)] + public class GoldenPathDefaultOnTests + { + /// 玩家一(胜方,连出石头两轮)。 + private const long PlayerOne = 1001; + + /// 玩家二(负方,连出剪刀两轮)。 + private const long PlayerTwo = 1002; + + /// 房间标识(确定性对局标识派生入参)。 + private const long RoomId = 5001; + + /// 局号(同房同局幂等)。 + private const int Round = 1; + + /// 驱动的最大 tick 轮数(每轮覆盖 match-tick / match-settlement-tick / 投影重投 job)。 + private const int MaxTickRounds = 10; + + /// + /// 验证零 JSON 默认配置即通黄金路径:默认榜随装配预建,RPS 两轮决胜 → 结算 → 发奖 → 默认榜条目出现。 + /// + [Fact] + public async Task ZeroSettings_RpsMatch_Settles_Grants_And_ProjectsOntoDefaultBoard() + { + await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => + { + await runtime.Host.StartAsync(); + var services = runtime.Host.Services; + var scope = new OnlineScope(OnlineCapabilityTestHarness.ServerId); + + // 默认榜已随装配预建(ActivateAsync 查询-创建):Top 探针即成功。 + var probe = await services.GetService().GetTopAsync(scope, new OnlineLeaderboardTopQuery { LeaderboardId = OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, Count = 1, }); + Assert.True(probe.IsSuccess, probe.Message); + + // 对局:开局幂等 + 双方各两轮出拳(石头胜剪刀两轮 = 达到 WinTarget 决胜)。 + var bridge = services.GetService(); + var started = await bridge.StartRoomGameAsync(new OnlineScope(scope.ServerId, PlayerOne), RoomId, Round, new List { PlayerOne, PlayerTwo }); + Assert.True(started.IsSuccess, started.Message); + + for (var roundIndex = 0; roundIndex < 2; roundIndex++) + { + foreach (var player in new[] { PlayerOne, PlayerTwo }) + { + var gesture = player == PlayerOne ? (int)OnlineRockPaperScissorsMove.Rock : (int)OnlineRockPaperScissorsMove.Scissors; + var submitted = await bridge.SubmitGestureAsync(new OnlineScope(scope.ServerId, player), RoomId, Round, gesture); + Assert.True(submitted.IsSuccess, submitted.Message); + } + + // 本轮双方已提交:驱动一轮 tick 裁决本轮,开启下一轮。 + await runtime.Host.Scheduler.TickAsync(); + } + + // 结算 → 发奖 → 投影:显式驱动调度轮直至默认榜出现条目(事件订阅链同步投影,重投 job 兜底)。 + OnlineLeaderboardEntry winnerEntry = null; + for (var tickRound = 0; tickRound < MaxTickRounds; tickRound++) + { + await runtime.Host.Scheduler.TickAsync(); + winnerEntry = await services.GetService().FindEntryAsync(OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, PlayerOne); + if (winnerEntry != null) + { + break; + } + } + + // 发奖断言:胜方 +WinnerRewardAmount、负方 +ParticipantRewardAmount(样例币资产)。 + var assetStore = services.GetService(); + var winnerWallet = await assetStore.FindWalletAsync(PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId); + var loserWallet = await assetStore.FindWalletAsync(PlayerTwo, OnlineRockPaperScissorsGame.RewardAssetId); + Assert.NotNull(winnerWallet); + Assert.Equal(OnlineRockPaperScissorsGame.WinnerRewardAmount, winnerWallet.Balance); + Assert.NotNull(loserWallet); + Assert.Equal(OnlineRockPaperScissorsGame.ParticipantRewardAmount, loserWallet.Balance); + + // 上榜断言:默认榜出现双方条目(胜方分高在前)。 + Assert.NotNull(winnerEntry); + var loserEntry = await services.GetService().FindEntryAsync(OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, PlayerTwo); + Assert.NotNull(loserEntry); + Assert.True(winnerEntry.Score >= loserEntry.Score, "winner score (" + winnerEntry.Score + ") should rank above loser score (" + loserEntry.Score + ")"); + }, null, options => + { + options.Filter = new CapabilityAssemblyFilter(new[] { "online-foundation", "online-social", "online-matchmaking", "online-match", "online-assets", "online-competition" }); + options.HostOptions.SchedulerIntervalMilliseconds = 3600000; + }); + } + } +} diff --git a/Tests/GameFrameX.Tests/Online/HotfixManagerRollbackExecutorTests.cs b/Tests/GameFrameX.Tests/Online/HotfixManagerRollbackExecutorTests.cs index 128a892e9..d845f6c7a 100644 --- a/Tests/GameFrameX.Tests/Online/HotfixManagerRollbackExecutorTests.cs +++ b/Tests/GameFrameX.Tests/Online/HotfixManagerRollbackExecutorTests.cs @@ -59,11 +59,6 @@ namespace GameFrameX.Tests.Online; [Collection(HotfixManagerStaticStateCollection.Name)] public sealed class HotfixManagerRollbackExecutorTests : IDisposable { - /// 测试用租户标识。 - private const long TenantId = 9211; - - /// 测试用应用标识。 - private const long AppId = 9212; /// 本实例创建的版本目录(Dispose 统一最佳努力清理)。 private readonly List _createdVersions = new List(); @@ -118,7 +113,6 @@ private static OnlineHotfixRollbackRequest CreateRollbackRequest(string targetVe { return new OnlineHotfixRollbackRequest { - Scope = new OnlineScope(TenantId, AppId, 0), TargetVersion = targetVersion, OperatorId = "admin-001", OperatorName = "运维一号", @@ -137,13 +131,10 @@ private static OnlineHotfixProtocolManifest CreateManifest(string version) return new OnlineHotfixProtocolManifest { Version = version, - TenantId = TenantId, - AppId = AppId, Messages = new List(), RegisteredTime = 1_760_000_000_000L, }; } - /// /// 创建一个真实可装载的版本目录(拷贝 Operations 程序集为 GameFrameX.Hotfix.dll)。 /// @@ -343,19 +334,19 @@ public async Task RollbackAsync_ServiceFullChain_ForwardThenBackward_PointerAndL var v2 = NewLoadableVersion(); Assert.True((await service.RegisterAsync(CreateManifest(v1))).Data); Assert.True((await service.RegisterAsync(CreateManifest(v2))).Data); - Assert.True((await service.ActivateAsync(new OnlineScope(TenantId, AppId, 0), v1)).Data); + Assert.True((await service.ActivateAsync(v1)).Data); await LoadVersion(v1); // 向前:切到更新登记的 v2。 var forward = await service.RollbackAsync(CreateRollbackRequest(v2, "c248-full-forward")); Assert.True(forward.IsSuccess, forward.Message); - Assert.Equal(v2, (await store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal(v2, (await store.FindActiveAsync()).Version); Assert.Equal(ArtifactPath(v2), HotfixManager.HotfixAssembly.Location); // 向后:回滚到 v1。 var backward = await service.RollbackAsync(CreateRollbackRequest(v1, "c248-full-backward")); Assert.True(backward.IsSuccess, backward.Message); - Assert.Equal(v1, (await store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal(v1, (await store.FindActiveAsync()).Version); Assert.Equal(ArtifactPath(v1), HotfixManager.HotfixAssembly.Location); Assert.Equal(2, recorder.Filter(OnlineHotfixEvents.RolledBack).Count); @@ -373,14 +364,14 @@ public async Task RollbackAsync_ServiceFullChain_TargetNotOnDisk_Rejected8002Wit var ghost = NewMissingVersion(); Assert.True((await service.RegisterAsync(CreateManifest(v1))).Data); Assert.True((await service.RegisterAsync(CreateManifest(ghost))).Data); - Assert.True((await service.ActivateAsync(new OnlineScope(TenantId, AppId, 0), v1)).Data); + Assert.True((await service.ActivateAsync(v1)).Data); await LoadVersion(v1); var failure = await service.RollbackAsync(CreateRollbackRequest(ghost, "c248-ghost-target")); Assert.False(failure.IsSuccess); Assert.Equal(OnlineErrorCode.DependencyUnavailable, failure.Code); - Assert.Equal(v1, (await store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal(v1, (await store.FindActiveAsync()).Version); Assert.Equal(ArtifactPath(v1), HotfixManager.HotfixAssembly.Location); } @@ -412,13 +403,13 @@ public async Task RegisterWithUrlThenRollback_EndToEnd_ArtifactLandedAndSwitched Assert.True((await service.RegisterAsync(manifestV2)).Data); Assert.True(File.Exists(ArtifactPath(v2))); Assert.True(handler.CallCount >= 1); - Assert.True((await service.ActivateAsync(new OnlineScope(TenantId, AppId, 0), v1)).Data); + Assert.True((await service.ActivateAsync(v1)).Data); await LoadVersion(v1); var rollback = await service.RollbackAsync(CreateRollbackRequest(v2, "c248-e2e-switch")); Assert.True(rollback.IsSuccess, rollback.Message); - Assert.Equal(v2, (await store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal(v2, (await store.FindActiveAsync()).Version); Assert.Equal(ArtifactPath(v2), HotfixManager.HotfixAssembly.Location); } diff --git a/Tests/GameFrameX.Tests/Online/InterleavingLeaderboardStore.cs b/Tests/GameFrameX.Tests/Online/InterleavingLeaderboardStore.cs index 2c4ddb54a..b017c6dfe 100644 --- a/Tests/GameFrameX.Tests/Online/InterleavingLeaderboardStore.cs +++ b/Tests/GameFrameX.Tests/Online/InterleavingLeaderboardStore.cs @@ -130,14 +130,12 @@ public Task CreateAsync(OnlineLeaderboard leaderboard, Cancel /// /// Forwards directly to the inner store to find the leaderboard definition by scope. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 榜单标识 / Leaderboard id /// 取消令牌 / The cancellation token - /// 内部存储返回的榜单副本(不存在或跨作用域时为 null)/ The leaderboard copy from the inner store (null when missing or cross-scope) - public Task FindAsync(long tenantId, long appId, string leaderboardId, CancellationToken cancellationToken = default) + /// 内部存储返回的榜单副本(不存在时为 null)/ The leaderboard copy from the inner store (null when missing) + public Task FindAsync(string leaderboardId, CancellationToken cancellationToken = default) { - return _inner.FindAsync(tenantId, appId, leaderboardId, cancellationToken); + return _inner.FindAsync(leaderboardId, cancellationToken); } /// @@ -146,15 +144,13 @@ public Task FindAsync(long tenantId, long appId, string leade /// /// Forwards directly to the inner store to find a single player's entry. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 榜单标识 / Leaderboard id /// 玩家标识 / Player id /// 取消令牌 / The cancellation token /// 内部存储返回的条目副本(未上榜时为 null)/ The entry copy from the inner store (null when the player is unranked) - public Task FindEntryAsync(long tenantId, long appId, string leaderboardId, long playerId, CancellationToken cancellationToken = default) + public Task FindEntryAsync(string leaderboardId, long playerId, CancellationToken cancellationToken = default) { - return _inner.FindEntryAsync(tenantId, appId, leaderboardId, playerId, cancellationToken); + return _inner.FindEntryAsync(leaderboardId, playerId, cancellationToken); } /// diff --git a/Tests/GameFrameX.Tests/Online/MechanismTestScopeAdapter.cs b/Tests/GameFrameX.Tests/Online/MechanismTestScopeAdapter.cs index 5b7d3974d..46a99a85b 100644 --- a/Tests/GameFrameX.Tests/Online/MechanismTestScopeAdapter.cs +++ b/Tests/GameFrameX.Tests/Online/MechanismTestScopeAdapter.cs @@ -37,24 +37,24 @@ namespace GameFrameX.Tests.Online; /// -/// 机制测试作用域适配器(从请求体读三元组 + 恒放行——作用域守卫语义另有 Online 侧用例锚定)。 +/// 机制测试作用域适配器(从请求体读区服键 + 恒放行——作用域守卫语义另有 Online 侧用例锚定)。 /// public sealed class MechanismTestScopeAdapter : IAdminApiScopeAdapter { /// - /// 从管理面请求中读取声明的租户、应用、服务器三元组;读取成功时据此构造声明作用域并返回 true,否则输出 null 并返回 false。 + /// 从管理面请求中读取声明的区服键;读取成功时据此构造声明作用域并返回 true,否则输出 null 并返回 false。 /// /// - /// Reads the claimed tenant, app and server triple from the admin API request; on success builds the claimed scope and returns true, otherwise outputs null and returns false. + /// Reads the claimed server key from the admin API request; on success builds the claimed scope and returns true, otherwise outputs null and returns false. /// /// 管理面请求 / Admin API request /// 读取成功时为声明作用域,失败时为 null / Claimed scope on success, null on failure - /// 请求中带有完整三元组时为 true,否则为 false / true when the request carries the full triple, otherwise false + /// 请求中带有区服键时为 true,否则为 false / true when the request carries the server key, otherwise false public bool TryReadClaimedScope(AdminApiRequest request, out AdminApiClaimedScope claimedScope) { - if (request.TryReadClaimedScope(out var tenantId, out var appId, out var serverId)) + if (request.TryReadClaimedScope(out var serverId)) { - claimedScope = new AdminApiClaimedScope(tenantId, appId, serverId); + claimedScope = new AdminApiClaimedScope(serverId); return true; } diff --git a/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs index d37ed8db1..9e24bf7f7 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs @@ -136,7 +136,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => { var dispatcher = OnlineCapabilityTestHarness.CreateDispatcher(runtime.Host); - var envelopeJson = await dispatcher.DispatchAsync("query_compensation_queue", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); + var envelopeJson = await dispatcher.DispatchAsync("query_compensation_queue", "{\"ServerId\":1001}"); var innerJson = ReadInnerJson(envelopeJson); using (var document = JsonDocument.Parse(innerJson)) { @@ -159,7 +159,7 @@ public async Task Dispatch_UnknownAction_ShouldReturnInner4002() { await WithDispatcherAsync(async dispatcher => { - var envelope = await dispatcher.DispatchAsync("definitely_not_an_action", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); + var envelope = await dispatcher.DispatchAsync("definitely_not_an_action", "{\"ServerId\":1001}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ResourceNotFound); }); } @@ -191,14 +191,12 @@ await WithDispatcherAsync(async dispatcher => } /// - /// 验证跨租户 / 跨应用 / 跨区服分别返回 3002 / 3003 / 3004。 + /// 验证跨区服作用域返回 3004(单键化后不再产生 3002/3003)。 /// /// 请求体。 /// 期望业务码。 [Theory] - [InlineData("{\"TenantId\":2,\"AppId\":1,\"ServerId\":1001}", OnlineErrorCode.CrossTenantDenied)] - [InlineData("{\"TenantId\":1,\"AppId\":2,\"ServerId\":1001}", OnlineErrorCode.CrossAppDenied)] - [InlineData("{\"TenantId\":1,\"AppId\":1,\"ServerId\":2002}", OnlineErrorCode.ServerScopeDenied)] + [InlineData("{\"ServerId\":2002}", OnlineErrorCode.ServerScopeDenied)] public async Task Dispatch_ScopeMismatch_ShouldReturnGuardCode(string body, OnlineErrorCode expectedCode) { await WithDispatcherAsync(async dispatcher => @@ -217,7 +215,7 @@ public async Task Dispatch_GrantAsset_ShouldRoundTripThroughLedgerAndDetail() await WithDispatcherAsync(async dispatcher => { var grantEnvelope = await dispatcher.DispatchAsync("grant_asset", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9001\",\"Reason\":\"admin-test\",\"IdempotencyKey\":\"GFX-GRANT-test-1\",\"GrantItems\":[{\"ItemOrCurrencyType\":\"Coin\",\"Quantity\":100}]}"); + "{\"ServerId\":1001,\"PlayerId\":\"9001\",\"Reason\":\"admin-test\",\"IdempotencyKey\":\"GFX-GRANT-test-1\",\"GrantItems\":[{\"ItemOrCurrencyType\":\"Coin\",\"Quantity\":100}]}"); string transactionId; using (var document = JsonDocument.Parse(ReadInnerJson(grantEnvelope))) { @@ -232,7 +230,7 @@ await WithDispatcherAsync(async dispatcher => } var ledgerEnvelope = await dispatcher.DispatchAsync("query_wallet_ledger", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9001\",\"PageSize\":20}"); + "{\"ServerId\":1001,\"PlayerId\":\"9001\",\"PageSize\":20}"); using (var ledgerDocument = JsonDocument.Parse(ReadInnerJson(ledgerEnvelope))) { var items = ledgerDocument.RootElement.GetProperty("Data").GetProperty("Items"); @@ -244,7 +242,7 @@ await WithDispatcherAsync(async dispatcher => } var detailEnvelope = await dispatcher.DispatchAsync("query_transaction_detail", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"TransactionId\":\"" + transactionId + "\"}"); + "{\"ServerId\":1001,\"TransactionId\":\"" + transactionId + "\"}"); using (var detailDocument = JsonDocument.Parse(ReadInnerJson(detailEnvelope))) { var data = detailDocument.RootElement.GetProperty("Data"); @@ -266,7 +264,7 @@ public async Task Dispatch_GrantAsset_WithoutPlayer_ShouldReturnInner4001() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("grant_asset", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"Reason\":\"admin-test\",\"GrantItems\":[{\"ItemOrCurrencyType\":\"Coin\",\"Quantity\":100}]}"); + "{\"ServerId\":1001,\"Reason\":\"admin-test\",\"GrantItems\":[{\"ItemOrCurrencyType\":\"Coin\",\"Quantity\":100}]}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ParameterInvalid); }); } @@ -279,7 +277,7 @@ public async Task Dispatch_MutePlayer_TwiceWithSameKey_ShouldReplayFirstResponse { await WithDispatcherAsync(async dispatcher => { - const string body = "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9002\",\"PenaltyId\":77,\"IdempotencyKey\":\"penalty-77-mute-1001\"}"; + const string body = "{\"ServerId\":1001,\"PlayerId\":\"9002\",\"PenaltyId\":77,\"IdempotencyKey\":\"penalty-77-mute-1001\"}"; var first = await dispatcher.DispatchAsync("mute_player", body); var second = await dispatcher.DispatchAsync("mute_player", body); Assert.Equal(first, second); @@ -301,7 +299,7 @@ public async Task Dispatch_KickPlayer_WithoutSessions_ShouldConfirm() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("kick_player", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9003\",\"PenaltyId\":78,\"IdempotencyKey\":\"penalty-78-kick-1001\"}"); + "{\"ServerId\":1001,\"PlayerId\":\"9003\",\"PenaltyId\":78,\"IdempotencyKey\":\"penalty-78-kick-1001\"}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var root = document.RootElement; @@ -319,7 +317,7 @@ public async Task Dispatch_QueryOnlineOverview_ShouldReturnCounters() { await WithDispatcherAsync(async dispatcher => { - var envelope = await dispatcher.DispatchAsync("query_online_overview", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); + var envelope = await dispatcher.DispatchAsync("query_online_overview", "{\"ServerId\":1001}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var root = document.RootElement; @@ -344,7 +342,7 @@ public async Task Dispatch_EndAbnormalMatch_ShouldReturnInner5003() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("end_abnormal_match", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"MatchId\":\"m-1\",\"Reason\":\"test\",\"ReviewerOperatorId\":\"admin\",\"IdempotencyKey\":\"onlineControlled-end_abnormal_match-m-1-1001\"}"); + "{\"ServerId\":1001,\"MatchId\":\"m-1\",\"Reason\":\"test\",\"ReviewerOperatorId\":\"admin\",\"IdempotencyKey\":\"onlineControlled-end_abnormal_match-m-1-1001\"}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.StateOperationForbidden); }); } @@ -358,7 +356,7 @@ public async Task Dispatch_QueryPlayerTimeline_Empty_ShouldReturnEmptyEvents() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("query_player_timeline", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9004\"}"); + "{\"ServerId\":1001,\"PlayerId\":\"9004\"}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var data = document.RootElement.GetProperty("Data"); @@ -377,7 +375,7 @@ public async Task Dispatch_PublishRemoteConfig_ShouldReturnConfirmVersion() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("publishRemoteConfig", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"ConfigId\":5001,\"Reason\":\"admin-test\"}"); + "{\"ServerId\":1001,\"ConfigId\":5001,\"Reason\":\"admin-test\"}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var root = document.RootElement; @@ -398,11 +396,11 @@ public async Task Dispatch_PublishConfigRollout_PercentOutOfRange_ShouldReturnIn await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("publishConfigRollout", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3,\"Percent\":101,\"Reason\":\"admin-test\"}"); + "{\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3,\"Percent\":101,\"Reason\":\"admin-test\"}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ParameterInvalid); envelope = await dispatcher.DispatchAsync("publishConfigRollout", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3,\"Percent\":-1,\"Reason\":\"admin-test\"}"); + "{\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3,\"Percent\":-1,\"Reason\":\"admin-test\"}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ParameterInvalid); }); } @@ -418,7 +416,7 @@ await WithDispatcherAsync(async dispatcher => foreach (var percent in new[] { "\"Percent\":0,", "\"Percent\":100,", "" }) { var envelope = await dispatcher.DispatchAsync("publishConfigRollout", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3," + percent + "\"Reason\":\"admin-test\"}"); + "{\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3," + percent + "\"Reason\":\"admin-test\"}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var root = document.RootElement; @@ -438,7 +436,7 @@ public async Task Dispatch_SuspendResumePlayer_WithoutDirection_ShouldReturnInne await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("suspend_resume_player", - "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9005\",\"Reason\":\"test\",\"ReviewerOperatorId\":\"admin\",\"IdempotencyKey\":\"onlineControlled-suspend_resume_player-9005-1001\"}"); + "{\"ServerId\":1001,\"PlayerId\":\"9005\",\"Reason\":\"test\",\"ReviewerOperatorId\":\"admin\",\"IdempotencyKey\":\"onlineControlled-suspend_resume_player-9005-1001\"}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ParameterInvalid); }); } @@ -451,7 +449,7 @@ public async Task Dispatch_QueryReportCases_Empty_ShouldReturnEmptyItems() { await WithDispatcherAsync(async dispatcher => { - var envelope = await dispatcher.DispatchAsync("query_report_cases", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); + var envelope = await dispatcher.DispatchAsync("query_report_cases", "{\"ServerId\":1001}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var data = document.RootElement.GetProperty("Data"); @@ -469,7 +467,7 @@ public async Task Dispatch_QueryMatchQueueOverview_ShouldReturnQueuesArray() { await WithDispatcherAsync(async dispatcher => { - var envelope = await dispatcher.DispatchAsync("query_match_queue_overview", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); + var envelope = await dispatcher.DispatchAsync("query_match_queue_overview", "{\"ServerId\":1001}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var data = document.RootElement.GetProperty("Data"); diff --git a/Tests/GameFrameX.Tests/Online/OnlineAdminApiRateLimitTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAdminApiRateLimitTests.cs index 43e1d7352..17eddd0b1 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAdminApiRateLimitTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAdminApiRateLimitTests.cs @@ -120,7 +120,7 @@ private static string Url /// HTTP 响应。 private static Task PostAsync() { - var content = new StringContent("{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}", Encoding.UTF8, "application/json"); + var content = new StringContent("{\"ServerId\":1001}", Encoding.UTF8, "application/json"); return SharedHttpClient.PostAsync(Url, content); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineAdminApiServerTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAdminApiServerTests.cs index 947b45980..9f5f12c0d 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAdminApiServerTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAdminApiServerTests.cs @@ -95,7 +95,7 @@ private static async Task WithStartedAdminAsync(Func body) /// HTTP 响应。 private static Task PostAsync(string action) { - var content = new StringContent("{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}", Encoding.UTF8, "application/json"); + var content = new StringContent("{\"ServerId\":1001}", Encoding.UTF8, "application/json"); return SharedHttpClient.PostAsync("http://127.0.0.1:" + TestPort + "/online/admin/" + action, content); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineAdminAssetCompensationHandlersTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAdminAssetCompensationHandlersTests.cs index c3ec4bf4d..cb0a93182 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAdminAssetCompensationHandlersTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAdminAssetCompensationHandlersTests.cs @@ -83,7 +83,7 @@ public Task AlertAsync(OnlineAssetAlertRecord record, CancellationToken cancella /// private sealed class NullAuditReader : IOnlineAuditReader { - public Task> QueryAsync(OnlineScope scope, OnlineAuditQuery query = null, CancellationToken cancellationToken = default) + public Task> QueryAsync(OnlineAuditQuery query = null, CancellationToken cancellationToken = default) { return Task.FromResult(OnlineResult.Ok(new OnlineAuditPage(new OnlineAuditRecord[0], null))); } @@ -135,7 +135,7 @@ private static OnlineAdminAssetHandlers CreateHandlers(OnlineGrantCompensationQu /// private static OnlineGrantRequest BuildRemoteRequest(string key) { - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); return new OnlineGrantRequest(scope, OnlineAssetChangeSource.MatchReward, OnlineGrantOperation.Grant, "跨服赛果", "bo-" + key, new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 100) }, key) { HomeServerId = 200 }; } @@ -147,7 +147,7 @@ public async Task QueryAndResolve_WithoutQueue_DegradesAndRejects() { // Arrange var handlers = CreateHandlers(null); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act var snapshot = (OnlineAdminAssetHandlers.CompensationQueueResponse)await handlers.QueryCompensationQueueAsync(new AdminApiRequest("query_compensation_queue", "{}"), scope, CancellationToken.None); @@ -177,7 +177,7 @@ public async Task QueryCompensationQueue_WithManualReviewEntry_ListsFailureFacts await queue.DrainAsync(); // Act - var snapshot = (OnlineAdminAssetHandlers.CompensationQueueResponse)await handlers.QueryCompensationQueueAsync(new AdminApiRequest("query_compensation_queue", "{}"), new OnlineScope(1, 10, 100, 10001), CancellationToken.None); + var snapshot = (OnlineAdminAssetHandlers.CompensationQueueResponse)await handlers.QueryCompensationQueueAsync(new AdminApiRequest("query_compensation_queue", "{}"), new OnlineScope(100, 10001), CancellationToken.None); // Assert Assert.True(snapshot.QueueConfigured); @@ -204,7 +204,7 @@ public async Task ResolveCompensationManualReview_Retry_RequeuesEntry() var handlers = CreateHandlers(queue); queue.Enqueue(BuildRemoteRequest("key-admin-retry")); await queue.DrainAsync(); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act var ack = (OnlineAdminAssetHandlers.CompensationResolveResponse)await handlers.ResolveCompensationManualReviewAsync( @@ -242,7 +242,7 @@ public async Task ResolveCompensationManualReview_Discard_RemovesEntryAndKeepsTr // Act var ack = (OnlineAdminAssetHandlers.CompensationResolveResponse)await handlers.ResolveCompensationManualReviewAsync( new AdminApiRequest("resolve_compensation_manual_review", "{\"IdempotencyKey\":\"key-admin-discard\",\"Action\":\"Discard\",\"Reason\":\"线下已补偿\"}"), - new OnlineScope(1, 10, 100, 10001), CancellationToken.None); + new OnlineScope(100, 10001), CancellationToken.None); // Assert Assert.Equal("Discarded", ack.State); diff --git a/Tests/GameFrameX.Tests/Online/OnlineAdminHotfixDispatcherTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAdminHotfixDispatcherTests.cs index b8b5e1737..c4dc17bf9 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAdminHotfixDispatcherTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAdminHotfixDispatcherTests.cs @@ -60,8 +60,8 @@ namespace GameFrameX.Tests.Online; [Collection(HotfixManagerStaticStateCollection.Name)] public sealed class OnlineAdminHotfixDispatcherTests : IDisposable { - /// 测试用作用域三元组(与组合产物授权作用域一致)。 - private const string ScopeBody = "\"TenantId\":1,\"AppId\":1,\"ServerId\":1001"; + /// 测试用作用域区服键(与组合产物授权作用域一致)。 + private const string ScopeBody = "\"ServerId\":1001"; /// 本实例创建的版本目录(Dispose 统一最佳努力清理)。 private readonly List _createdVersions = new List(); @@ -76,8 +76,6 @@ private static CapabilityCompositionOptions CreateProductionExecutorOptions() { HostOptions = new CapabilityHostOptions { - TenantId = OnlineCapabilityTestHarness.TenantId, - AppId = OnlineCapabilityTestHarness.AppId, ServerId = OnlineCapabilityTestHarness.ServerId, }, }; diff --git a/Tests/GameFrameX.Tests/Online/OnlineAssetDomainGuardTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAssetDomainGuardTests.cs index 0b3093753..071f779f4 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAssetDomainGuardTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAssetDomainGuardTests.cs @@ -94,7 +94,7 @@ public async Task LedgerEntries_CarryCompleteAuditIdentity() var coordinator = new IdempotencyCoordinator(new InMemoryIdempotencyStore(), new StepClock(), options); var assetStore = new InMemoryOnlineAssetStore(); var grantService = new OnlineGrantService(assetStore, new InMemoryOnlineAssetTransactionStore(), new OnlineIdempotencyService(coordinator, null), new NullPublisher(), null); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); var request = new OnlineGrantRequest(scope, OnlineAssetChangeSource.PaymentConfirm, OnlineGrantOperation.Grant, "支付发货", "bo-guard", new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 60) }, "key-guard"); // Act diff --git a/Tests/GameFrameX.Tests/Online/OnlineAssetG3AcceptanceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAssetG3AcceptanceTests.cs index 95587228b..c28639339 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAssetG3AcceptanceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAssetG3AcceptanceTests.cs @@ -126,7 +126,7 @@ public async Task G3_Acceptance_FourSourcesEndToEnd() OnlineAssetChangeSource.MailAttachment, OnlineAssetChangeSource.MatchReward, }; - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); var transactionIds = new List(); // Act:每类来源发放 100(不同幂等键)+ 同键重试一次(应回放)。 @@ -168,7 +168,7 @@ public async Task G3_Acceptance_FourSourcesEndToEnd() }); // 对账:账本累加 == 快照(差异 = 0 红线)。 - var report = await reconciliationService.ReconcileAllAsync(1, 10); + var report = await reconciliationService.ReconcileAllAsync(); Assert.Equal(1, report.PlayerCount); Assert.True(report.IsConsistent); diff --git a/Tests/GameFrameX.Tests/Online/OnlineAssetQueryServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAssetQueryServiceTests.cs index 5d82502df..4e69b8a2d 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAssetQueryServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAssetQueryServiceTests.cs @@ -115,7 +115,7 @@ public async Task GetWalletAndInventory_AfterGrant_ReturnsSnapshots() { // Arrange var harness = new Harness(); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); await harness.CreateGrantService().ExecuteAsync(new OnlineGrantRequest(scope, OnlineAssetChangeSource.MailAttachment, OnlineGrantOperation.Grant, "邮件附件", "bo-q1", new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 100), new OnlineAssetChangeLine(OnlineAssetKind.Item, "sword", 2) }, "key-q1")); var query = harness.CreateQueryService(); @@ -145,13 +145,13 @@ public async Task GetLedgerPageAsync_PagesWithoutOverlapOrGaps() var grantService = harness.CreateGrantService(); for (var index = 1; index <= 5; index++) { - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); var ok = await grantService.ExecuteAsync(new OnlineGrantRequest(scope, OnlineAssetChangeSource.MatchReward, OnlineGrantOperation.Grant, "五连发", "bo-p" + index, new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 10) }, "key-p" + index)); Assert.True(ok.IsSuccess); } var query = harness.CreateQueryService(); - var scope2 = new OnlineScope(1, 10, 100, 10001); + var scope2 = new OnlineScope(100, 10001); // Act var page1 = await query.GetLedgerPageAsync(scope2, string.Empty, 4); @@ -184,7 +184,7 @@ public async Task GetLedgerPageAsync_InvalidArguments_ShouldReturnParameterInval // Arrange var harness = new Harness(); var query = harness.CreateQueryService(); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act var result = await query.GetLedgerPageAsync(scope, cursor, maxCount); @@ -202,7 +202,7 @@ public async Task GetTransactionDetailAsync_ReturnsFullAuditFields() { // Arrange var harness = new Harness(); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); var granted = await harness.CreateGrantService().ExecuteAsync(new OnlineGrantRequest(scope, OnlineAssetChangeSource.AdminOperation, OnlineGrantOperation.Reissue, "客诉补发", "bo-detail", new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 88) }, "key-detail") { OperatorId = "op-42" }); var query = harness.CreateQueryService(); @@ -229,10 +229,10 @@ public async Task GetTransactionDetailAsync_CrossScopeOrMissing_ShouldReturnReso { // Arrange var harness = new Harness(); - var ownerScope = new OnlineScope(1, 10, 100, 10001); + var ownerScope = new OnlineScope(100, 10001); var granted = await harness.CreateGrantService().ExecuteAsync(new OnlineGrantRequest(ownerScope, OnlineAssetChangeSource.MatchReward, OnlineGrantOperation.Grant, "赛果", "bo-cross", new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 10) }, "key-cross")); var query = harness.CreateQueryService(); - var strangerScope = new OnlineScope(1, 10, 100, 10999); + var strangerScope = new OnlineScope(100, 10999); // Act var crossScope = await query.GetTransactionDetailAsync(strangerScope, granted.Data.TransactionId); @@ -254,7 +254,7 @@ public async Task GetWalletAsync_WithoutPlayerScope_ShouldReturnParameterInvalid // Arrange var harness = new Harness(); var query = harness.CreateQueryService(); - var scope = new OnlineScope(1, 10, 100, 0); + var scope = new OnlineScope(100, 0); // Act var result = await query.GetWalletAsync(scope, "gold"); diff --git a/Tests/GameFrameX.Tests/Online/OnlineAssetReconciliationServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAssetReconciliationServiceTests.cs index 57ada3972..8c77b5d30 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAssetReconciliationServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAssetReconciliationServiceTests.cs @@ -95,18 +95,18 @@ public DriftingAssetStore(IOnlineAssetStore inner, long playerId, long balanceOf _balanceOffset = balanceOffset; } - public Task> ListWalletAccountsAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListWalletAccountsAsync(long playerId, CancellationToken cancellationToken = default) { if (playerId != _playerId) { - return _inner.ListWalletAccountsAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListWalletAccountsAsync(playerId, cancellationToken); } - var drifted = _inner.ListWalletAccountsAsync(tenantId, appId, playerId, cancellationToken).GetAwaiter().GetResult(); + var drifted = _inner.ListWalletAccountsAsync(playerId, cancellationToken).GetAwaiter().GetResult(); var tampered = new List(); foreach (var account in drifted) { - tampered.Add(new OnlineWalletAccount { TenantId = account.TenantId, AppId = account.AppId, PlayerId = account.PlayerId, CurrencyId = account.CurrencyId, Balance = account.Balance + _balanceOffset, Version = account.Version, UpdatedTime = account.UpdatedTime }); + tampered.Add(new OnlineWalletAccount { PlayerId = account.PlayerId, CurrencyId = account.CurrencyId, Balance = account.Balance + _balanceOffset, Version = account.Version, UpdatedTime = account.UpdatedTime }); } return Task.FromResult>(tampered); @@ -117,19 +117,19 @@ public Task ApplyAsync(OnlineAssetChangeBatch batch, Can return _inner.ApplyAsync(batch, cancellationToken); } - public Task FindWalletAsync(long tenantId, long appId, long playerId, string currencyId, CancellationToken cancellationToken = default) + public Task FindWalletAsync(long playerId, string currencyId, CancellationToken cancellationToken = default) { - return _inner.FindWalletAsync(tenantId, appId, playerId, currencyId, cancellationToken); + return _inner.FindWalletAsync(playerId, currencyId, cancellationToken); } - public Task FindInventoryAsync(long tenantId, long appId, long playerId, string itemId, CancellationToken cancellationToken = default) + public Task FindInventoryAsync(long playerId, string itemId, CancellationToken cancellationToken = default) { - return _inner.FindInventoryAsync(tenantId, appId, playerId, itemId, cancellationToken); + return _inner.FindInventoryAsync(playerId, itemId, cancellationToken); } - public Task> ListInventoryStacksAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListInventoryStacksAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListInventoryStacksAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListInventoryStacksAsync(playerId, cancellationToken); } public Task> ListLedgerEntriesAsync(OnlineLedgerPageQuery query, CancellationToken cancellationToken = default) @@ -142,14 +142,14 @@ public Task> FindLedgerEntriesByTransactionIdAs return _inner.FindLedgerEntriesByTransactionIdAsync(transactionId, cancellationToken); } - public Task> SumLedgerDeltasByAssetAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> SumLedgerDeltasByAssetAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.SumLedgerDeltasByAssetAsync(tenantId, appId, playerId, cancellationToken); + return _inner.SumLedgerDeltasByAssetAsync(playerId, cancellationToken); } - public Task> ListPlayerIdsAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListPlayerIdsAsync(CancellationToken cancellationToken = default) { - return _inner.ListPlayerIdsAsync(tenantId, appId, cancellationToken); + return _inner.ListPlayerIdsAsync(cancellationToken); } } @@ -184,7 +184,7 @@ public OnlineAssetReconciliationService CreateReconciliationService(IOnlineAsset /// private static OnlineGrantRequest BuildRequest(long playerId, string key, long amount) { - var scope = new OnlineScope(1, 10, 100, playerId); + var scope = new OnlineScope(100, playerId); return new OnlineGrantRequest(scope, OnlineAssetChangeSource.MatchReward, OnlineGrantOperation.Grant, "赛季结算", "bo-" + key, new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", amount) }, key); } @@ -202,7 +202,7 @@ public async Task ReconcilePlayerAsync_AfterNormalFlow_IsConsistent() var reconciliation = harness.CreateReconciliationService(); // Act - var report = await reconciliation.ReconcilePlayerAsync(new OnlineScope(1, 10, 100, 10001)); + var report = await reconciliation.ReconcilePlayerAsync(new OnlineScope(100, 10001)); // Assert Assert.Equal(1, report.PlayerCount); @@ -224,7 +224,7 @@ public async Task ReconcilePlayerAsync_WithDriftedSnapshot_ReportsLocatedDiffere var reconciliation = harness.CreateReconciliationService(drifting); // Act - var report = await reconciliation.ReconcilePlayerAsync(new OnlineScope(1, 10, 100, 10001)); + var report = await reconciliation.ReconcilePlayerAsync(new OnlineScope(100, 10001)); // Assert Assert.False(report.IsConsistent); @@ -251,7 +251,7 @@ public async Task ReconcileAllAsync_CoversAllPlayersAndLocatesDrift() var reconciliation = harness.CreateReconciliationService(drifting); // Act - var report = await reconciliation.ReconcileAllAsync(1, 10); + var report = await reconciliation.ReconcileAllAsync(); // Assert Assert.Equal(2, report.PlayerCount); diff --git a/Tests/GameFrameX.Tests/Online/OnlineAuditServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAuditServiceTests.cs index 1181bae5d..b97883ece 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAuditServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAuditServiceTests.cs @@ -42,25 +42,13 @@ namespace GameFrameX.Tests.Online /// 统一审计链路服务测试(审计半边 + 服务端半边: /// 审计完整性校验(操作者/原因/标识/类型/作用域/域白名单逐维度拒绝)、重复接入幂等(不重复落档无副作用)、 /// 脱敏落档与检索(掩码逐键断言、无明文敏感值)、跨域联查与各维度过滤、keyset 全序分页不重不漏、 - /// App 级与区服级审计共存、跨作用域读取与无数据同构(反预言))。 + /// 全局级与区服级审计共存、无数据同构(反预言))。 /// public class OnlineAuditServiceTests { - /// 测试用租户标识。 - private const long TenantId = 9101; - - /// 测试用应用标识。 - private const long AppId = 9102; - /// 测试用区服标识。 private const long ServerId = 9103; - /// 测试用其它租户标识(反预言用例)。 - private const long OtherTenantId = 9901; - - /// 测试用其它 App 标识(反预言用例)。 - private const long OtherAppId = 9902; - /// /// 构造一条完整可接入的审计条目(各用例在此基础上按需破坏单一维度)。 /// @@ -76,8 +64,6 @@ private static OnlineAuditEntry CreateEntry(string eventId, string domain, long EventId = eventId, EventType = "admin.audit." + domain.ToLowerInvariant(), OccurredTime = occurredTime, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, PlayerId = 42, OperatorId = "admin-001", @@ -117,7 +103,7 @@ public async Task Ingest_CompleteAudit_CrossDomainSearchable() Assert.False(result.Data.IsDuplicate); } - var query = await service.QueryAsync(new OnlineScope(TenantId, AppId, ServerId)); + var query = await service.QueryAsync(); Assert.True(query.IsSuccess); var records = query.Data.Records; Assert.Equal(3, records.Count); @@ -148,7 +134,7 @@ public async Task Ingest_MissingOperator_Rejected() Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.ParameterInvalid, result.Code); - var query = await service.QueryAsync(new OnlineScope(TenantId, AppId, ServerId)); + var query = await service.QueryAsync(); Assert.Empty(query.Data.Records); } @@ -182,14 +168,12 @@ public async Task Ingest_UnknownDomain_Rejected() } /// - /// 审计半边:缺审计标识 / 缺事件类型 / 缺租户或 App 的条目分别被拒绝(参数非法)。 + /// 审计半边:缺审计标识 / 缺事件类型的条目分别被拒绝(参数非法)。 /// /// 按维度破坏条目的委托。 [Theory] [InlineData("eventId")] [InlineData("eventType")] - [InlineData("tenant")] - [InlineData("app")] public async Task Ingest_MissingRequiredDimensions_Rejected(string dimension) { var service = CreateService(); @@ -202,12 +186,6 @@ public async Task Ingest_MissingRequiredDimensions_Rejected(string dimension) case "eventType": entry.EventType = string.Empty; break; - case "tenant": - entry.TenantId = 0; - break; - case "app": - entry.AppId = 0; - break; } var result = await service.IngestAsync(entry); @@ -294,7 +272,7 @@ public async Task Ingest_DuplicateEventId_IdempotentReplay() Assert.True(third.IsSuccess); Assert.True(third.Data.IsDuplicate); - var query = await service.QueryAsync(new OnlineScope(TenantId, AppId, ServerId)); + var query = await service.QueryAsync(); var matched = query.Data.Records.Where(r => r.EventId == "audit-idem-001").ToList(); Assert.Single(matched); } @@ -321,7 +299,7 @@ public async Task Ingest_SensitiveFields_MaskedInStorageAndRetrieval() var ingest = await service.IngestAsync(entry); Assert.True(ingest.IsSuccess); - var query = await service.QueryAsync(new OnlineScope(TenantId, AppId, ServerId)); + var query = await service.QueryAsync(); var record = Assert.Single(query.Data.Records); Assert.Equal(OnlineEventSanitizer.MaskedValue, record.SanitizedFields["SessionToken"]); @@ -352,14 +330,14 @@ public async Task Query_DomainFilter_CrossDomainJoin() await service.IngestAsync(CreateEntry("dj-penalty", OnlineAuditDomain.Penalty, 1_700_000_000_200L)); await service.IngestAsync(CreateEntry("dj-mail", OnlineAuditDomain.Mail, 1_700_000_000_300L)); - var joined = await service.QueryAsync(new OnlineScope(TenantId, AppId, ServerId), new OnlineAuditQuery + var joined = await service.QueryAsync(new OnlineAuditQuery { Domains = new List { OnlineAuditDomain.Payment, OnlineAuditDomain.Penalty }, }); Assert.Equal(2, joined.Data.Records.Count); Assert.All(joined.Data.Records, r => Assert.NotEqual(OnlineAuditDomain.Mail, r.Domain)); - var all = await service.QueryAsync(new OnlineScope(TenantId, AppId, ServerId), new OnlineAuditQuery + var all = await service.QueryAsync(new OnlineAuditQuery { Domains = new List(), }); @@ -389,29 +367,28 @@ public async Task Query_OptionalFilters_EachDimensionEffective() byCorrelation.CorrelationId = "trace-abc"; await service.IngestAsync(byCorrelation); - var appLevel = CreateEntry("f-app-level", OnlineAuditDomain.RemoteConfig, 1_700_000_000_400L); - appLevel.ServerId = 0; - await service.IngestAsync(appLevel); + var globalLevel = CreateEntry("f-global-level", OnlineAuditDomain.RemoteConfig, 1_700_000_000_400L); + globalLevel.ServerId = 0; + await service.IngestAsync(globalLevel); - var scope = new OnlineScope(TenantId, AppId, ServerId); - var playerQuery = await service.QueryAsync(scope, new OnlineAuditQuery { PlayerId = 777 }); + var playerQuery = await service.QueryAsync(new OnlineAuditQuery { PlayerId = 777 }); Assert.Equal("f-player", Assert.Single(playerQuery.Data.Records).EventId); - var operatorQuery = await service.QueryAsync(scope, new OnlineAuditQuery { OperatorId = "admin-777" }); + var operatorQuery = await service.QueryAsync(new OnlineAuditQuery { OperatorId = "admin-777" }); Assert.Equal("f-operator", Assert.Single(operatorQuery.Data.Records).EventId); - var typeQuery = await service.QueryAsync(scope, new OnlineAuditQuery { EventType = "online.session.kicked" }); + var typeQuery = await service.QueryAsync(new OnlineAuditQuery { EventType = "online.session.kicked" }); Assert.Equal("f-type", Assert.Single(typeQuery.Data.Records).EventId); - var correlationQuery = await service.QueryAsync(scope, new OnlineAuditQuery { CorrelationId = "trace-abc" }); + var correlationQuery = await service.QueryAsync(new OnlineAuditQuery { CorrelationId = "trace-abc" }); Assert.Equal("f-corr", Assert.Single(correlationQuery.Data.Records).EventId); - var serverQuery = await service.QueryAsync(scope, new OnlineAuditQuery { ServerId = 0 }); - Assert.Equal("f-app-level", Assert.Single(serverQuery.Data.Records).EventId); + var serverQuery = await service.QueryAsync(new OnlineAuditQuery { ServerId = 0 }); + Assert.Equal("f-global-level", Assert.Single(serverQuery.Data.Records).EventId); // 时间窗为闭区间:[t, t] 命中恰好落在边界上的记录。 - var windowQuery = await service.QueryAsync(scope, new OnlineAuditQuery + var windowQuery = await service.QueryAsync(new OnlineAuditQuery { StartTime = 1_700_000_000_100L, EndTime = 1_700_000_000_200L, @@ -433,12 +410,11 @@ public async Task Query_Pagination_NoOverlapNoMiss_StableOrder() await service.IngestAsync(CreateEntry("page-d", OnlineAuditDomain.Reward, 1_700_000_000_300L)); await service.IngestAsync(CreateEntry("page-e", OnlineAuditDomain.Mail, 1_700_000_000_200L)); - var scope = new OnlineScope(TenantId, AppId, ServerId); var seen = new List(); string cursor = null; while (true) { - var page = await service.QueryAsync(scope, new OnlineAuditQuery { Cursor = cursor, PageSize = 2 }); + var page = await service.QueryAsync(new OnlineAuditQuery { Cursor = cursor, PageSize = 2 }); Assert.True(page.IsSuccess); seen.AddRange(page.Data.Records.Select(r => r.EventId)); if (!page.Data.Cursor.HasMore) @@ -453,11 +429,11 @@ public async Task Query_Pagination_NoOverlapNoMiss_StableOrder() Assert.Equal(new[] { "page-a", "page-b", "page-c", "page-d", "page-e" }, seen); Assert.Equal(5, seen.Distinct().Count()); - var badCursor = await service.QueryAsync(scope, new OnlineAuditQuery { Cursor = "not-a-valid-cursor" }); + var badCursor = await service.QueryAsync(new OnlineAuditQuery { Cursor = "not-a-valid-cursor" }); Assert.False(badCursor.IsSuccess); Assert.Equal(OnlineErrorCode.ParameterInvalid, badCursor.Code); - var oversized = await service.QueryAsync(scope, new OnlineAuditQuery { PageSize = 201 }); + var oversized = await service.QueryAsync(new OnlineAuditQuery { PageSize = 201 }); Assert.False(oversized.IsSuccess); Assert.Equal(OnlineErrorCode.ParameterInvalid, oversized.Code); } @@ -475,12 +451,11 @@ public async Task Query_Pagination_ExactFullLastPage_HasMoreFalse() await service.IngestAsync(CreateEntry("full-page-c", OnlineAuditDomain.Reward, 1_700_000_000_200L)); await service.IngestAsync(CreateEntry("full-page-d", OnlineAuditDomain.Reward, 1_700_000_000_100L)); - var scope = new OnlineScope(TenantId, AppId, ServerId); var seen = new List(); string cursor = null; while (true) { - var page = await service.QueryAsync(scope, new OnlineAuditQuery { Cursor = cursor, PageSize = 2 }); + var page = await service.QueryAsync(new OnlineAuditQuery { Cursor = cursor, PageSize = 2 }); Assert.True(page.IsSuccess); seen.AddRange(page.Data.Records.Select(r => r.EventId)); if (!page.Data.Cursor.HasMore) @@ -513,12 +488,11 @@ public async Task Query_Pagination_WithDomainFilter_NoOverlapNoMiss() await service.IngestAsync(CreateEntry("mix-e", OnlineAuditDomain.Payment, 1_700_000_000_200L)); await service.IngestAsync(CreateEntry("mix-f", OnlineAuditDomain.Mail, 1_700_000_000_200L)); - var scope = new OnlineScope(TenantId, AppId, ServerId); var seen = new List(); string cursor = null; while (true) { - var page = await service.QueryAsync(scope, new OnlineAuditQuery + var page = await service.QueryAsync(new OnlineAuditQuery { Domains = new List { OnlineAuditDomain.Payment }, Cursor = cursor, @@ -540,54 +514,34 @@ public async Task Query_Pagination_WithDomainFilter_NoOverlapNoMiss() } /// - /// 反预言(作用域越界):跨租户/跨 App 检索与「无数据」(空存储同作用域)在页形状上逐项一致 - /// (空行集 + HasMore=false + 空游标),不泄露其它作用域审计的存在性。 + /// 无数据同构:空存储的默认查询在页形状上为空行集 + HasMore=false + 空游标(不误报错误)。 /// [Fact] - public async Task Query_CrossScope_EmptyIsomorphicWithNoData() + public async Task Query_EmptyStore_EmptyPageShape() { - var service = CreateService(); - await service.IngestAsync(CreateEntry("iso-001", OnlineAuditDomain.Payment, 1_700_000_000_000L)); + var noData = await CreateService().QueryAsync(); - var otherTenant = await service.QueryAsync(new OnlineScope(OtherTenantId, AppId, ServerId)); - var otherApp = await service.QueryAsync(new OnlineScope(TenantId, OtherAppId, ServerId)); - var noData = await CreateService().QueryAsync(new OnlineScope(TenantId, AppId, ServerId)); - - foreach (var page in new[] { otherTenant, otherApp, noData }) - { - Assert.True(page.IsSuccess); - Assert.Empty(page.Data.Records); - Assert.False(page.Data.Cursor.HasMore); - Assert.Equal(string.Empty, page.Data.Cursor.Cursor); - } + Assert.True(noData.IsSuccess); + Assert.Empty(noData.Data.Records); + Assert.False(noData.Data.Cursor.HasMore); + Assert.Equal(string.Empty, noData.Data.Cursor.Cursor); } /// - /// 作用域锚定语义:QueryAsync 只锚定 TenantId/AppId,缺任一即拒绝; - /// 区服维度完全由查询条件承载(App 级 ServerId=0 与区服级审计在默认查询中共存)。 + /// 区服维度完全由查询条件承载(区服级与 ServerId=0 的全局级审计在默认查询中共存)。 /// [Fact] - public async Task Query_ScopeAnchors_TenantAppOnly() + public async Task Query_ServerLevelCoexistsWithGlobalLevel() { var service = CreateService(); await service.IngestAsync(CreateEntry("anchor-server", OnlineAuditDomain.Operation, 1_700_000_000_000L)); - var appLevel = CreateEntry("anchor-app", OnlineAuditDomain.RemoteConfig, 1_700_000_000_100L); - appLevel.ServerId = 0; - await service.IngestAsync(appLevel); + var globalLevel = CreateEntry("anchor-global", OnlineAuditDomain.RemoteConfig, 1_700_000_000_100L); + globalLevel.ServerId = 0; + await service.IngestAsync(globalLevel); - // scope.ServerId=任意值不影响结果集(锚定语义只看 TenantId/AppId)。 - var scopeWithServer = new OnlineScope(TenantId, AppId, 12345); - var page = await service.QueryAsync(scopeWithServer); + var page = await service.QueryAsync(); Assert.Equal(2, page.Data.Records.Count); - - var missingTenant = await service.QueryAsync(new OnlineScope(0, AppId, ServerId)); - Assert.False(missingTenant.IsSuccess); - Assert.Equal(OnlineErrorCode.ParameterInvalid, missingTenant.Code); - - var missingApp = await service.QueryAsync(new OnlineScope(TenantId, 0, ServerId)); - Assert.False(missingApp.IsSuccess); - Assert.Equal(OnlineErrorCode.ParameterInvalid, missingApp.Code); } /// @@ -605,7 +559,7 @@ public async Task Ingest_DefensiveCopy_CallerMutationDoesNotLeakIntoStore() await service.IngestAsync(entry); payload["OrderAmount"] = "999999"; - var query = await service.QueryAsync(new OnlineScope(TenantId, AppId, ServerId)); + var query = await service.QueryAsync(); Assert.Equal("100", Assert.Single(query.Data.Records).SanitizedFields["OrderAmount"]); } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs index d6b421d1e..343eef36c 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs @@ -102,8 +102,6 @@ private static CapabilityCompositionOptions CreateBareOptions(JsonElement family { HostOptions = new CapabilityHostOptions { - TenantId = OnlineCapabilityTestHarness.TenantId, - AppId = OnlineCapabilityTestHarness.AppId, ServerId = OnlineCapabilityTestHarness.ServerId, }, }; @@ -453,13 +451,14 @@ public void Compose_NullOptions_ThrowsArgumentNull() } /// - /// 族配置段作用域非法(缺 TenantId / TenantId=0):族基建读取三元组即 fail-fast,消息带配置路径。 + /// 族配置段作用域非法(缺 ServerId / ServerId=0):族基建读取区服键即 fail-fast,消息带配置路径 + ///(单键化 D4 后族段只读 ServerId;遗留 TenantId/AppId 键为废键,不参与校验)。 /// /// 族配置段原文。 [Theory] - [InlineData("{\"AppId\":1,\"ServerId\":1001}")] - [InlineData("{\"TenantId\":0,\"AppId\":1,\"ServerId\":1001}")] - public void Compose_FamilySectionTenantInvalid_FailsFast(string familySectionJson) + [InlineData("{\"TenantId\":1,\"AppId\":1}")] + [InlineData("{\"TenantId\":1,\"AppId\":1,\"ServerId\":0}")] + public void Compose_FamilySectionServerKeyInvalid_FailsFast(string familySectionJson) { var options = CreateBareOptions(JsonDocument.Parse(familySectionJson).RootElement.Clone()); options.Override(new OnlineCapabilityTestHarness.EmptyPlayerDirectory()); @@ -467,7 +466,7 @@ public void Compose_FamilySectionTenantInvalid_FailsFast(string familySectionJso var exception = Assert.Throws(() => CapabilityComposition.Compose(new OnlineCapabilityFamily(), options)); - Assert.Contains("Online.TenantId", exception.Message); + Assert.Contains("Online.ServerId", exception.Message); } /// @@ -477,7 +476,7 @@ public void Compose_FamilySectionTenantInvalid_FailsFast(string familySectionJso public void Compose_HostOptionsInvalid_FailsFast() { var options = OnlineCapabilityTestHarness.CreateOptions(); - options.HostOptions.TenantId = 0; + options.HostOptions.ServerId = 0; var exception = Assert.Throws(() => CapabilityComposition.Compose(new OnlineCapabilityFamily(), options)); diff --git a/Tests/GameFrameX.Tests/Online/OnlineCapabilityTestHarness.cs b/Tests/GameFrameX.Tests/Online/OnlineCapabilityTestHarness.cs index 1583dbbf6..f2dd9bb9d 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineCapabilityTestHarness.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineCapabilityTestHarness.cs @@ -54,24 +54,18 @@ namespace GameFrameX.Tests.Online; /// public static class OnlineCapabilityTestHarness { - /// 测试用租户标识(与族配置段一致)。 - public const long TenantId = 1; - - /// 测试用应用标识(与族配置段一致)。 - public const long AppId = 1; - /// 测试用区服标识(与族配置段一致)。 public const long ServerId = 1001; /// - /// 构造族配置段 JSON(作用域三元组 + 可选 Settings 子对象;缺失键由族 fail-fast,因此恒写入)。 + /// 构造族配置段 JSON(区服键 + 可选 Settings 子对象;缺失键由族 fail-fast,因此恒写入)。 /// /// Settings 子对象原文(null = 不写 Settings 键)。 /// 族配置段节点。 public static JsonElement FamilySection(string settingsJson = null) { var settings = string.IsNullOrEmpty(settingsJson) ? string.Empty : ",\"Settings\":" + settingsJson; - return JsonDocument.Parse("{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001" + settings + "}").RootElement.Clone(); + return JsonDocument.Parse("{\"ServerId\":1001" + settings + "}").RootElement.Clone(); } /// @@ -87,7 +81,7 @@ public static CapabilityCompositionOptions CreateOptions(string settingsJson = n { var options = new CapabilityCompositionOptions(FamilySection(settingsJson), new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = TenantId, AppId = AppId, ServerId = ServerId, }, + HostOptions = new CapabilityHostOptions { ServerId = ServerId, }, }; // 宿主扩展点:Social 的玩家目录与 Operations 的热更回滚执行器(两者均 RequireHostService,缺失即装配 fail-fast)。 @@ -130,7 +124,7 @@ public static AdminApiDispatcher CreateDispatcher(CapabilityHost host) registry, host.Services.GetService(), host.Services.GetService(), - new AdminApiClaimedScope(host.TenantId, host.AppId, host.ServerId), + new AdminApiClaimedScope(host.ServerId), host.Services.GetOptionalService(), host.Report, host.Services); @@ -182,13 +176,11 @@ public sealed class EmptyPlayerDirectory : IOnlinePlayerDirectory /// /// Searches the player directory by name; this stub has no directory data and always returns an empty collection. /// - /// 租户标识(本桩忽略) / Tenant identifier (ignored by this stub) - /// 应用标识(本桩忽略) / Application identifier (ignored by this stub) /// 搜索关键字(本桩忽略) / Search keyword (ignored by this stub) /// 返回条数上限(本桩忽略) / Maximum number of results (ignored by this stub) /// 取消令牌(本桩忽略) / Cancellation token (ignored by this stub) /// 固定为空的目录条目集合 / An always-empty collection of directory entries - public Task> SearchByNameAsync(long tenantId, long appId, string keyword, int limit, CancellationToken cancellationToken = default) + public Task> SearchByNameAsync(string keyword, int limit, CancellationToken cancellationToken = default) { return Task.FromResult>(Array.Empty()); } @@ -199,12 +191,10 @@ public Task> SearchByNameAsync(long te /// /// Resolves directory entries by player identifiers; this stub has no directory data and always returns an empty collection. /// - /// 租户标识(本桩忽略) / Tenant identifier (ignored by this stub) - /// 应用标识(本桩忽略) / Application identifier (ignored by this stub) /// 待解析的玩家标识集合(本桩忽略) / Player identifiers to resolve (ignored by this stub) /// 取消令牌(本桩忽略) / Cancellation token (ignored by this stub) /// 固定为空的目录条目集合 / An always-empty collection of directory entries - public Task> FindAsync(long tenantId, long appId, IReadOnlyList playerIds, CancellationToken cancellationToken = default) + public Task> FindAsync(IReadOnlyList playerIds, CancellationToken cancellationToken = default) { return Task.FromResult>(Array.Empty()); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineChatServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineChatServiceTests.cs index c6c78ab00..586409d1c 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineChatServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineChatServiceTests.cs @@ -46,15 +46,10 @@ namespace GameFrameX.Tests.Online /// public class OnlineChatServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; + /// 测试用玩家一标识。 private const long PlayerOne = 1001; @@ -78,9 +73,9 @@ public class OnlineChatServiceTests public void BuildChannelId_ShouldBeIndependentOfDirection() { // Arrange & Act - var forward = OnlineChatService.BuildChannelId(TenantId, AppId, OnlineChatChannelKind.Direct, PlayerOne, PlayerTwo, string.Empty); - var backward = OnlineChatService.BuildChannelId(TenantId, AppId, OnlineChatChannelKind.Direct, PlayerTwo, PlayerOne, string.Empty); - var otherPair = OnlineChatService.BuildChannelId(TenantId, AppId, OnlineChatChannelKind.Direct, PlayerOne, PlayerThree, string.Empty); + var forward = OnlineChatService.BuildChannelId(OnlineChatChannelKind.Direct, PlayerOne, PlayerTwo, string.Empty); + var backward = OnlineChatService.BuildChannelId(OnlineChatChannelKind.Direct, PlayerTwo, PlayerOne, string.Empty); + var otherPair = OnlineChatService.BuildChannelId(OnlineChatChannelKind.Direct, PlayerOne, PlayerThree, string.Empty); // Assert Assert.Equal(forward, backward); @@ -552,8 +547,6 @@ public async Task GetHistoryAsync_WhenMessagesShareSameMillisecond_ShouldStillPa var draft = new OnlineChatMessage { MessageId = "msg-fixed-" + index, - TenantId = TenantId, - AppId = AppId, ChannelId = channel.ChannelId, ChannelKind = OnlineChatChannelKind.Direct, SenderId = PlayerOne, @@ -701,8 +694,6 @@ public async Task RecallAsync_WhenBeyondWindow_ShouldReturnStateOperationForbidd var draft = new OnlineChatMessage { MessageId = "msg-old", - TenantId = TenantId, - AppId = AppId, ChannelId = channel.ChannelId, ChannelKind = OnlineChatChannelKind.Direct, SenderId = PlayerOne, @@ -820,7 +811,7 @@ public async Task SendAsync_WhenScopeLacksPlayer_ShouldDenyAsInvalid() var channel = await OpenDirectAsync(service, PlayerOne, PlayerTwo); // Act - var outcome = await service.SendAsync(new OnlineScope(TenantId, AppId, ServerId, 0), channel.ChannelId, "内容"); + var outcome = await service.SendAsync(new OnlineScope(ServerId), channel.ChannelId, "内容"); // Assert Assert.False(outcome.IsSuccess); @@ -877,7 +868,7 @@ private static async Task OpenDirectAsync(TestChatFixture fix /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// @@ -1052,14 +1043,12 @@ public StubMembershipProbe(params long[] memberPlayerIds) /// Only checks whether the player is in the member whitelist supplied at /// construction, ignoring the channel kind and bound id. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 频道类型 / The channel kind /// 绑定主体标识 / The bound id /// 待判定的玩家 / The player to check /// 取消令牌 / Cancellation token /// 在白名单中返回 true / True when present in the whitelist - public Task IsChannelMemberAsync(long tenantId, long appId, OnlineChatChannelKind kind, string boundId, long playerId, CancellationToken cancellationToken = default) + public Task IsChannelMemberAsync(OnlineChatChannelKind kind, string boundId, long playerId, CancellationToken cancellationToken = default) { return Task.FromResult(_members.Contains(playerId)); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineCrossServerGrantRouterTests.cs b/Tests/GameFrameX.Tests/Online/OnlineCrossServerGrantRouterTests.cs index 55bc8131c..66ea7328c 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineCrossServerGrantRouterTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineCrossServerGrantRouterTests.cs @@ -197,7 +197,7 @@ public OnlineCrossServerGrantRouter CreateRouter(OnlineGrantService localService /// private static OnlineGrantRequest BuildRemoteRequest(long playerId, string key) { - var scope = new OnlineScope(1, 10, 100, playerId); + var scope = new OnlineScope(100, playerId); return new OnlineGrantRequest(scope, OnlineAssetChangeSource.MatchReward, OnlineGrantOperation.Grant, "跨服赛果", "bo-" + key, new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 100) }, key) { HomeServerId = 200 }; } @@ -212,7 +212,7 @@ public async Task RouteAsync_LocalHome_ExecutesLocally() var localService = harness.CreateGrantService(harness.LocalAssetStore); var transport = new ScriptedTransport(true); var router = harness.CreateRouter(localService, transport); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); var request = new OnlineGrantRequest(scope, OnlineAssetChangeSource.MatchReward, OnlineGrantOperation.Grant, "本地赛果", "bo-local", new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 100) }, "key-local"); // Act @@ -221,7 +221,7 @@ public async Task RouteAsync_LocalHome_ExecutesLocally() // Assert Assert.True(result.IsSuccess); Assert.Empty(transport.Calls); - var wallet = await harness.LocalAssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.LocalAssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(100, wallet.Balance); } @@ -246,7 +246,7 @@ public async Task RouteAsync_RemoteHome_DeliversViaTransport() var call = Assert.Single(transport.Calls); Assert.Equal(200, call.ServerId); Assert.Equal("key-remote", call.IdempotencyKey); - var localWallet = await harness.LocalAssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var localWallet = await harness.LocalAssetStore.FindWalletAsync(10001, "gold"); Assert.Null(localWallet); } @@ -285,9 +285,9 @@ public async Task RouteAsync_RemoteUnreachable_EnqueuesAndDrainDeliversOnce() Assert.Empty(queue.ListPending()); // 续投一次即成功出队(重试不重复生效由远端幂等键保证)。 Assert.Single(forwarding.Calls); - var remoteWallet = await harness.RemoteAssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var remoteWallet = await harness.RemoteAssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(100, remoteWallet.Balance); - var remoteLedger = await harness.RemoteAssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = 1, AppId = 10, PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); + var remoteLedger = await harness.RemoteAssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); Assert.Single(remoteLedger); Assert.Equal(0, drainAgain.RemainingCount); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineEventEnvelopeMapperTests.cs b/Tests/GameFrameX.Tests/Online/OnlineEventEnvelopeMapperTests.cs index 6022d7e8b..a04c6a678 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineEventEnvelopeMapperTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineEventEnvelopeMapperTests.cs @@ -50,8 +50,6 @@ private static OnlineEvent CreateSampleEvent() EventType = "online.session.created", OccurredTime = 1760000000123, SchemaVersion = 1, - TenantId = 1, - AppId = 10, ServerId = 100, PlayerId = 10001, Source = "online-identity", @@ -80,8 +78,6 @@ public void ToEnvelope_ShouldCarryScopeViaStableAttributeKeys() Assert.Equal("online-identity", envelope.Source); Assert.Equal("req-0001", envelope.CorrelationId); Assert.Equal(new byte[] { 1, 2, 3 }, envelope.Payload.ToArray()); - Assert.Equal("1", envelope.Attributes[OnlineEventEnvelopeMapper.TenantAttributeKey]); - Assert.Equal("10", envelope.Attributes[OnlineEventEnvelopeMapper.AppAttributeKey]); Assert.Equal("100", envelope.Attributes[OnlineEventEnvelopeMapper.ServerAttributeKey]); Assert.Equal("10001", envelope.Attributes[OnlineEventEnvelopeMapper.PlayerAttributeKey]); } @@ -103,8 +99,6 @@ public void FromEnvelope_AfterToEnvelope_ShouldRoundTripAllFields() Assert.Equal(original.EventType, roundTripped.EventType); Assert.Equal(original.OccurredTime, roundTripped.OccurredTime); Assert.Equal(original.SchemaVersion, roundTripped.SchemaVersion); - Assert.Equal(original.TenantId, roundTripped.TenantId); - Assert.Equal(original.AppId, roundTripped.AppId); Assert.Equal(original.ServerId, roundTripped.ServerId); Assert.Equal(original.PlayerId, roundTripped.PlayerId); Assert.Equal(original.Source, roundTripped.Source); @@ -126,8 +120,6 @@ public void FromEnvelope_WithoutScopeAttributes_ShouldFallBackToZero() // Assert Assert.Equal("evt-0002", onlineEvent.EventId); - Assert.Equal(0, onlineEvent.TenantId); - Assert.Equal(0, onlineEvent.AppId); Assert.Equal(0, onlineEvent.ServerId); Assert.Equal(0, onlineEvent.PlayerId); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineEventPublisherConsumerTests.cs b/Tests/GameFrameX.Tests/Online/OnlineEventPublisherConsumerTests.cs index 154493f19..d5d203124 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineEventPublisherConsumerTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineEventPublisherConsumerTests.cs @@ -80,8 +80,6 @@ private static OnlineEvent CreateSampleEvent() EventType = "online.session.kicked", OccurredTime = 1760000000999, SchemaVersion = 1, - TenantId = 1, - AppId = 10, ServerId = 100, PlayerId = 10001, Source = "online-identity", @@ -112,8 +110,6 @@ public void PublishAsync_ShouldDelegateToCapabilityPublisherWithEventTypeAsTopic Assert.Same(onlineEvent, payload); Assert.Equal("evt-0004", payload.EventId); Assert.Equal("req-0004", payload.CorrelationId); - Assert.Equal(1, payload.TenantId); - Assert.Equal(10, payload.AppId); Assert.Equal(100, payload.ServerId); Assert.Equal(10001, payload.PlayerId); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineEventSanitizerTests.cs b/Tests/GameFrameX.Tests/Online/OnlineEventSanitizerTests.cs index 9ef63b305..ff41eea3a 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineEventSanitizerTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineEventSanitizerTests.cs @@ -49,8 +49,6 @@ private static OnlineEvent CreateEventWithAuditFields(IDictionary测试用租户标识(与族配置段授权作用域一致)。 - private const long TenantId = OnlineCapabilityTestHarness.TenantId; - - /// 测试用应用标识。 - private const long AppId = OnlineCapabilityTestHarness.AppId; /// 测试用区服标识(与族配置段授权作用域一致)。 private const long ServerId = OnlineCapabilityTestHarness.ServerId; @@ -67,13 +62,13 @@ public class OnlineFriendConsumptionChainAssemblyTests private const long PlayerTwo = 1002; /// - /// 构造玩家作用域(作用域三元组与测试常量一致)。 + /// 构造玩家作用域(作用域区服键与测试常量一致)。 /// /// 玩家标识。 /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// @@ -86,7 +81,7 @@ private static CapabilityCompositionOptions CreateOptionsWithDirectory(IOnlinePl { var options = new CapabilityCompositionOptions(OnlineCapabilityTestHarness.FamilySection(), new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = TenantId, AppId = AppId, ServerId = ServerId, }, + HostOptions = new CapabilityHostOptions { ServerId = ServerId, }, }; options.Override(directory); options.Override(new OnlineCapabilityTestHarness.NoopHotfixRollbackExecutor()); @@ -97,20 +92,16 @@ private static CapabilityCompositionOptions CreateOptionsWithDirectory(IOnlinePl /// 直接向存储落一条已超期的待答复请求(清扫用例的种子数据;不经过服务以控制时间戳)。 /// /// 好友存储。 - /// 租户标识。 - /// App 标识。 /// 发起方。 /// 被请求方。 /// 落库后的关系记录。 - private static async Task SeedExpiredRequestAsync(IOnlineFriendStore store, long tenantId, long appId, long requesterId, long addresseeId) + private static async Task SeedExpiredRequestAsync(IOnlineFriendStore store, long requesterId, long addresseeId) { OnlineFriendship.Canonicalize(requesterId, addresseeId, out var low, out var high); var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); return await store.SaveIfAbsentAsync(new OnlineFriendship { FriendshipId = "frd-seed-" + Guid.NewGuid().ToString("N"), - TenantId = tenantId, - AppId = appId, ServerId = ServerId, LowPlayerId = low, HighPlayerId = high, @@ -162,14 +153,14 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => var request = await service.RequestAsync(CreatePlayerScope(PlayerOne), PlayerTwo, "corr-2"); Assert.True(request.IsSuccess); - Assert.NotNull(await store.FindAsync(TenantId, AppId, PlayerOne, PlayerTwo)); + Assert.NotNull(await store.FindAsync(PlayerOne, PlayerTwo)); - await SeedExpiredRequestAsync(store, TenantId, AppId, PlayerTwo, PlayerOne + 10); + await SeedExpiredRequestAsync(store, PlayerTwo, PlayerOne + 10); await runtime.Host.Scheduler.TickAsync(); - var expired = await store.FindAsync(TenantId, AppId, PlayerTwo, PlayerOne + 10); + var expired = await store.FindAsync(PlayerTwo, PlayerOne + 10); Assert.Equal(OnlineFriendshipState.Expired, expired.State); - var live = await store.FindAsync(TenantId, AppId, PlayerOne, PlayerTwo); + var live = await store.FindAsync(PlayerOne, PlayerTwo); Assert.Equal(OnlineFriendshipState.Requested, live.State); }); } @@ -182,7 +173,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => public async Task OverrideFriendStore_PreSeed_DrivesServiceAndSweepOnSameStateSource() { var preSeeded = new InMemoryOnlineFriendStore(); - await SeedExpiredRequestAsync(preSeeded, TenantId, AppId, PlayerOne, PlayerTwo); + await SeedExpiredRequestAsync(preSeeded, PlayerOne, PlayerTwo); await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => { @@ -192,11 +183,11 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => var service = runtime.Host.Services.GetService(); var request = await service.RequestAsync(CreatePlayerScope(PlayerTwo), PlayerOne + 10); Assert.True(request.IsSuccess); - Assert.NotNull(await preSeeded.FindAsync(TenantId, AppId, PlayerTwo, PlayerOne + 10)); + Assert.NotNull(await preSeeded.FindAsync(PlayerTwo, PlayerOne + 10)); await runtime.Host.Scheduler.TickAsync(); - var expired = await preSeeded.FindAsync(TenantId, AppId, PlayerOne, PlayerTwo); + var expired = await preSeeded.FindAsync(PlayerOne, PlayerTwo); Assert.Equal(OnlineFriendshipState.Expired, expired.State); }, null, options => options.Override(preSeeded)); } @@ -291,25 +282,22 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => } /// - /// 清扫的作用域隔离:滴答 job 经族基建授权作用域锚定租户 / App—— - /// 其余租户或 App 的超期请求不被本宿主触碰。 + /// 清扫的全局覆盖:好友关系为全局键,滴答 job 终结全部超期请求(不同玩家对互不遮蔽)。 /// [Fact] - public async Task Sweep_ScopedToAuthorizedTenantAndApp() + public async Task Sweep_ExpiredRequestsAcrossPlayerPairs_AllSwept() { await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => { var store = runtime.Host.Services.GetService(); - await SeedExpiredRequestAsync(store, TenantId, AppId, PlayerOne, PlayerTwo); - await SeedExpiredRequestAsync(store, TenantId + 1, AppId, PlayerOne, PlayerTwo); - await SeedExpiredRequestAsync(store, TenantId, AppId + 1, PlayerOne, PlayerTwo); + await SeedExpiredRequestAsync(store, PlayerOne, PlayerTwo); + await SeedExpiredRequestAsync(store, PlayerTwo, PlayerOne + 10); await runtime.Host.StartAsync(); await runtime.Host.Scheduler.TickAsync(); - Assert.Equal(OnlineFriendshipState.Expired, (await store.FindAsync(TenantId, AppId, PlayerOne, PlayerTwo)).State); - Assert.Equal(OnlineFriendshipState.Requested, (await store.FindAsync(TenantId + 1, AppId, PlayerOne, PlayerTwo)).State); - Assert.Equal(OnlineFriendshipState.Requested, (await store.FindAsync(TenantId, AppId + 1, PlayerOne, PlayerTwo)).State); + Assert.Equal(OnlineFriendshipState.Expired, (await store.FindAsync(PlayerOne, PlayerTwo)).State); + Assert.Equal(OnlineFriendshipState.Expired, (await store.FindAsync(PlayerTwo, PlayerOne + 10)).State); }); } @@ -325,14 +313,14 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => var store = runtime.Host.Services.GetService(); await runtime.Host.StartAsync(); - await SeedExpiredRequestAsync(store, TenantId, AppId, PlayerOne, PlayerTwo); - var swept = await UntilAsync(async () => (await store.FindAsync(TenantId, AppId, PlayerOne, PlayerTwo))?.State == OnlineFriendshipState.Expired, 5000); + await SeedExpiredRequestAsync(store, PlayerOne, PlayerTwo); + var swept = await UntilAsync(async () => (await store.FindAsync(PlayerOne, PlayerTwo))?.State == OnlineFriendshipState.Expired, 5000); Assert.True(swept); await runtime.Host.StopAsync(); - await SeedExpiredRequestAsync(store, TenantId, AppId, PlayerTwo, PlayerOne + 10); + await SeedExpiredRequestAsync(store, PlayerTwo, PlayerOne + 10); await Task.Delay(600); - Assert.Equal(OnlineFriendshipState.Requested, (await store.FindAsync(TenantId, AppId, PlayerTwo, PlayerOne + 10)).State); + Assert.Equal(OnlineFriendshipState.Requested, (await store.FindAsync(PlayerTwo, PlayerOne + 10)).State); }, null, options => options.HostOptions.SchedulerIntervalMilliseconds = 100); } @@ -371,13 +359,11 @@ public void Add(long playerId, string name) } /// 按名称子串检索。 - /// 租户标识。 - /// App 标识。 /// 名称关键字。 /// 返回条数上限。 /// 取消令牌。 /// 匹配的目录条目。 - public Task> SearchByNameAsync(long tenantId, long appId, string keyword, int limit, CancellationToken cancellationToken = default) + public Task> SearchByNameAsync(string keyword, int limit, CancellationToken cancellationToken = default) { var matched = new List(); foreach (var entry in _entries) @@ -397,12 +383,10 @@ public Task> SearchByNameAsync(long te } /// 按标识批量解析。 - /// 租户标识。 - /// App 标识。 /// 玩家标识集合。 /// 取消令牌。 /// 命中标识的目录条目。 - public Task> FindAsync(long tenantId, long appId, IReadOnlyList playerIds, CancellationToken cancellationToken = default) + public Task> FindAsync(IReadOnlyList playerIds, CancellationToken cancellationToken = default) { var matched = new List(); foreach (var entry in _entries) @@ -435,12 +419,10 @@ public void SetOnline(long playerId) } /// 白名单判定。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 在白名单中返回 true。 - public Task IsOnlineAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task IsOnlineAsync(long playerId, CancellationToken cancellationToken = default) { return Task.FromResult(_online.Contains(playerId)); } @@ -476,69 +458,57 @@ public Task SaveIfAbsentAsync(OnlineFriendship friendship, Can } /// 委托内层。 - /// 租户标识。 - /// App 标识。 /// 一侧玩家标识。 /// 另一侧玩家标识。 /// 取消令牌。 /// 关系副本;不存在返回 null。 - public Task FindAsync(long tenantId, long appId, long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default) + public Task FindAsync(long leftPlayerId, long rightPlayerId, CancellationToken cancellationToken = default) { - return _inner.FindAsync(tenantId, appId, leftPlayerId, rightPlayerId, cancellationToken); + return _inner.FindAsync(leftPlayerId, rightPlayerId, cancellationToken); } /// 委托内层。 - /// 租户标识。 - /// App 标识。 /// 状态迁移载荷。 /// 取消令牌。 /// 更新后的关系副本;CAS 失败或记录不存在返回 null。 - public Task UpdateStateAsync(long tenantId, long appId, FriendshipStateTransition transition, CancellationToken cancellationToken = default) + public Task UpdateStateAsync(FriendshipStateTransition transition, CancellationToken cancellationToken = default) { - return _inner.UpdateStateAsync(tenantId, appId, transition, cancellationToken); + return _inner.UpdateStateAsync(transition, cancellationToken); } /// 委托内层。 - /// 租户标识。 - /// App 标识。 /// 状态迁移载荷。 /// 已建立好友数上限(<= 0 表示不启用上限判定)。 /// 取消令牌。 /// 迁移结果:成功携带更新后的副本;上限拒绝置 FriendLimitReached;CAS 失败两者皆空。 - public Task UpdateStateWithFriendLimitAsync(long tenantId, long appId, FriendshipStateTransition transition, int establishedFriendLimit, CancellationToken cancellationToken = default) + public Task UpdateStateWithFriendLimitAsync(FriendshipStateTransition transition, int establishedFriendLimit, CancellationToken cancellationToken = default) { - return _inner.UpdateStateWithFriendLimitAsync(tenantId, appId, transition, establishedFriendLimit, cancellationToken); + return _inner.UpdateStateWithFriendLimitAsync(transition, establishedFriendLimit, cancellationToken); } /// 委托内层。 - /// 租户标识。 - /// App 标识。 /// 重新发起载荷。 /// 取消令牌。 /// 更新后的关系副本;CAS 失败或记录不存在返回 null。 - public Task RenewRequestAsync(long tenantId, long appId, FriendshipRenewal renewal, CancellationToken cancellationToken = default) + public Task RenewRequestAsync(FriendshipRenewal renewal, CancellationToken cancellationToken = default) { - return _inner.RenewRequestAsync(tenantId, appId, renewal, cancellationToken); + return _inner.RenewRequestAsync(renewal, cancellationToken); } /// 委托内层。 - /// 租户标识。 - /// App 标识。 /// 玩家标识。 /// 取消令牌。 /// 关系副本列表。 - public Task> ListByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListByPlayerAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListByPlayerAsync(playerId, cancellationToken); } /// 清扫输入面:计数后抛异常。 - /// 租户标识。 - /// App 标识。 /// 关系状态。 /// 取消令牌。 /// 不返回(恒抛)。 - public Task> ListByStateAsync(long tenantId, long appId, OnlineFriendshipState state, CancellationToken cancellationToken = default) + public Task> ListByStateAsync(OnlineFriendshipState state, CancellationToken cancellationToken = default) { Interlocked.Increment(ref _sweepInputFailures); throw new InvalidOperationException("friend sweep input failure (test)"); diff --git a/Tests/GameFrameX.Tests/Online/OnlineFriendDomainBridgeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineFriendDomainBridgeTests.cs index 84188d690..7c18bcdbd 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineFriendDomainBridgeTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineFriendDomainBridgeTests.cs @@ -64,13 +64,13 @@ private static void SocialClosure(CapabilityCompositionOptions options) } /// - /// 构造玩家作用域(三元组与族配置段一致)。 + /// 构造玩家作用域(区服键与族配置段一致)。 /// /// 玩家标识。 /// 玩家作用域。 private static OnlineScope PlayerScope(long playerId) { - return new OnlineScope(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId, playerId); + return new OnlineScope(OnlineCapabilityTestHarness.ServerId, playerId); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineFriendLegacyMigrationTests.cs b/Tests/GameFrameX.Tests/Online/OnlineFriendLegacyMigrationTests.cs index a454e2d1f..50b9e2de7 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineFriendLegacyMigrationTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineFriendLegacyMigrationTests.cs @@ -106,7 +106,7 @@ private static async Task WithStartedSocialRuntimeAsync(Func(new OnlineCapabilityTestHarness.EmptyPlayerDirectory()); @@ -131,7 +131,7 @@ private static async Task WithStartedSocialRuntimeAsync(Func玩家作用域。 private static OnlineScope PlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// @@ -182,7 +182,7 @@ await WithStartedSocialRuntimeAsync(async runtime => { var friends = runtime.Host.Services.GetService(); - var (established, pending, failed) = await OnlineFriendLegacyMigration.MigrateAsync(friends, TenantId, AppId, ServerId); + var (established, pending, failed) = await OnlineFriendLegacyMigration.MigrateAsync(friends, ServerId); Assert.Equal(1, established); Assert.Equal(1, pending); @@ -215,8 +215,8 @@ await WithStartedSocialRuntimeAsync(async runtime => { var friends = runtime.Host.Services.GetService(); - await OnlineFriendLegacyMigration.MigrateAsync(friends, TenantId, AppId, ServerId); - var (established, pending, failed) = await OnlineFriendLegacyMigration.MigrateAsync(friends, TenantId, AppId, ServerId); + await OnlineFriendLegacyMigration.MigrateAsync(friends, ServerId); + var (established, pending, failed) = await OnlineFriendLegacyMigration.MigrateAsync(friends, ServerId); Assert.Equal(1, established); Assert.Equal(1, pending); diff --git a/Tests/GameFrameX.Tests/Online/OnlineFriendServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineFriendServiceTests.cs index e121f8b93..c9767940c 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineFriendServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineFriendServiceTests.cs @@ -44,11 +44,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineFriendServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; /// 测试用区服标识。 private const long ServerId = 100; @@ -91,7 +86,7 @@ public async Task RequestAsync_ShouldCreateSinglePendingRecordAndConvergeOnRepea Assert.True(repeated.IsSuccess); Assert.Equal(outcome.Data.FriendshipId, repeated.Data.FriendshipId); - Assert.Single(await store.ListByPlayerAsync(TenantId, AppId, PlayerOne)); + Assert.Single(await store.ListByPlayerAsync(PlayerOne)); Assert.Equal(1, recorder.Count); // 待答复列表只在被请求方(AddresseeId)一侧可见。 @@ -287,7 +282,7 @@ public async Task RequestAsync_AfterRejected_ShouldReopenExistingRecordWithNewRe Assert.Equal(OnlineFriendshipState.Requested, reopened.Data.State); Assert.Equal(PlayerTwo, reopened.Data.RequesterId); Assert.Equal(PlayerOne, reopened.Data.AddresseeId); - Assert.Single(await store.ListByPlayerAsync(TenantId, AppId, PlayerOne)); + Assert.Single(await store.ListByPlayerAsync(PlayerOne)); var pendingForNewAddressee = await service.ListPendingRequestsAsync(CreatePlayerScope(PlayerOne)); Assert.True(pendingForNewAddressee.IsSuccess); @@ -365,7 +360,7 @@ public async Task RequestAsync_AfterRemoved_ShouldReopenExistingRecordWithNewReq Assert.Equal(OnlineFriendshipState.Requested, reopened.Data.State); Assert.Equal(PlayerTwo, reopened.Data.RequesterId); Assert.Equal(PlayerOne, reopened.Data.AddresseeId); - Assert.Single(await store.ListByPlayerAsync(TenantId, AppId, PlayerOne)); + Assert.Single(await store.ListByPlayerAsync(PlayerOne)); } /// @@ -380,9 +375,9 @@ public async Task SweepExpiredAsync_WhenRequestOverdue_ShouldExpireAndReturnAffe var request = await RequestAsync(service, PlayerOne, PlayerTwo); // Act - var notDue = await service.SweepExpiredAsync(TenantId, AppId, request.ExpiresAtTime - 1); - var outcome = await service.SweepExpiredAsync(TenantId, AppId, request.ExpiresAtTime + 1); - var repeated = await service.SweepExpiredAsync(TenantId, AppId, request.ExpiresAtTime + 1); + var notDue = await service.SweepExpiredAsync(request.ExpiresAtTime - 1); + var outcome = await service.SweepExpiredAsync(request.ExpiresAtTime + 1); + var repeated = await service.SweepExpiredAsync(request.ExpiresAtTime + 1); // Assert Assert.True(notDue.IsSuccess); @@ -392,7 +387,7 @@ public async Task SweepExpiredAsync_WhenRequestOverdue_ShouldExpireAndReturnAffe Assert.Equal(1, outcome.Data); Assert.Equal(0, repeated.Data); - var stored = await store.FindAsync(TenantId, AppId, PlayerOne, PlayerTwo); + var stored = await store.FindAsync(PlayerOne, PlayerTwo); Assert.NotNull(stored); Assert.Equal(OnlineFriendshipState.Expired, stored.State); @@ -438,7 +433,7 @@ public async Task AcceptAsync_WhenFriendLimitReached_ShouldRejectAndNotPersist() Assert.Equal(OnlineErrorCode.StateOperationForbidden, outcome.Code); // 请求仍然停在待答复态,没有变成好友(拒绝必须是干净的)。 - var rows = await store.ListByPlayerAsync(TenantId, AppId, PlayerFour); + var rows = await store.ListByPlayerAsync(PlayerFour); var stillPending = Assert.Single(rows); Assert.Equal(third.FriendshipId, stillPending.FriendshipId); Assert.Equal(OnlineFriendshipState.Requested, stillPending.State); @@ -498,7 +493,7 @@ public async Task AcceptAsync_ConcurrentAccepts_ShouldNotExceedFriendLimit() var rejected = Assert.Single(accepts, outcome => !outcome.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, rejected.Code); - var rows = await store.ListByPlayerAsync(TenantId, AppId, PlayerOne); + var rows = await store.ListByPlayerAsync(PlayerOne); Assert.Equal(2, rows.Count(row => row.State == OnlineFriendshipState.Accepted)); var stillPending = Assert.Single(rows, row => row.State == OnlineFriendshipState.Requested); Assert.Contains(stillPending.FriendshipId, new[] { first.FriendshipId, second.FriendshipId, third.FriendshipId }); @@ -521,7 +516,7 @@ public async Task RequestAsync_WhenRequesterFriendLimitReached_ShouldRejectWitho // Assert Assert.False(outcome.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, outcome.Code); - Assert.Empty(await store.ListByPlayerAsync(TenantId, AppId, PlayerFour)); + Assert.Empty(await store.ListByPlayerAsync(PlayerFour)); } /// @@ -541,7 +536,7 @@ public async Task RequestAsync_WhenTargetFriendLimitReached_ShouldRejectWithoutP // Assert Assert.False(outcome.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, outcome.Code); - Assert.Empty(await store.ListByPlayerAsync(TenantId, AppId, PlayerTwo)); + Assert.Empty(await store.ListByPlayerAsync(PlayerTwo)); } /// @@ -567,7 +562,7 @@ public async Task RequestAsync_AfterRemoval_WhenTargetFriendLimitReached_ShouldR // Assert Assert.False(outcome.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, outcome.Code); - var rows = await store.ListByPlayerAsync(TenantId, AppId, PlayerOne); + var rows = await store.ListByPlayerAsync(PlayerOne); var pair = Assert.Single(rows, row => row.OtherOf(PlayerOne) == PlayerTwo); Assert.Equal(OnlineFriendshipState.Removed, pair.State); } @@ -629,7 +624,7 @@ public async Task ListFriendsAsync_ShouldReadPresenceLiveWithoutPersistingIt() var probe = new StubPresenceProbe(); var service = CreateService(out _, out var store, presenceProbe: probe); await EstablishFriendshipAsync(service, PlayerOne, PlayerTwo); - var storedBefore = await store.FindAsync(TenantId, AppId, PlayerOne, PlayerTwo); + var storedBefore = await store.FindAsync(PlayerOne, PlayerTwo); // Act var offline = await service.ListFriendsAsync(CreatePlayerScope(PlayerOne)); @@ -643,7 +638,7 @@ public async Task ListFriendsAsync_ShouldReadPresenceLiveWithoutPersistingIt() Assert.True(Assert.Single(online.Data).Online); // 在线事实不落库:OnlineFriendship 无在线字段,落库记录亦未被读取行为改写。 - var storedAfter = await store.FindAsync(TenantId, AppId, PlayerOne, PlayerTwo); + var storedAfter = await store.FindAsync(PlayerOne, PlayerTwo); Assert.NotNull(storedAfter); Assert.Equal(storedBefore.State, storedAfter.State); Assert.Equal(storedBefore.RespondedAtTime, storedAfter.RespondedAtTime); @@ -703,8 +698,6 @@ public async Task FriendshipLifecycle_ShouldPublishChangedEventsWithAction() Assert.Equal(PlayerOne, events[1].PlayerId); Assert.Equal(PlayerOne, events[2].PlayerId); Assert.Equal(request.Data.FriendshipId, events[0].PayloadAuditFields["FriendshipId"]); - Assert.Equal(TenantId, events[2].TenantId); - Assert.Equal(AppId, events[2].AppId); Assert.Equal(ServerId, events[2].ServerId); } @@ -761,7 +754,7 @@ private static OnlineFriendService CreateService( /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// @@ -841,13 +834,11 @@ public void Add(long playerId, string name) /// Records the keyword and limit, then returns the registered entries whose /// display name contains the keyword, truncated to the limit. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 名称关键字 / The name keyword /// 返回条数上限 / The maximum number of entries /// 取消令牌 / Cancellation token /// 名称含关键字的目录条目(至多 limit 条)/ Directory entries whose name contains the keyword (at most limit) - public Task> SearchByNameAsync(long tenantId, long appId, string keyword, int limit, CancellationToken cancellationToken = default) + public Task> SearchByNameAsync(string keyword, int limit, CancellationToken cancellationToken = default) { LastKeyword = keyword; LastSearchLimit = limit; @@ -875,12 +866,10 @@ public Task> SearchByNameAsync(long te /// Returns the registered entries whose player id appears in the given set; /// unknown ids are simply absent from the result. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识集合 / The player ids to resolve /// 取消令牌 / Cancellation token /// 命中标识的目录条目 / The matched directory entries - public Task> FindAsync(long tenantId, long appId, IReadOnlyList playerIds, CancellationToken cancellationToken = default) + public Task> FindAsync(IReadOnlyList playerIds, CancellationToken cancellationToken = default) { var matched = new List(); foreach (var entry in _entries) @@ -923,12 +912,10 @@ public void SetOnline(long playerId) /// Only checks whether the player is in the online whitelist set /// (mutable mid-test via ). /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌 / Cancellation token /// 在白名单中返回 true / True when present in the whitelist - public Task IsOnlineAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task IsOnlineAsync(long playerId, CancellationToken cancellationToken = default) { return Task.FromResult(_online.Contains(playerId)); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineGameDbStorePersistenceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineGameDbStorePersistenceTests.cs index 8a69651b0..f58198c4f 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineGameDbStorePersistenceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineGameDbStorePersistenceTests.cs @@ -47,6 +47,7 @@ namespace GameFrameX.Tests.Online; using GameFrameX.DataBase.Sqlite; using GameFrameX.Foundation.Idempotency; using Xunit; +using GameFrameX.Capability.Online.Abstractions.Keys; /// /// Online 一级 store 的 GameDb 适配层测试(Identity / PlayerStorage / 资产账本三域)。 @@ -64,16 +65,6 @@ namespace GameFrameX.Tests.Online; [Collection("GameDbStaticStateCollection")] public sealed class OnlineGameDbStorePersistenceTests { - /// - /// 测试作用域租户标识。 - /// - private const long TenantId = 7L; - - /// - /// 测试作用域 App 标识。 - /// - private const long AppId = 3L; - /// /// 门面初始化后必须归还(关闭 + 复位静态注册表;串行集合保证静态门面独占)。 /// @@ -97,7 +88,7 @@ private static async Task WithSqliteFacadeAsync(Func action, string name = } /// - /// 身份域全生命周期事实:四元组唯一查找 / 覆盖写 / 归属列举 / 设备二元组 / 自然主键覆盖。 + /// 身份域全生命周期事实:身份键唯一查找 / 覆盖写 / 归属列举 / 设备二元组 / 自然主键覆盖。 /// [Fact] public async Task IdentityStore_FullCycle_ShouldRoundTrip() @@ -107,14 +98,12 @@ await WithSqliteFacadeAsync(async () => var store = new GameDbOnlineIdentityStore(); // 未命中返回 null。 - Assert.Null(await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "user@example.com")); + Assert.Null(await store.FindIdentityAsync(OnlineIdentityKind.Email, "user@example.com")); // 新建 → 按唯一键读回全字段。 var identity = new OnlineIdentity { Id = "idn-1", - TenantId = TenantId, - AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "user@example.com", GameAccountId = 101, @@ -123,28 +112,28 @@ await WithSqliteFacadeAsync(async () => UnboundAtTime = 0, }; await store.AddOrUpdateIdentityAsync(identity); - var loaded = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "user@example.com"); + var loaded = await store.FindIdentityAsync(OnlineIdentityKind.Email, "user@example.com"); Assert.NotNull(loaded); Assert.Equal("idn-1", loaded.Id); Assert.Equal(101, loaded.GameAccountId); Assert.Equal(OnlineIdentityKind.Email, loaded.Kind); Assert.Equal(1000, loaded.CreatedAtTime); - // 同四元组覆盖写(换绑账号):仍为一行、字段覆盖。 + // 同身份键覆盖写(换绑账号):仍为一行、字段覆盖。 identity.GameAccountId = 202; identity.UpdatedAtTime = 2000; await store.AddOrUpdateIdentityAsync(identity); - var rebound = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "user@example.com"); + var rebound = await store.FindIdentityAsync(OnlineIdentityKind.Email, "user@example.com"); Assert.Equal(202, rebound.GameAccountId); Assert.Single(await store.ListIdentitiesAsync(202)); // 账号 / 玩家档案:自然主键覆盖写 + 归属列举按创建时间升序。 - await store.AddOrUpdateAccountAsync(new OnlineGameAccount { Id = 101, TenantId = TenantId, AppId = AppId, Status = OnlineGameAccountStatus.Active, CreatedAtTime = 1, UpdatedAtTime = 2, }); + await store.AddOrUpdateAccountAsync(new OnlineGameAccount { Id = 101, Status = OnlineGameAccountStatus.Active, CreatedAtTime = 1, UpdatedAtTime = 2, }); Assert.Equal(OnlineGameAccountStatus.Active, (await store.FindAccountAsync(101)).Status); - await store.AddOrUpdatePlayerAsync(new OnlinePlayerProfile { Id = 1, GameAccountId = 101, TenantId = TenantId, AppId = AppId, ServerId = 5, Name = "p1", CreatedAtTime = 10, }); - await store.AddOrUpdatePlayerAsync(new OnlinePlayerProfile { Id = 2, GameAccountId = 101, TenantId = TenantId, AppId = AppId, ServerId = 5, Name = "p2", CreatedAtTime = 20, }); - await store.AddOrUpdatePlayerAsync(new OnlinePlayerProfile { Id = 3, GameAccountId = 101, TenantId = TenantId, AppId = AppId, ServerId = 6, Name = "other-server", CreatedAtTime = 30, }); - Assert.Equal(new long[] { 1, 2 }, (await store.ListPlayersAsync(101, AppId, 5)).Select(player => player.Id).ToArray()); + await store.AddOrUpdatePlayerAsync(new OnlinePlayerProfile { Id = 1, GameAccountId = 101, ServerId = 5, Name = "p1", CreatedAtTime = 10, }); + await store.AddOrUpdatePlayerAsync(new OnlinePlayerProfile { Id = 2, GameAccountId = 101, ServerId = 5, Name = "p2", CreatedAtTime = 20, }); + await store.AddOrUpdatePlayerAsync(new OnlinePlayerProfile { Id = 3, GameAccountId = 101, ServerId = 6, Name = "other-server", CreatedAtTime = 30, }); + Assert.Equal(new long[] { 1, 2 }, (await store.ListPlayersAsync(101, 5)).Select(player => player.Id).ToArray()); Assert.Equal(new long[] { 1, 2, 3 }, (await store.ListAllPlayersAsync(101)).Select(player => player.Id).ToArray()); // 设备二元组唯一键:新建 → 覆盖读回。 @@ -185,8 +174,6 @@ await WithSqliteFacadeAsync(async () => var identity = new OnlineIdentity { Id = "idn-cas-1", - TenantId = TenantId, - AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 101, @@ -197,26 +184,26 @@ await WithSqliteFacadeAsync(async () => // 唯一插入:首插成功建档版本 1;同键冲突 false 且零覆写。 Assert.True(await store.TryAddIdentityAsync(identity)); - var winner = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "cas@example.com"); + var winner = await store.FindIdentityAsync(OnlineIdentityKind.Email, "cas@example.com"); Assert.Equal(1, winner.RowVersion); - var contender = new OnlineIdentity { Id = "idn-cas-2", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 202, CreatedAtTime = 1000, UpdatedAtTime = 1000, }; + var contender = new OnlineIdentity { Id = "idn-cas-2", Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 202, CreatedAtTime = 1000, UpdatedAtTime = 1000, }; Assert.False(await store.TryAddIdentityAsync(contender)); - Assert.Equal(101, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "cas@example.com")).GameAccountId); + Assert.Equal(101, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "cas@example.com")).GameAccountId); // CAS:匹配版本写入并推进到 2;过期版本拒绝零写入。 - var rebound = new OnlineIdentity { Id = "idn-cas-1", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 202, CreatedAtTime = 1000, UpdatedAtTime = 2000, UnboundAtTime = 0, }; + var rebound = new OnlineIdentity { Id = "idn-cas-1", Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 202, CreatedAtTime = 1000, UpdatedAtTime = 2000, UnboundAtTime = 0, }; Assert.True(await store.TryUpdateIdentityIfRowVersionAsync(rebound, winner.RowVersion)); - var updated = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "cas@example.com"); + var updated = await store.FindIdentityAsync(OnlineIdentityKind.Email, "cas@example.com"); Assert.Equal(202, updated.GameAccountId); Assert.Equal(2, updated.RowVersion); - var stale = new OnlineIdentity { Id = "idn-cas-1", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 303, CreatedAtTime = 1000, UpdatedAtTime = 3000, UnboundAtTime = 0, }; + var stale = new OnlineIdentity { Id = "idn-cas-1", Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 303, CreatedAtTime = 1000, UpdatedAtTime = 3000, UnboundAtTime = 0, }; Assert.False(await store.TryUpdateIdentityIfRowVersionAsync(stale, 1)); - Assert.Equal(202, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "cas@example.com")).GameAccountId); + Assert.Equal(202, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "cas@example.com")).GameAccountId); // 盲写:覆盖账号但保留存量行版本(不推进、不抹空)。 - var blind = new OnlineIdentity { Id = "idn-cas-1", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 404, CreatedAtTime = 1000, UpdatedAtTime = 4000, UnboundAtTime = 0, }; + var blind = new OnlineIdentity { Id = "idn-cas-1", Kind = OnlineIdentityKind.Email, Identifier = "cas@example.com", GameAccountId = 404, CreatedAtTime = 1000, UpdatedAtTime = 4000, UnboundAtTime = 0, }; await store.AddOrUpdateIdentityAsync(blind); - var afterBlindWrite = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "cas@example.com"); + var afterBlindWrite = await store.FindIdentityAsync(OnlineIdentityKind.Email, "cas@example.com"); Assert.Equal(404, afterBlindWrite.GameAccountId); Assert.Equal(2, afterBlindWrite.RowVersion); }); @@ -237,10 +224,8 @@ await WithSqliteFacadeAsync(async () => var legacyState = new OnlineIdentityState { Id = rowId, - UniqueKey = TenantId + ":" + AppId + ":" + (int)OnlineIdentityKind.Email + ":" + "legacy@example.com", + UniqueKey = OnlineRowKey.Identity((int)OnlineIdentityKind.Email, "legacy@example.com"), EntityId = "idn-legacy-1", - TenantId = TenantId, - AppId = AppId, Kind = (int)OnlineIdentityKind.Email, Identifier = "legacy@example.com", GameAccountId = 101, @@ -251,17 +236,17 @@ await WithSqliteFacadeAsync(async () => await GameDb.AddOrUpdateAsync(legacyState); // 读回映射为版本 0;以期望 0 CAS(领养)成功并播种版本 1;此后正常 CAS 生效。 - var legacy = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "legacy@example.com"); + var legacy = await store.FindIdentityAsync(OnlineIdentityKind.Email, "legacy@example.com"); Assert.NotNull(legacy); Assert.Equal(0, legacy.RowVersion); - var adopted = new OnlineIdentity { Id = legacy.Id, TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "legacy@example.com", GameAccountId = 202, CreatedAtTime = legacy.CreatedAtTime, UpdatedAtTime = 2000, UnboundAtTime = 0, }; + var adopted = new OnlineIdentity { Id = legacy.Id, Kind = OnlineIdentityKind.Email, Identifier = "legacy@example.com", GameAccountId = 202, CreatedAtTime = legacy.CreatedAtTime, UpdatedAtTime = 2000, UnboundAtTime = 0, }; Assert.True(await store.TryUpdateIdentityIfRowVersionAsync(adopted, 0)); - var afterAdoption = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "legacy@example.com"); + var afterAdoption = await store.FindIdentityAsync(OnlineIdentityKind.Email, "legacy@example.com"); Assert.Equal(202, afterAdoption.GameAccountId); Assert.Equal(1, afterAdoption.RowVersion); - var nextWrite = new OnlineIdentity { Id = legacy.Id, TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "legacy@example.com", GameAccountId = 303, CreatedAtTime = legacy.CreatedAtTime, UpdatedAtTime = 3000, UnboundAtTime = 0, }; + var nextWrite = new OnlineIdentity { Id = legacy.Id, Kind = OnlineIdentityKind.Email, Identifier = "legacy@example.com", GameAccountId = 303, CreatedAtTime = legacy.CreatedAtTime, UpdatedAtTime = 3000, UnboundAtTime = 0, }; Assert.True(await store.TryUpdateIdentityIfRowVersionAsync(nextWrite, 1)); - Assert.Equal(303, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "legacy@example.com")).GameAccountId); + Assert.Equal(303, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "legacy@example.com")).GameAccountId); }); } @@ -274,7 +259,7 @@ public async Task StorageStore_CreateCasSoftDeleteRevive_ShouldMatchContract() await WithSqliteFacadeAsync(async () => { var store = new GameDbOnlinePlayerStorageStore(); - var key = new OnlineStorageEntryKey { TenantId = TenantId, AppId = AppId, PlayerId = 9, Collection = "settings", Key = "volume", }; + var key = new OnlineStorageEntryKey { PlayerId = 9, Collection = "settings", Key = "volume", }; // 创建(expected=0):成功且读回 Version == 1(行 RowVersion 0 + 校准恒等式)。 Assert.True(await store.UpsertAsync(BuildEntry(key, new byte[] { 1, 2, 3 }, 1), 0)); @@ -294,7 +279,7 @@ await WithSqliteFacadeAsync(async () => Assert.Equal(2, (await store.FindAsync(key)).Version); // 行缺失 CAS 拒绝。 - var missingKey = new OnlineStorageEntryKey { TenantId = TenantId, AppId = AppId, PlayerId = 9, Collection = "settings", Key = "missing", }; + var missingKey = new OnlineStorageEntryKey { PlayerId = 9, Collection = "settings", Key = "missing", }; Assert.False(await store.UpsertAsync(BuildEntry(missingKey, new byte[] { 1 }, 1), 1)); // 软删:Find 可见 / List 不可见 / 活跃键数排除;ListAll 含软删(物理保留)。 @@ -303,7 +288,7 @@ await WithSqliteFacadeAsync(async () => Assert.True(await store.UpsertAsync(softDeleted, 2)); Assert.NotNull(await store.FindAsync(key)); Assert.Empty(await ListAsync(store, 9, "settings")); - Assert.Equal(0, await store.CountActiveKeysAsync(TenantId, AppId, 9, "settings")); + Assert.Equal(0, await store.CountActiveKeysAsync(9, "settings")); Assert.Single(await store.ListAllAsync()); // 复活:以软删条目版本(3)为期望 CAS 写回可见行。 @@ -312,7 +297,7 @@ await WithSqliteFacadeAsync(async () => Assert.Single(listed); Assert.Equal(4, listed[0].Version); Assert.Equal(0, listed[0].DeletedAtTime); - Assert.Equal(1, await store.CountActiveKeysAsync(TenantId, AppId, 9, "settings")); + Assert.Equal(1, await store.CountActiveKeysAsync(9, "settings")); }); } @@ -326,7 +311,7 @@ public async Task StorageService_ResurrectThroughGameDb_ShouldContinueVersionMon await WithSqliteFacadeAsync(async () => { var service = new OnlinePlayerStorageService(new GameDbOnlinePlayerStorageStore(), new OnlinePlayerStorageOptions()); - var scope = new OnlineScope(TenantId, AppId, 5, 21); + var scope = new OnlineScope(5, 21); // 创建 v1 → 软删 v2(DeleteAsync 版本推进)。 var created = await service.WriteAsync(scope, "settings", "theme", new byte[] { 1 }, 0, "sess-1"); @@ -368,12 +353,12 @@ await WithSqliteFacadeAsync(async () => var keys = new[] { "a", "B", "b", "Aa", "c", "z9", "Z", }; foreach (var entryKey in keys) { - var payloadKey = new OnlineStorageEntryKey { TenantId = TenantId, AppId = AppId, PlayerId = 11, Collection = "archive", Key = entryKey, }; + var payloadKey = new OnlineStorageEntryKey { PlayerId = 11, Collection = "archive", Key = entryKey, }; Assert.True(await store.UpsertAsync(BuildEntry(payloadKey, new byte[] { 1 }, 1), 0)); } // 另一集合的数据不得串页。 - var otherKey = new OnlineStorageEntryKey { TenantId = TenantId, AppId = AppId, PlayerId = 11, Collection = "other", Key = "a", }; + var otherKey = new OnlineStorageEntryKey { PlayerId = 11, Collection = "other", Key = "a", }; Assert.True(await store.UpsertAsync(BuildEntry(otherKey, new byte[] { 1 }, 1), 0)); // 全量分页(页大小 3)收集全部键,无重无漏、序 = ordinal 字典序。 @@ -381,7 +366,7 @@ await WithSqliteFacadeAsync(async () => string cursor = string.Empty; while (true) { - var page = await store.ListAsync(new OnlineStorageListQuery { TenantId = TenantId, AppId = AppId, PlayerId = 11, Collection = "archive", AfterKey = cursor, MaxCount = 3, }); + var page = await store.ListAsync(new OnlineStorageListQuery { PlayerId = 11, Collection = "archive", AfterKey = cursor, MaxCount = 3, }); if (page.Count == 0) { break; @@ -419,11 +404,11 @@ await WithSqliteFacadeAsync(async () => var firstTransactionId = first.Data.TransactionId; // 快照读回(直查 store)。 - var gold = await assetStore.FindWalletAsync(TenantId, AppId, 21, "gold"); + var gold = await assetStore.FindWalletAsync(21, "gold"); Assert.Equal(100, gold.Balance); Assert.Equal(1, gold.Version); - Assert.Equal(2, (await assetStore.FindInventoryAsync(TenantId, AppId, 21, "sword")).Quantity); - Assert.Equal(new[] { "gem", "gold" }, (await assetStore.ListWalletAccountsAsync(TenantId, AppId, 21)).Select(wallet => wallet.CurrencyId).ToArray()); + Assert.Equal(2, (await assetStore.FindInventoryAsync(21, "sword")).Quantity); + Assert.Equal(new[] { "gem", "gold" }, (await assetStore.ListWalletAccountsAsync(21)).Select(wallet => wallet.CurrencyId).ToArray()); // 余额不足整批拒绝:净效应 0(无新账本行、快照不动),交易落 Failed。 var overdrawn = await grantService.ExecuteAsync(Request(scope, "g3-overdrawn", new (OnlineAssetKind, string, long)[] @@ -433,8 +418,8 @@ await WithSqliteFacadeAsync(async () => })); Assert.False(overdrawn.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, overdrawn.Code); - Assert.Equal(100, (await assetStore.FindWalletAsync(TenantId, AppId, 21, "gold")).Balance); - Assert.Equal(3, (await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 21, AfterSequenceNumber = 0, MaxCount = 100, })).Count); + Assert.Equal(100, (await assetStore.FindWalletAsync(21, "gold")).Balance); + Assert.Equal(3, (await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 21, AfterSequenceNumber = 0, MaxCount = 100, })).Count); // 同一交易内资产重复:服务层参数拒绝。 var duplicate = await grantService.ExecuteAsync(Request(scope, "g3-duplicate", new (OnlineAssetKind, string, long)[] @@ -453,21 +438,21 @@ await WithSqliteFacadeAsync(async () => })); Assert.True(second.IsSuccess); // 账本序单调不稠密:拒绝批在预演期已取号作废(gold 行 seq 4),第二批续 5、6——与 InMemory 预演取号语义逐语句等价。 - var ledger = await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 21, AfterSequenceNumber = 0, MaxCount = 100, }); + var ledger = await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 21, AfterSequenceNumber = 0, MaxCount = 100, }); Assert.Equal(new long[] { 1, 2, 3, 5, 6 }, ledger.Select(entry => entry.SequenceNumber).ToArray()); - gold = await assetStore.FindWalletAsync(TenantId, AppId, 21, "gold"); + gold = await assetStore.FindWalletAsync(21, "gold"); Assert.Equal(70, gold.Balance); Assert.Equal(2, gold.Version); // 账本序游标分页 + 交易反查 + 聚合 + 玩家清单。 - var tail = await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 21, AfterSequenceNumber = 4, MaxCount = 2, }); + var tail = await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 21, AfterSequenceNumber = 4, MaxCount = 2, }); Assert.Equal(new long[] { 5, 6 }, tail.Select(entry => entry.SequenceNumber).ToArray()); Assert.Equal(new long[] { 1, 2, 3 }, (await assetStore.FindLedgerEntriesByTransactionIdAsync(firstTransactionId)).Select(entry => entry.SequenceNumber).ToArray()); - var sums = await assetStore.SumLedgerDeltasByAssetAsync(TenantId, AppId, 21); + var sums = await assetStore.SumLedgerDeltasByAssetAsync(21); Assert.Equal(70, sums["c:gold"]); Assert.Equal(5, sums["c:gem"]); Assert.Equal(3, sums["i:sword"]); - Assert.Equal(new long[] { 21 }, (await assetStore.ListPlayerIdsAsync(TenantId, AppId)).ToArray()); + Assert.Equal(new long[] { 21 }, (await assetStore.ListPlayerIdsAsync()).ToArray()); // 交易读回:成功交易终态 Succeeded + 外键列表;按状态列举含 Failed 拒绝单。 var settled = await transactionStore.FindAsync(firstTransactionId); @@ -504,7 +489,7 @@ await WithSqliteFacadeAsync(async () => var (serviceOne, scopeOne) = BuildGrantService(storeOne, new GameDbOnlineAssetTransactionStore(), playerId: 31); var seed = await serviceOne.ExecuteAsync(Request(scopeOne, "g1109-seed", new[] { (OnlineAssetKind.Currency, "gold", 100L) })); Assert.True(seed.IsSuccess); - Assert.Equal(100, (await storeOne.FindWalletAsync(TenantId, AppId, 31, "gold")).Balance); + Assert.Equal(100, (await storeOne.FindWalletAsync(31, "gold")).Balance); // 两实例并发各 +10:分片信号量各自独立,唯一串行化点是数据库事务。 var storeTwo = new GameDbOnlineAssetStore(); @@ -514,11 +499,11 @@ await WithSqliteFacadeAsync(async () => Task.Run(() => serviceTwo.ExecuteAsync(Request(scopeTwo, "g1109-b", new[] { (OnlineAssetKind.Currency, "gold", 10L) })))); Assert.All(results, result => Assert.True(result.IsSuccess)); - var wallet = await storeOne.FindWalletAsync(TenantId, AppId, 31, "gold"); + var wallet = await storeOne.FindWalletAsync(31, "gold"); Assert.Equal(120, wallet.Balance); // 账本链连续:预置 1 条 + 并发 2 条,按序每条 AmountBefore = 上一条 AmountAfter(无孤儿/断链)。 - var ledger = (await storeOne.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 31, AfterSequenceNumber = 0, MaxCount = 100, })).OrderBy(entry => entry.SequenceNumber).ToArray(); + var ledger = (await storeOne.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 31, AfterSequenceNumber = 0, MaxCount = 100, })).OrderBy(entry => entry.SequenceNumber).ToArray(); Assert.Equal(3, ledger.Length); Assert.Equal(0L, ledger[0].AmountBefore); for (var i = 1; i < ledger.Length; i++) @@ -554,12 +539,12 @@ await WithSqliteFacadeAsync(async () => Assert.All(results, result => Assert.True(result.IsSuccess)); // 只生成一行快照,两笔都入账。 - var wallets = await storeOne.ListWalletAccountsAsync(TenantId, AppId, 32); + var wallets = await storeOne.ListWalletAccountsAsync(32); var row = Assert.Single(wallets); Assert.Equal("gem", row.CurrencyId); Assert.Equal(20, row.Balance); - var ledger = (await storeOne.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 32, AfterSequenceNumber = 0, MaxCount = 100, })).OrderBy(entry => entry.SequenceNumber).ToArray(); + var ledger = (await storeOne.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 32, AfterSequenceNumber = 0, MaxCount = 100, })).OrderBy(entry => entry.SequenceNumber).ToArray(); Assert.Equal(2, ledger.Length); Assert.Equal(0L, ledger[0].AmountBefore); Assert.Equal(ledger[0].AmountAfter, ledger[1].AmountBefore); @@ -582,13 +567,11 @@ public async Task AssetStore_LegacyNullRowVersion_ShouldBackfillOnFirstApplyAndK await WithSqliteFacadeAsync(async () => { // 构造行版本缺位的存量行(模拟旧数据;显式 null 持久化为 JSON null)。 - var uniqueKey = TenantId + ":" + AppId + ":33:oldcoin"; + var uniqueKey = OnlineRowKey.WalletAccount(33, "oldcoin"); await GameDb.SaveOneAsync(new OnlineWalletAccountState { Id = 987001, UniqueKey = uniqueKey, - TenantId = TenantId, - AppId = AppId, PlayerId = 33, CurrencyId = "oldcoin", Balance = 100, @@ -602,14 +585,14 @@ await GameDb.SaveOneAsync(new OnlineWalletAccountState // 首次落账:回填原语补全 + 首写(余额 100 + 50)落行版本 0(与新建行基线一致),实体 Version = 0 + 1 = 1。 var first = await service.ExecuteAsync(Request(scope, "g1109-legacy-first", new[] { (OnlineAssetKind.Currency, "oldcoin", 50L) })); Assert.True(first.IsSuccess); - var wallet = await store.FindWalletAsync(TenantId, AppId, 33, "oldcoin"); + var wallet = await store.FindWalletAsync(33, "oldcoin"); Assert.Equal(150, wallet.Balance); Assert.Equal(1, wallet.Version); // 第二次落账:转正常 CAS(期望行版本 0),版本单调递增。 var second = await service.ExecuteAsync(Request(scope, "g1109-legacy-second", new[] { (OnlineAssetKind.Currency, "oldcoin", 30L) })); Assert.True(second.IsSuccess); - wallet = await store.FindWalletAsync(TenantId, AppId, 33, "oldcoin"); + wallet = await store.FindWalletAsync(33, "oldcoin"); Assert.Equal(180, wallet.Balance); Assert.Equal(2, wallet.Version); @@ -620,7 +603,7 @@ await GameDb.SaveOneAsync(new OnlineWalletAccountState Assert.Equal(180, row.Balance); // 账本链自存量余额续写。 - var ledger = (await store.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 33, AfterSequenceNumber = 0, MaxCount = 100, })).OrderBy(entry => entry.SequenceNumber).ToArray(); + var ledger = (await store.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 33, AfterSequenceNumber = 0, MaxCount = 100, })).OrderBy(entry => entry.SequenceNumber).ToArray(); Assert.Equal(2, ledger.Length); Assert.Equal(100L, ledger[0].AmountBefore); Assert.Equal(150L, ledger[0].AmountAfter); @@ -643,9 +626,9 @@ public async Task Restart_IdentityDomain_ShouldSurviveRestartWithSequenceContinu await WithSqliteFileFacadeAsync(dataFile, async () => { var store = new GameDbOnlineIdentityStore(); - await store.AddOrUpdateIdentityAsync(new OnlineIdentity { Id = "idn-r", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.UserName, Identifier = "restart-user", GameAccountId = 900, CreatedAtTime = 10, UpdatedAtTime = 11, }); - await store.AddOrUpdateAccountAsync(new OnlineGameAccount { Id = 900, TenantId = TenantId, AppId = AppId, Status = OnlineGameAccountStatus.Active, CreatedAtTime = 10, }); - await store.AddOrUpdatePlayerAsync(new OnlinePlayerProfile { Id = 55, GameAccountId = 900, TenantId = TenantId, AppId = AppId, ServerId = 5, Name = "restart-player", CreatedAtTime = 12, }); + await store.AddOrUpdateIdentityAsync(new OnlineIdentity { Id = "idn-r", Kind = OnlineIdentityKind.UserName, Identifier = "restart-user", GameAccountId = 900, CreatedAtTime = 10, UpdatedAtTime = 11, }); + await store.AddOrUpdateAccountAsync(new OnlineGameAccount { Id = 900, Status = OnlineGameAccountStatus.Active, CreatedAtTime = 10, }); + await store.AddOrUpdatePlayerAsync(new OnlinePlayerProfile { Id = 55, GameAccountId = 900, ServerId = 5, Name = "restart-player", CreatedAtTime = 12, }); await store.AddOrUpdateDeviceAsync(new OnlinePlayerDevice { Id = "dev-r", GameAccountId = 900, DeviceIdentifier = "device-r", Platform = "ios", BoundAtTime = 13, }); Assert.Equal(1L, await store.NextAccountIdAsync()); Assert.Equal(2L, await store.NextAccountIdAsync()); @@ -655,7 +638,7 @@ await WithSqliteFileFacadeAsync(dataFile, async () => await WithSqliteFileFacadeAsync(dataFile, async () => { var store = new GameDbOnlineIdentityStore(); - var identity = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.UserName, "restart-user"); + var identity = await store.FindIdentityAsync(OnlineIdentityKind.UserName, "restart-user"); Assert.NotNull(identity); Assert.Equal("idn-r", identity.Id); Assert.Equal(900, identity.GameAccountId); @@ -689,20 +672,20 @@ public async Task Restart_StorageDomain_ShouldSurviveRestartAndContinueCas() await WithSqliteFileFacadeAsync(dataFile, async () => { var store = new GameDbOnlinePlayerStorageStore(); - var key = new OnlineStorageEntryKey { TenantId = TenantId, AppId = AppId, PlayerId = 33, Collection = "settings", Key = "theme", }; + var key = new OnlineStorageEntryKey { PlayerId = 33, Collection = "settings", Key = "theme", }; Assert.True(await store.UpsertAsync(BuildEntry(key, new byte[] { 7, 7, 7 }, 1), 0)); Assert.True(await store.UpsertAsync(BuildEntry(key, new byte[] { 8, 8 }, 2), 1)); var softDeleted = BuildEntry(key, new byte[] { 8, 8 }, 3); softDeleted.DeletedAtTime = 7777; Assert.True(await store.UpsertAsync(softDeleted, 2)); - var other = new OnlineStorageEntryKey { TenantId = TenantId, AppId = AppId, PlayerId = 33, Collection = "settings", Key = "sound", }; + var other = new OnlineStorageEntryKey { PlayerId = 33, Collection = "settings", Key = "sound", }; Assert.True(await store.UpsertAsync(BuildEntry(other, new byte[] { 1 }, 1), 0)); }); await WithSqliteFileFacadeAsync(dataFile, async () => { var store = new GameDbOnlinePlayerStorageStore(); - var key = new OnlineStorageEntryKey { TenantId = TenantId, AppId = AppId, PlayerId = 33, Collection = "settings", Key = "theme", }; + var key = new OnlineStorageEntryKey { PlayerId = 33, Collection = "settings", Key = "theme", }; // 软删条目读回:DeletedAtTime 与版本(3 = 行 RowVersion 2 + 校准)保真;活跃列举只见 sound。 var softDeletedEntry = await store.FindAsync(key); @@ -714,7 +697,7 @@ await WithSqliteFileFacadeAsync(dataFile, async () => // 重启后 CAS 以软删版本继续:复活成功且版本推进 4。 Assert.True(await store.UpsertAsync(BuildEntry(key, new byte[] { 9 }, 4), 3)); - Assert.Equal(2, await store.CountActiveKeysAsync(TenantId, AppId, 33, "settings")); + Assert.Equal(2, await store.CountActiveKeysAsync(33, "settings")); }); } finally @@ -745,7 +728,7 @@ await WithSqliteFileFacadeAsync(dataFile, async () => { (OnlineAssetKind.Currency, "gold", -120), }))).IsSuccess); - beforeLedger = (await new GameDbOnlineAssetStore().ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 44, AfterSequenceNumber = 0, MaxCount = 100, })).ToArray(); + beforeLedger = (await new GameDbOnlineAssetStore().ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 44, AfterSequenceNumber = 0, MaxCount = 100, })).ToArray(); }); await WithSqliteFileFacadeAsync(dataFile, async () => @@ -754,13 +737,13 @@ await WithSqliteFileFacadeAsync(dataFile, async () => var transactionStore = new GameDbOnlineAssetTransactionStore(); // 快照读回:余额 / 数量 / 版本一致。 - var gold = await assetStore.FindWalletAsync(TenantId, AppId, 44, "gold"); + var gold = await assetStore.FindWalletAsync(44, "gold"); Assert.Equal(380, gold.Balance); Assert.Equal(2, gold.Version); - Assert.Equal(3, (await assetStore.FindInventoryAsync(TenantId, AppId, 44, "sword")).Quantity); + Assert.Equal(3, (await assetStore.FindInventoryAsync(44, "sword")).Quantity); // 账本全量读回:逐字段一致(前后值链完整 = 余额可由账本重算)。 - var ledger = (await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 44, AfterSequenceNumber = 0, MaxCount = 100, })).ToArray(); + var ledger = (await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 44, AfterSequenceNumber = 0, MaxCount = 100, })).ToArray(); Assert.Equal(beforeLedger.Length, ledger.Length); for (var i = 0; i < ledger.Length; i++) { @@ -772,7 +755,7 @@ await WithSqliteFileFacadeAsync(dataFile, async () => } // 聚合一致 + 交易终态读回(含外键列表)。 - Assert.Equal(380, (await assetStore.SumLedgerDeltasByAssetAsync(TenantId, AppId, 44))["c:gold"]); + Assert.Equal(380, (await assetStore.SumLedgerDeltasByAssetAsync(44))["c:gold"]); var succeeded = await transactionStore.ListByStateAsync(OnlineAssetTransactionState.Succeeded); Assert.Equal(2, succeeded.Count); Assert.All(succeeded, transaction => Assert.NotEmpty(transaction.AppliedLedgerEntryIds)); @@ -783,12 +766,12 @@ await WithSqliteFileFacadeAsync(dataFile, async () => { (OnlineAssetKind.Currency, "gold", 20), }))).IsSuccess); - var after = await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = 44, AfterSequenceNumber = 3, MaxCount = 10, }); + var after = await assetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 44, AfterSequenceNumber = 3, MaxCount = 10, }); var continuation = Assert.Single(after); Assert.Equal(4, continuation.SequenceNumber); Assert.Equal(380, continuation.AmountBefore); Assert.Equal(400, continuation.AmountAfter); - Assert.Equal(400, (await assetStore.FindWalletAsync(TenantId, AppId, 44, "gold")).Balance); + Assert.Equal(400, (await assetStore.FindWalletAsync(44, "gold")).Balance); }); } finally @@ -826,7 +809,7 @@ private static (OnlineGrantService Service, OnlineScope Scope) BuildGrantService { var coordinator = new IdempotencyCoordinator(new InMemoryIdempotencyStore(), SystemClock.Instance); var service = new OnlineGrantService(assetStore, transactionStore, new OnlineIdempotencyService(coordinator, null), new NopEventPublisher(), null); - return (service, new OnlineScope(TenantId, AppId, 5, playerId)); + return (service, new OnlineScope(5, playerId)); } /// @@ -849,7 +832,7 @@ private static OnlineGrantRequest Request(OnlineScope scope, string idempotencyK /// private static Task> ListAsync(GameDbOnlinePlayerStorageStore store, long playerId, string collection) { - return store.ListAsync(new OnlineStorageListQuery { TenantId = TenantId, AppId = AppId, PlayerId = playerId, Collection = collection, AfterKey = string.Empty, MaxCount = 10, }); + return store.ListAsync(new OnlineStorageListQuery { PlayerId = playerId, Collection = collection, AfterKey = string.Empty, MaxCount = 10, }); } /// @@ -859,8 +842,6 @@ private static OnlinePlayerStorageEntry BuildEntry(OnlineStorageEntryKey key, by { return new OnlinePlayerStorageEntry { - TenantId = key.TenantId, - AppId = key.AppId, PlayerId = key.PlayerId, Collection = key.Collection, Key = key.Key, diff --git a/Tests/GameFrameX.Tests/Online/OnlineGameEventMetricsTests.cs b/Tests/GameFrameX.Tests/Online/OnlineGameEventMetricsTests.cs index ad6488b02..94d785fb2 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineGameEventMetricsTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineGameEventMetricsTests.cs @@ -53,8 +53,8 @@ public async Task ComputeAsync_RecomputedFromRawEvents_ShouldBeIdentical() var harness = new OnlineGameEventTestHarness(); await ProjectSampleTrafficAsync(harness); - var first = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 0, long.MaxValue); - var second = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 0, long.MaxValue); + var first = await harness.MetricsService.ComputeAsync(0, long.MaxValue); + var second = await harness.MetricsService.ComputeAsync(0, long.MaxValue); var stored = await harness.StoredEventsAsync(); @@ -69,10 +69,10 @@ public async Task ComputeAsync_RecomputedFromRawEvents_ShouldBeIdentical() // 活跃玩家数是去重口径:样例流量含 1 条会话开始(玩家一)→ 1; // 再补玩家一的第二条会话开始(重连)与玩家二的一条 → 仍去重为 2 人。 Assert.Equal(1, first.ActivePlayerCount); - await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.SessionStart, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.SessionStart), 1, OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, OnlineGameEventTestHarness.Now + 10, OnlineGameEventTestHarness.PlayerOne), OnlineGameEventTestHarness.Now + 10); - await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.SessionStart, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.SessionStart), 1, OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, OnlineGameEventTestHarness.Now + 11, OnlineGameEventTestHarness.PlayerTwo), OnlineGameEventTestHarness.Now + 11); + await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.SessionStart, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.SessionStart), 1, OnlineGameEventTestHarness.Now + 10, OnlineGameEventTestHarness.PlayerOne), OnlineGameEventTestHarness.Now + 10); + await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.SessionStart, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.SessionStart), 1, OnlineGameEventTestHarness.Now + 11, OnlineGameEventTestHarness.PlayerTwo), OnlineGameEventTestHarness.Now + 11); - var withReconnect = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 0, long.MaxValue); + var withReconnect = await harness.MetricsService.ComputeAsync(0, long.MaxValue); Assert.Equal(2, withReconnect.ActivePlayerCount); Assert.Equal(3, withReconnect.GetNameCount(OnlineGameEventName.SessionStart)); @@ -87,7 +87,7 @@ public async Task ComputeAsync_ShouldCountByRegisteredCategory() var harness = new OnlineGameEventTestHarness(); await ProjectSampleTrafficAsync(harness); - var metrics = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 0, long.MaxValue); + var metrics = await harness.MetricsService.ComputeAsync(0, long.MaxValue); Assert.Equal(2, metrics.GetCategoryCount(OnlineGameEventCategory.Login)); Assert.Equal(1, metrics.GetCategoryCount(OnlineGameEventCategory.Matchmaking)); @@ -119,17 +119,17 @@ public async Task ComputeAsync_ShouldCountByRegisteredCategory() public async Task ComputeAsync_Window_ShouldIncludeBothBoundaries() { var harness = new OnlineGameEventTestHarness(); - await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 1000), 1000); - await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 2000), 2000); - await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 3000), 3000); + await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, 1000), 1000); + await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, 2000), 2000); + await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, 3000), 3000); - var window = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 1000, 2000); + var window = await harness.MetricsService.ComputeAsync(1000, 2000); Assert.Equal(2, window.TotalCount); Assert.Equal(1000, window.FromTime); Assert.Equal(2000, window.ToTime); - var everything = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 0, long.MaxValue); + var everything = await harness.MetricsService.ComputeAsync(0, long.MaxValue); Assert.Equal(3, everything.TotalCount); } @@ -145,15 +145,11 @@ public async Task ComputeAsync_ShouldIsolateScopeAndCountRejectedSeparately() await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope("NotARegisteredEvent", new Dictionary()), OnlineGameEventTestHarness.Now); await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Win, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Win, "PlayerId")), OnlineGameEventTestHarness.Now); - var metrics = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 0, long.MaxValue); + var metrics = await harness.MetricsService.ComputeAsync(0, long.MaxValue); Assert.Equal(1, metrics.TotalCount); Assert.Equal(2, metrics.RejectedCount); Assert.Equal(1, metrics.GetCategoryCount(OnlineGameEventCategory.Match)); - - var otherApp = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.OtherAppId, OnlineGameEventTestHarness.AppId, 0, long.MaxValue); - Assert.Equal(0, otherApp.TotalCount); - Assert.Equal(0, otherApp.RejectedCount); } /// @@ -164,12 +160,12 @@ public async Task ComputeAsync_ShouldIsolateScopeAndCountRejectedSeparately() public async Task ComputeAsync_ShouldCarryNoCrossWindowState() { var harness = new OnlineGameEventTestHarness(); - await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 1000), 1000); - await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 2000), 2000); + await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, 1000), 1000); + await harness.Ingestor.IngestAsync(OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Login, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Login), 1, 2000), 2000); - var firstHalf = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 1000, 1000); - var secondHalf = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 1001, 2000); - var whole = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 1000, 2000); + var firstHalf = await harness.MetricsService.ComputeAsync(1000, 1000); + var secondHalf = await harness.MetricsService.ComputeAsync(1001, 2000); + var whole = await harness.MetricsService.ComputeAsync(1000, 2000); Assert.Equal(1, firstHalf.TotalCount); Assert.Equal(1, secondHalf.TotalCount); diff --git a/Tests/GameFrameX.Tests/Online/OnlineGameEventProjectorTests.cs b/Tests/GameFrameX.Tests/Online/OnlineGameEventProjectorTests.cs index 0f5efa8d3..46d98fb46 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineGameEventProjectorTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineGameEventProjectorTests.cs @@ -206,7 +206,7 @@ public async Task ProjectAsync_ShouldIngestAllSixCategoriesWithoutRejection() var stored = await harness.StoredEventsAsync(); Assert.Equal(events.Count, stored.Count); - var metrics = await harness.MetricsService.ComputeAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.AppId, 0, long.MaxValue); + var metrics = await harness.MetricsService.ComputeAsync(0, long.MaxValue); Assert.Equal(events.Count, metrics.TotalCount); Assert.Equal(3, metrics.GetCategoryCount(OnlineGameEventCategory.Login)); Assert.Equal(1, metrics.GetCategoryCount(OnlineGameEventCategory.Matchmaking)); diff --git a/Tests/GameFrameX.Tests/Online/OnlineGameEventSchemaTests.cs b/Tests/GameFrameX.Tests/Online/OnlineGameEventSchemaTests.cs index d3914c535..e134af818 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineGameEventSchemaTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineGameEventSchemaTests.cs @@ -131,8 +131,6 @@ public async Task IngestAsync_DirtyEvents_ShouldRejectIntoDeadLetterAndNotStore( (Event: OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Win, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Win), 0), Reason: OnlineGameEventRejectionReason.UnsupportedVersion), (Event: OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Win, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Win), 2), Reason: OnlineGameEventRejectionReason.UnsupportedVersion), (Event: OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Win, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Win, "PlayerId")), Reason: OnlineGameEventRejectionReason.MissingRequiredField), - (Event: OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Win, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Win), 1, 0, OnlineGameEventTestHarness.AppId), Reason: OnlineGameEventRejectionReason.InvalidScope), - (Event: OnlineGameEventTestHarness.BuildEnvelope(OnlineGameEventName.Win, OnlineGameEventTestHarness.CompleteFields(OnlineGameEventName.Win), 1, OnlineGameEventTestHarness.TenantId, 0), Reason: OnlineGameEventRejectionReason.InvalidScope), }; foreach (var item in cases) @@ -147,7 +145,7 @@ public async Task IngestAsync_DirtyEvents_ShouldRejectIntoDeadLetterAndNotStore( // 脏事件不污染下游:存储里一条都没有。 Assert.Empty(await harness.StoredEventsAsync()); - // 死信按事件自身作用域归档:四条作用域合法者落在本作用域下。 + // 死信按事件归档:四条脏事件全部可检索、不丢失。 var deadLetters = await harness.DeadLettersAsync(); Assert.Equal(4, deadLetters.Count); Assert.Equal( @@ -160,14 +158,6 @@ public async Task IngestAsync_DirtyEvents_ShouldRejectIntoDeadLetterAndNotStore( }, deadLetters.Select(item => item.Reason).ToArray()); - // 作用域非法的两条按「退化作用域」原样归档(可检索、不丢失)。 - var zeroTenant = await harness.DeadLetterSink.ListAsync(0, OnlineGameEventTestHarness.AppId, new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue }); - var zeroApp = await harness.DeadLetterSink.ListAsync(OnlineGameEventTestHarness.TenantId, 0, new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue }); - Assert.Single(zeroTenant); - Assert.Single(zeroApp); - Assert.Equal(OnlineGameEventRejectionReason.InvalidScope, zeroTenant[0].Reason); - Assert.Equal(OnlineGameEventRejectionReason.InvalidScope, zeroApp[0].Reason); - // 空信封是编程错误(拒绝意味着「有事件但脏」,空信封没有可归档的实体)。 await Assert.ThrowsAsync(() => harness.Ingestor.IngestAsync(null)); } @@ -247,9 +237,6 @@ public async Task StoreAndDeadLetter_ShouldIsolateScope() Assert.Single(await harness.StoredEventsAsync()); Assert.Single(await harness.DeadLettersAsync()); - Assert.Empty(await harness.EventStore.ListAsync(OnlineGameEventTestHarness.OtherAppId, OnlineGameEventTestHarness.AppId, new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue })); - Assert.Empty(await harness.EventStore.ListAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.OtherAppId, new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue })); - Assert.Empty(await harness.DeadLetterSink.ListAsync(OnlineGameEventTestHarness.TenantId, OnlineGameEventTestHarness.OtherAppId, new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue })); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineGameEventTestHarness.cs b/Tests/GameFrameX.Tests/Online/OnlineGameEventTestHarness.cs index 45542cd67..214aba3ed 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineGameEventTestHarness.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineGameEventTestHarness.cs @@ -46,15 +46,6 @@ namespace GameFrameX.Tests.Online /// internal sealed class OnlineGameEventTestHarness { - /// 租户标识。 - public const long TenantId = 1; - - /// App 标识。 - public const long AppId = 10; - - /// 另一 App 标识(跨 App 反预言用例)。 - public const long OtherAppId = 11; - /// 区服标识。 public const long ServerId = 100; @@ -115,12 +106,10 @@ public OnlineGameEventMetricsService MetricsService /// 事件名。 /// 载荷字段投影(可空,取登记表必需字段的全零填充)。 /// Schema 版本。 - /// 租户标识。 - /// App 标识。 /// 事件发生时刻(UTC 毫秒)。 /// 玩家标识(信封维度)。 /// 事件信封实例。 - public static OnlineEvent BuildEnvelope(string eventName, Dictionary fields = null, int schemaVersion = 1, long tenantId = TenantId, long appId = AppId, long occurredTime = Now, long playerId = PlayerOne) + public static OnlineEvent BuildEnvelope(string eventName, Dictionary fields = null, int schemaVersion = 1, long occurredTime = Now, long playerId = PlayerOne) { return new OnlineEvent { @@ -128,8 +117,6 @@ public static OnlineEvent BuildEnvelope(string eventName, Dictionary CompleteFields(string eventName, string /// 事件列表。 public Task> StoredEventsAsync() { - return EventStore.ListAsync(TenantId, AppId, new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue }); + return EventStore.ListAsync(new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue }); } /// @@ -178,7 +165,7 @@ public Task> StoredEventsAsync() /// 死信列表。 public Task> DeadLettersAsync() { - return DeadLetterSink.ListAsync(TenantId, AppId, new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue }); + return DeadLetterSink.ListAsync(new EventTimeRangeQuery { FromTime = 0, ToTime = long.MaxValue }); } /// @@ -193,8 +180,6 @@ public static OnlineSession Session(OnlineSessionState state, long playerId = Pl return new OnlineSession { Id = sessionId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, GameAccountId = playerId, PlayerId = playerId, @@ -221,8 +206,6 @@ public static OnlineMatchTicket Ticket(OnlineMatchTicketState state = OnlineMatc TicketId = "ticket-1", PartyId = "party-1", PlayerIds = new List { PlayerOne, PlayerTwo }, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Mode = 7, Region = 1, @@ -241,8 +224,6 @@ public static OnlineMatch Match(OnlineMatchState state, string matchId = "match- { return new OnlineMatch { - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, MatchId = matchId, AssignmentId = "assign-1", @@ -280,8 +261,6 @@ public static OnlineMatchResult MatchResult(OnlineMatchState outcome, params (lo { MatchResultId = "mrs-1", MatchId = "match-1", - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Mode = 7, Region = 1, @@ -305,8 +284,6 @@ public static OnlineAssetTransaction Transaction(OnlineAssetChangeSource source, TransactionId = "txn-1", IdempotencyKey = "idem-1", RequestDigest = "digest-1", - TenantId = TenantId, - AppId = AppId, PlayerId = PlayerOne, HomeServerId = ServerId, InitiatingServerId = ServerId, @@ -331,8 +308,6 @@ public static OnlineReportCase ReportCase(OnlineReportScene scene) return new OnlineReportCase { ReportId = "report-1", - TenantId = TenantId, - AppId = AppId, ReporterId = PlayerOne, ReportedPlayerId = PlayerTwo, Scene = scene, @@ -356,8 +331,6 @@ public static OnlinePunishment Punishment(bool revoked = false) return new OnlinePunishment { PunishmentId = "punish-1", - TenantId = TenantId, - AppId = AppId, PlayerId = PlayerTwo, Kind = OnlinePunishmentKind.Ban, Reason = "测试处罚", diff --git a/Tests/GameFrameX.Tests/Online/OnlineGrantServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineGrantServiceTests.cs index 5c4834e68..5c0c6c426 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineGrantServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineGrantServiceTests.cs @@ -192,24 +192,24 @@ public Task ApplyAsync(OnlineAssetChangeBatch batch, Can } } - public Task FindWalletAsync(long tenantId, long appId, long playerId, string currencyId, CancellationToken cancellationToken = default) + public Task FindWalletAsync(long playerId, string currencyId, CancellationToken cancellationToken = default) { - return _inner.FindWalletAsync(tenantId, appId, playerId, currencyId, cancellationToken); + return _inner.FindWalletAsync(playerId, currencyId, cancellationToken); } - public Task FindInventoryAsync(long tenantId, long appId, long playerId, string itemId, CancellationToken cancellationToken = default) + public Task FindInventoryAsync(long playerId, string itemId, CancellationToken cancellationToken = default) { - return _inner.FindInventoryAsync(tenantId, appId, playerId, itemId, cancellationToken); + return _inner.FindInventoryAsync(playerId, itemId, cancellationToken); } - public Task> ListWalletAccountsAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListWalletAccountsAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListWalletAccountsAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListWalletAccountsAsync(playerId, cancellationToken); } - public Task> ListInventoryStacksAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListInventoryStacksAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListInventoryStacksAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListInventoryStacksAsync(playerId, cancellationToken); } public Task> ListLedgerEntriesAsync(OnlineLedgerPageQuery query, CancellationToken cancellationToken = default) @@ -222,14 +222,14 @@ public Task> FindLedgerEntriesByTransactionIdAs return _inner.FindLedgerEntriesByTransactionIdAsync(transactionId, cancellationToken); } - public Task> SumLedgerDeltasByAssetAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> SumLedgerDeltasByAssetAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.SumLedgerDeltasByAssetAsync(tenantId, appId, playerId, cancellationToken); + return _inner.SumLedgerDeltasByAssetAsync(playerId, cancellationToken); } - public Task> ListPlayerIdsAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListPlayerIdsAsync(CancellationToken cancellationToken = default) { - return _inner.ListPlayerIdsAsync(tenantId, appId, cancellationToken); + return _inner.ListPlayerIdsAsync(cancellationToken); } /// @@ -240,8 +240,6 @@ private static OnlineAssetChangeBatch BuildBatch(OnlineAssetChangeBatch source, var constructor = typeof(OnlineAssetChangeBatch).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).Single(); var header = new OnlineLedgerHeader { - TenantId = source.TenantId, - AppId = source.AppId, PlayerId = source.PlayerId, HomeServerId = source.HomeServerId, InitiatingServerId = source.InitiatingServerId, @@ -357,7 +355,7 @@ public OnlineGrantService CreateService(IOnlineAssetStore assetStore = null, IOn /// private static OnlineGrantRequest BuildRequest(long playerId, OnlineAssetChangeSource source, string key, OnlineAssetChangeLine line, params OnlineAssetChangeLine[] moreLines) { - var scope = new OnlineScope(1, 10, 100, playerId); + var scope = new OnlineScope(100, playerId); var lines = new List { line }; lines.AddRange(moreLines); return new OnlineGrantRequest(scope, source, OnlineGrantOperation.Grant, "赛季结算奖励", "bo-" + key, lines, key); @@ -388,7 +386,7 @@ public async Task ExecuteAsync_FourSources_RetrySameKeyReplaysFirstResult(Online Assert.True(second.IsSuccess); Assert.True(second.Data.IsReplay); Assert.Equal(first.Data.TransactionId, second.Data.TransactionId); - var wallet = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(100, wallet.Balance); var entries = await harness.AssetStore.FindLedgerEntriesByTransactionIdAsync(first.Data.TransactionId); Assert.Single(entries); @@ -414,7 +412,7 @@ public async Task ExecuteAsync_SameKeyDifferentIntent_ShouldReturnVersionConflic Assert.True(first.IsSuccess); Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.VersionConflict, result.Code); - var wallet = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(100, wallet.Balance); } @@ -427,7 +425,7 @@ public async Task ExecuteAsync_PolicyViolations_ShouldReturnParameterInvalid() // Arrange var harness = new Harness(); var service = harness.CreateService(); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act / Assert var compensationSource = await service.ExecuteAsync(new OnlineGrantRequest(scope, OnlineAssetChangeSource.SystemCompensation, OnlineGrantOperation.Adjust, "r", "bo-x", new[] { new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 100) }, "key-c") { OperatorId = "op-1" }); @@ -468,9 +466,9 @@ public async Task ExecuteAsync_InsufficientBalance_ShouldFailWithoutPartialState // Assert Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, result.Code); - var wallet = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(100, wallet.Balance); - var ledger = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = 1, AppId = 10, PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); + var ledger = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); Assert.Single(ledger); Assert.Contains(harness.AlertSink.Records, record => record.Kind == OnlineAssetAlertKind.NegativeBalanceAttempt); } @@ -495,9 +493,9 @@ public async Task ExecuteAsync_ConcurrentDeducts_OnlyAffordableApply() // Assert Assert.Equal(5, results.Count(result => result.IsSuccess)); Assert.Equal(5, results.Count(result => !result.IsSuccess)); - var wallet = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(0, wallet.Balance); - var ledger = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = 1, AppId = 10, PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); + var ledger = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); Assert.Equal(6, ledger.Count); } @@ -557,13 +555,12 @@ public async Task ExecuteAsync_PartialApplyCrash_CompensatesToNetZero() // Act var result = await service.ExecuteAsync(request); - // Assert Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.InternalError, result.Code); - var wallet = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.NotNull(wallet); Assert.Equal(0, wallet.Balance); - var stack = await harness.AssetStore.FindInventoryAsync(1, 10, 10001, "sword"); + var stack = await harness.AssetStore.FindInventoryAsync(10001, "sword"); Assert.Null(stack); var compensated = await harness.TransactionStore.ListByStateAsync(OnlineAssetTransactionState.Compensated); @@ -614,15 +611,15 @@ public async Task RecoverAsync_OriginalAlreadyCompensated_ShouldNotAppendSecondR var topUp = await service.ExecuteAsync(BuildRequest(10001, OnlineAssetChangeSource.PaymentConfirm, "key-topup", new OnlineAssetChangeLine(OnlineAssetKind.Currency, "gold", 100))); Assert.True(topUp.IsSuccess); - var entriesBefore = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = 1, AppId = 10, PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); + var entriesBefore = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); // Act:重启恢复 var recovered = await service.RecoverAsync(); // Assert:不得追加第二条反转(账本条目数与余额都不变) - var entriesAfter = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = 1, AppId = 10, PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); + var entriesAfter = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); Assert.Equal(entriesBefore.Count, entriesAfter.Count); - var wallet = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(100, wallet.Balance); Assert.Equal(1, recovered); } @@ -650,7 +647,7 @@ public async Task ExecuteAsync_ZeroApplyCrash_MarksFailedAndRetriableWithNewKey( Assert.Equal(OnlineErrorCode.InternalError, crashed.Code); var failed = await harness.TransactionStore.ListByStateAsync(OnlineAssetTransactionState.Failed); Assert.Single(failed); - var walletAfterCrash = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var walletAfterCrash = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.Null(walletAfterCrash); // Act(第二段:换新幂等键重试) @@ -658,7 +655,7 @@ public async Task ExecuteAsync_ZeroApplyCrash_MarksFailedAndRetriableWithNewKey( // Assert Assert.True(retried.IsSuccess); - var wallet = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(100, wallet.Balance); } @@ -691,9 +688,9 @@ public async Task RecoverAsync_FullApplyCrashBeforeSettle_RecoversAsSucceededThe Assert.Single(succeeded); Assert.True(replayed.IsSuccess); Assert.True(replayed.Data.IsReplay); - var wallet = await harness.AssetStore.FindWalletAsync(1, 10, 10001, "gold"); + var wallet = await harness.AssetStore.FindWalletAsync(10001, "gold"); Assert.Equal(100, wallet.Balance); - var ledger = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = 1, AppId = 10, PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); + var ledger = await harness.AssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = 10001, AfterSequenceNumber = 0, MaxCount = 100 }); Assert.Single(ledger); } @@ -711,8 +708,6 @@ public async Task RecoverAsync_ZeroEntryExecutingTransaction_MarksFailed() TransactionId = "tx-orphan-1", IdempotencyKey = "key-orphan", RequestDigest = string.Empty, - TenantId = 1, - AppId = 10, PlayerId = 10001, HomeServerId = 100, InitiatingServerId = 100, @@ -808,8 +803,6 @@ private static OnlineAssetTransaction BuildExecutingTransaction(string transacti TransactionId = transactionId, IdempotencyKey = idempotencyKey, RequestDigest = string.Empty, - TenantId = 1, - AppId = 10, PlayerId = 10001, HomeServerId = 100, InitiatingServerId = 100, @@ -834,8 +827,6 @@ private static OnlineLedgerEntry BuildFabricatedEntry(string transactionId, stri { var header = new OnlineLedgerHeader { - TenantId = 1, - AppId = 10, PlayerId = playerId, HomeServerId = 100, InitiatingServerId = 100, @@ -864,24 +855,24 @@ public FabricatedLedgerAssetStore(IOnlineAssetStore inner, string transactionId, _fabricate = fabricate; } - public Task FindWalletAsync(long tenantId, long appId, long playerId, string currencyId, CancellationToken cancellationToken = default) + public Task FindWalletAsync(long playerId, string currencyId, CancellationToken cancellationToken = default) { - return _inner.FindWalletAsync(tenantId, appId, playerId, currencyId, cancellationToken); + return _inner.FindWalletAsync(playerId, currencyId, cancellationToken); } - public Task FindInventoryAsync(long tenantId, long appId, long playerId, string itemId, CancellationToken cancellationToken = default) + public Task FindInventoryAsync(long playerId, string itemId, CancellationToken cancellationToken = default) { - return _inner.FindInventoryAsync(tenantId, appId, playerId, itemId, cancellationToken); + return _inner.FindInventoryAsync(playerId, itemId, cancellationToken); } - public Task> ListWalletAccountsAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListWalletAccountsAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListWalletAccountsAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListWalletAccountsAsync(playerId, cancellationToken); } - public Task> ListInventoryStacksAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListInventoryStacksAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListInventoryStacksAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListInventoryStacksAsync(playerId, cancellationToken); } public Task ApplyAsync(OnlineAssetChangeBatch batch, CancellationToken cancellationToken = default) @@ -904,14 +895,14 @@ public Task> FindLedgerEntriesByTransactionIdAs return _inner.FindLedgerEntriesByTransactionIdAsync(transactionId, cancellationToken); } - public Task> SumLedgerDeltasByAssetAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> SumLedgerDeltasByAssetAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.SumLedgerDeltasByAssetAsync(tenantId, appId, playerId, cancellationToken); + return _inner.SumLedgerDeltasByAssetAsync(playerId, cancellationToken); } - public Task> ListPlayerIdsAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListPlayerIdsAsync(CancellationToken cancellationToken = default) { - return _inner.ListPlayerIdsAsync(tenantId, appId, cancellationToken); + return _inner.ListPlayerIdsAsync(cancellationToken); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineGroupServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineGroupServiceTests.cs index 4b434bcc1..96f236aeb 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineGroupServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineGroupServiceTests.cs @@ -43,15 +43,10 @@ namespace GameFrameX.Tests.Online /// public class OnlineGroupServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; + /// 测试用群主玩家标识。 private const long OwnerId = 1001; @@ -479,9 +474,9 @@ public async Task SweepExpiredInvitesAsync_ShouldExpireOverdueInvite() var futureNow = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + 3_600_000; // Act - var sweep = await service.SweepExpiredInvitesAsync(TenantId, AppId, futureNow); + var sweep = await service.SweepExpiredInvitesAsync(futureNow); var accepted = await service.AcceptInviteAsync(CreatePlayerScope(MemberOneId), group.GroupId, invite.Data.InviteId); - var repeated = await service.SweepExpiredInvitesAsync(TenantId, AppId, futureNow); + var repeated = await service.SweepExpiredInvitesAsync(futureNow); // Assert Assert.True(sweep.IsSuccess); @@ -506,12 +501,12 @@ public async Task IsChannelMemberAsync_WhenGroupChannel_ShouldJudgeByCurrentMemb await InviteAndAcceptAsync(service, group.GroupId, OwnerId, MemberOneId); // Act - var ownerMember = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Group, group.GroupId, OwnerId); - var joinedMember = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Group, group.GroupId, MemberOneId); - var outsider = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Group, group.GroupId, OutsiderId); - var missingGroup = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Group, "grp-不存在", OwnerId); - var emptyBoundId = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Group, string.Empty, OwnerId); - var nullBoundId = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Group, null, OwnerId); + var ownerMember = await service.IsChannelMemberAsync(OnlineChatChannelKind.Group, group.GroupId, OwnerId); + var joinedMember = await service.IsChannelMemberAsync(OnlineChatChannelKind.Group, group.GroupId, MemberOneId); + var outsider = await service.IsChannelMemberAsync(OnlineChatChannelKind.Group, group.GroupId, OutsiderId); + var missingGroup = await service.IsChannelMemberAsync(OnlineChatChannelKind.Group, "grp-不存在", OwnerId); + var emptyBoundId = await service.IsChannelMemberAsync(OnlineChatChannelKind.Group, string.Empty, OwnerId); + var nullBoundId = await service.IsChannelMemberAsync(OnlineChatChannelKind.Group, null, OwnerId); // Assert Assert.True(ownerMember); @@ -522,7 +517,7 @@ public async Task IsChannelMemberAsync_WhenGroupChannel_ShouldJudgeByCurrentMemb Assert.False(nullBoundId); await service.KickAsync(CreatePlayerScope(OwnerId), group.GroupId, MemberOneId); - var kickedMember = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Group, group.GroupId, MemberOneId); + var kickedMember = await service.IsChannelMemberAsync(OnlineChatChannelKind.Group, group.GroupId, MemberOneId); Assert.False(kickedMember); } @@ -539,12 +534,12 @@ public async Task IsChannelMemberAsync_WhenKindIsNotGroupOrGroupDisbanded_Should await InviteAndAcceptAsync(service, group.GroupId, OwnerId, MemberOneId); // Act - var direct = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Direct, group.GroupId, OwnerId); - var party = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Party, group.GroupId, OwnerId); - var global = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Global, group.GroupId, OwnerId); + var direct = await service.IsChannelMemberAsync(OnlineChatChannelKind.Direct, group.GroupId, OwnerId); + var party = await service.IsChannelMemberAsync(OnlineChatChannelKind.Party, group.GroupId, OwnerId); + var global = await service.IsChannelMemberAsync(OnlineChatChannelKind.Global, group.GroupId, OwnerId); await service.DisbandAsync(CreatePlayerScope(OwnerId), group.GroupId); - var disbanded = await service.IsChannelMemberAsync(TenantId, AppId, OnlineChatChannelKind.Group, group.GroupId, OwnerId); + var disbanded = await service.IsChannelMemberAsync(OnlineChatChannelKind.Group, group.GroupId, OwnerId); // Assert Assert.False(direct); @@ -618,7 +613,7 @@ private static async Task InviteAndAcceptAsync(OnlineGroupService s /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineHotfixRollbackServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineHotfixRollbackServiceTests.cs index 819ad61ee..48e5df6d7 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineHotfixRollbackServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineHotfixRollbackServiceTests.cs @@ -54,14 +54,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineHotfixRollbackServiceTests { - /// 测试用租户标识。 - private const long TenantId = 9201; - - /// 测试用应用标识。 - private const long AppId = 9202; - - /// 测试用其它 App 标识(隔离用例)。 - private const long OtherAppId = 9902; /// /// 步进时钟(Foundation 协调器依赖 IClock;每次读取前进 10ms, @@ -207,17 +199,17 @@ public Task RegisterAsync(OnlineHotfixProtocolManifest manifest, Cancellat return _inner.RegisterAsync(manifest, cancellationToken); } - public Task FindAsync(long tenantId, long appId, string version, CancellationToken cancellationToken = default) + public Task FindAsync(string version, CancellationToken cancellationToken = default) { - return _inner.FindAsync(tenantId, appId, version, cancellationToken); + return _inner.FindAsync(version, cancellationToken); } - public Task FindActiveAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task FindActiveAsync(CancellationToken cancellationToken = default) { - return _inner.FindActiveAsync(tenantId, appId, cancellationToken); + return _inner.FindActiveAsync(cancellationToken); } - public async Task SetActiveAsync(long tenantId, long appId, string version, CancellationToken cancellationToken = default) + public async Task SetActiveAsync(string version, CancellationToken cancellationToken = default) { SetActiveCallCount++; if (RemainingSetActiveFailures > 0) @@ -226,7 +218,7 @@ public async Task SetActiveAsync(long tenantId, long appId, string versi throw new InvalidOperationException(FailMessage); } - return await _inner.SetActiveAsync(tenantId, appId, version, cancellationToken); + return await _inner.SetActiveAsync(version, cancellationToken); } } @@ -328,8 +320,6 @@ private static OnlineHotfixProtocolManifest CreateManifest(string version, param return new OnlineHotfixProtocolManifest { Version = version, - TenantId = TenantId, - AppId = AppId, Messages = messages.ToList(), RegisteredTime = 1_760_000_000_000L, }; @@ -356,7 +346,6 @@ private static OnlineHotfixRollbackRequest CreateRollbackRequest(string targetVe { return new OnlineHotfixRollbackRequest { - Scope = new OnlineScope(TenantId, AppId, 0), TargetVersion = targetVersion, OperatorId = "admin-001", OperatorName = "运维一号", @@ -372,9 +361,9 @@ private static OnlineHotfixRollbackRequest CreateRollbackRequest(string targetVe private static async Task SetupActiveV2Async(Harness harness) { await harness.Service.RegisterAsync(CreateManifest("1.0.0", Msg("LoginReq", 1), Msg("LoginRes", 2))); - await harness.Service.ActivateAsync(new OnlineScope(TenantId, AppId, 0), "1.0.0"); + await harness.Service.ActivateAsync("1.0.0"); await harness.Service.RegisterAsync(CreateManifest("1.1.0", Msg("LoginReq", 1), Msg("LoginRes", 2))); - await harness.Service.ActivateAsync(new OnlineScope(TenantId, AppId, 0), "1.1.0"); + await harness.Service.ActivateAsync("1.1.0"); } /// @@ -384,7 +373,7 @@ private static async Task SetupActiveV2Async(Harness harness) /// 审计记录数。 private static async Task CountAuditRecordsAsync(Harness harness) { - var page = await harness.AuditService.QueryAsync(new OnlineScope(TenantId, AppId, 0)); + var page = await harness.AuditService.QueryAsync(); return page.Data.Records.Count; } @@ -495,10 +484,10 @@ public async Task RollbackAsync_CompatibleTarget_SwitchesVersionAuditsAndPublish Assert.Equal(1, harness.Executor.CallCount); Assert.Equal("1.0.0", harness.Executor.TargetVersions[0]); - var active = await harness.Store.FindActiveAsync(TenantId, AppId); + var active = await harness.Store.FindActiveAsync(); Assert.Equal("1.0.0", active.Version); - var page = await harness.AuditService.QueryAsync(new OnlineScope(TenantId, AppId, 0)); + var page = await harness.AuditService.QueryAsync(); var record = Assert.Single(page.Data.Records); Assert.Equal(OnlineAuditDomain.Operation, record.Domain); Assert.Equal("hotfix-rollback-rb-key-001", record.EventId); @@ -568,7 +557,7 @@ public async Task RollbackAsync_UnregisteredTarget_RejectedWith404() Assert.Equal(OnlineErrorCode.ResourceNotFound, result.Code); Assert.Equal(0, harness.Executor.CallCount); Assert.Equal(0, await CountAuditRecordsAsync(harness)); - Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync()).Version); } /// @@ -612,9 +601,9 @@ public async Task RollbackAsync_IncompatibleTarget_RejectedAndVersionUnchanged() { var harness = new Harness(new OnlineAuditService(new InMemoryOnlineAuditStore())); await harness.Service.RegisterAsync(CreateManifest("1.0.0", Msg("LoginReq", 1))); - await harness.Service.ActivateAsync(new OnlineScope(TenantId, AppId, 0), "1.0.0"); + await harness.Service.ActivateAsync("1.0.0"); await harness.Service.RegisterAsync(CreateManifest("1.1.0", Msg("LoginReq", 1), Msg("MatchReq", 5))); - await harness.Service.ActivateAsync(new OnlineScope(TenantId, AppId, 0), "1.1.0"); + await harness.Service.ActivateAsync("1.1.0"); var result = await harness.Service.RollbackAsync(CreateRollbackRequest("1.0.0", "rb-key-007")); @@ -622,7 +611,7 @@ public async Task RollbackAsync_IncompatibleTarget_RejectedAndVersionUnchanged() Assert.Equal(OnlineErrorCode.VersionConflict, result.Code); Assert.Contains("Removed=1", result.Message); Assert.Equal(0, harness.Executor.CallCount); - Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync()).Version); } /// @@ -639,13 +628,13 @@ public async Task RollbackAsync_ExecutorFails_RejectedAndIdempotencyReleased() Assert.False(failed.IsSuccess); Assert.Equal(OnlineErrorCode.DependencyUnavailable, failed.Code); - Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync()).Version); harness.Executor.FailMessage = null; var retried = await harness.Service.RollbackAsync(CreateRollbackRequest("1.0.0", "rb-key-008")); Assert.True(retried.IsSuccess); Assert.False(retried.Data.IsReplay); - Assert.Equal("1.0.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.0.0", (await harness.Store.FindActiveAsync()).Version); } /// @@ -661,7 +650,7 @@ public async Task RollbackAsync_ExecutorMissing_RejectedWithDependencyUnavailabl Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.DependencyUnavailable, result.Code); - Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync()).Version); } /// @@ -679,7 +668,7 @@ public async Task RollbackAsync_AuditIngestFails_RejectedWithoutExecution() Assert.Equal(OnlineErrorCode.InternalError, result.Code); Assert.Contains("无审计不执行", result.Message); Assert.Equal(0, harness.Executor.CallCount); - Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync()).Version); } // ==================== 参数校验(4001 宁拒毋缺) ==================== @@ -744,7 +733,7 @@ public async Task CheckProtocolCompatibilityAsync_ReturnsReportWithoutSideEffect // 预检目标取超集版本(Added 兼容差异):当前 1.1.0={LoginReq,LoginRes},目标 2.0.0 多一条 ChatReq。 await harness.Service.RegisterAsync(CreateManifest("2.0.0", Msg("LoginReq", 1), Msg("LoginRes", 2), Msg("ChatReq", 7))); - var report = await harness.Service.CheckProtocolCompatibilityAsync(new OnlineScope(TenantId, AppId, 0), "2.0.0"); + var report = await harness.Service.CheckProtocolCompatibilityAsync("2.0.0"); Assert.True(report.IsSuccess); Assert.True(report.Data.IsCompatible); @@ -752,7 +741,7 @@ public async Task CheckProtocolCompatibilityAsync_ReturnsReportWithoutSideEffect Assert.Equal(0, harness.Executor.CallCount); Assert.Equal(0, await CountAuditRecordsAsync(harness)); Assert.Empty(harness.EventRecorder.Filter(OnlineHotfixEvents.RolledBack)); - Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync()).Version); } /// @@ -770,7 +759,7 @@ public async Task RegisterAsync_DuplicateVersion_IdempotentReceiptWithoutOverwri Assert.True(second.IsSuccess); Assert.False(second.Data); - var stored = await harness.Store.FindAsync(TenantId, AppId, "1.0.0"); + var stored = await harness.Store.FindAsync("1.0.0"); Assert.Single(stored.Messages); Assert.Single(harness.EventRecorder.Filter(OnlineHotfixEvents.VersionRegistered)); } @@ -797,29 +786,12 @@ public async Task ActivateAsync_UnregisteredVersion_RejectedWith404() { var harness = new Harness(new OnlineAuditService(new InMemoryOnlineAuditStore())); - var result = await harness.Service.ActivateAsync(new OnlineScope(TenantId, AppId, 0), "404.0.0"); + var result = await harness.Service.ActivateAsync("404.0.0"); Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.ResourceNotFound, result.Code); } - /// - /// 作用域隔离:清单是 App 级资产,其它 App 查不到本 App 登记的版本(4002 反预言)。 - /// - [Fact] - public async Task RollbackAsync_CrossAppVersionInvisible_RejectedWith404() - { - var harness = new Harness(new OnlineAuditService(new InMemoryOnlineAuditStore())); - await SetupActiveV2Async(harness); - var request = CreateRollbackRequest("1.0.0", "rb-key-012"); - request.Scope = new OnlineScope(TenantId, OtherAppId, 0); - - var result = await harness.Service.RollbackAsync(request); - - Assert.False(result.IsSuccess); - Assert.Equal(OnlineErrorCode.ResourceNotFound, result.Code); - Assert.Equal(0, harness.Executor.CallCount); - } /// /// 登记携带制品字段(SourceUrl + Sha256 成对):获取器先行(登记先于清单落簿),登记成功。 @@ -839,7 +811,7 @@ public async Task RegisterAsync_WithArtifactFields_FetchesThenRegisters() Assert.True(result.Data); Assert.Equal(1, fetcher.CallCount); Assert.Equal(("3.0.0", "http://artifacts.test/3.0.0/GameFrameX.Hotfix.dll", new string('a', 64)), fetcher.Calls[0]); - Assert.NotNull(await harness.Store.FindAsync(TenantId, AppId, "3.0.0")); + Assert.NotNull(await harness.Store.FindAsync("3.0.0")); } /// @@ -858,7 +830,7 @@ public async Task RegisterAsync_FetchFailure_RejectedWithDependencyUnavailableAn Assert.False(failure.IsSuccess); Assert.Equal(OnlineErrorCode.DependencyUnavailable, failure.Code); - Assert.Null(await harness.Store.FindAsync(TenantId, AppId, "3.0.0")); + Assert.Null(await harness.Store.FindAsync("3.0.0")); fetcher.FailMessage = null; var retry = await harness.Service.RegisterAsync(manifest); @@ -883,7 +855,7 @@ public async Task RegisterAsync_UrlOnlyWithoutSha_RejectedWithParameterInvalid() Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.ParameterInvalid, result.Code); Assert.Equal(0, fetcher.CallCount); - Assert.Null(await harness.Store.FindAsync(TenantId, AppId, "3.0.0")); + Assert.Null(await harness.Store.FindAsync("3.0.0")); } /// @@ -954,7 +926,7 @@ public async Task RegisterAsync_ArtifactFieldsWithoutFetcher_RejectedWithDepende Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.DependencyUnavailable, result.Code); - Assert.Null(await harness.Store.FindAsync(TenantId, AppId, "3.0.0")); + Assert.Null(await harness.Store.FindAsync("3.0.0")); } // ==================== 活跃指针写入失败:重试与反切补偿 ==================== @@ -978,7 +950,7 @@ public async Task RollbackAsync_ActivePointerWriteTransientFailure_RetriedAndSuc Assert.Equal(4, store.SetActiveCallCount); // setup 激活 2 次 + 命令第 1 次失败 + 第 2 次成功 Assert.Equal(1, harness.Executor.CallCount); Assert.Equal(new[] { "1.0.0", }, harness.Executor.TargetVersions); - Assert.Equal("1.0.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.0.0", (await harness.Store.FindActiveAsync()).Version); Assert.Equal(1, await CountAuditRecordsAsync(harness)); var warnLine = Assert.Single(rollbackLog.WarnLines); Assert.Contains("transition=pointer-write-failed", warnLine); @@ -1007,7 +979,7 @@ public async Task RollbackAsync_ActivePointerWriteExhausted_RevertsExecutorToPre Assert.Equal(OnlineErrorCode.InternalError, failed.Code); Assert.Equal(6, store.SetActiveCallCount); // setup 激活 2 次 + 命令 4 次尝试全部失败 Assert.Equal(new[] { "1.0.0", "1.1.0", }, harness.Executor.TargetVersions); - Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync()).Version); Assert.Contains(rollbackLog.ErrorLines, line => line.Contains("transition=pointer-write-exhausted")); Assert.Contains(rollbackLog.WarnLines, line => line.Contains("transition=executor-reverted")); Assert.Equal(3, rollbackLog.WarnLines.Count(line => line.Contains("transition=pointer-write-failed"))); @@ -1015,7 +987,7 @@ public async Task RollbackAsync_ActivePointerWriteExhausted_RevertsExecutorToPre store.RemainingSetActiveFailures = 0; var retried = await harness.Service.RollbackAsync(CreateRollbackRequest("1.0.0", "rb-key-102")); Assert.True(retried.IsSuccess); - Assert.Equal("1.0.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.0.0", (await harness.Store.FindActiveAsync()).Version); } /// @@ -1040,7 +1012,7 @@ public async Task RollbackAsync_ActivePointerWriteExhaustedAndRevertFails_Report Assert.Contains("须对账", failed.Message); Assert.Equal(6, store.SetActiveCallCount); // setup 激活 2 次 + 命令 4 次尝试全部失败 Assert.Equal(new[] { "1.0.0", "1.1.0", }, harness.Executor.TargetVersions); - Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync(TenantId, AppId)).Version); + Assert.Equal("1.1.0", (await harness.Store.FindActiveAsync()).Version); var exhaustedLine = Assert.Single(rollbackLog.ErrorLines, line => line.Contains("transition=pointer-write-exhausted")); Assert.Contains("attempts=4", exhaustedLine); var revertFailedLine = Assert.Single(rollbackLog.ErrorLines, line => line.Contains("transition=executor-revert-failed")); diff --git a/Tests/GameFrameX.Tests/Online/OnlineIdempotencyServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineIdempotencyServiceTests.cs index 4a931e39f..b8ab928ba 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineIdempotencyServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineIdempotencyServiceTests.cs @@ -103,7 +103,7 @@ public async Task BeginAsync_WithInvalidKey_ShouldReturnInvalidOutcome(string id // Arrange var auditSink = new CollectingAuditSink(); var service = CreateService(auditSink); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act var outcome = await service.BeginAsync(scope, idempotencyKey, "{\"amount\":1}", true); @@ -114,7 +114,7 @@ public async Task BeginAsync_WithInvalidKey_ShouldReturnInvalidOutcome(string id Assert.False(outcome.CanExecute); Assert.Single(auditSink.Records); Assert.Equal(OnlineIdempotencyOutcomeKind.InvalidKey, auditSink.Records[0].OutcomeKind); - Assert.Equal("online:1:10:100:10001", auditSink.Records[0].ScopeKey); + Assert.Equal("online:100:10001", auditSink.Records[0].ScopeKey); } /// @@ -125,7 +125,7 @@ public async Task BeginAsync_FirstRequest_ShouldReturnExecute() { // Arrange var service = CreateService(new CollectingAuditSink()); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act var outcome = await service.BeginAsync(scope, "order-create-001", "{\"amount\":1}", true); @@ -134,7 +134,7 @@ public async Task BeginAsync_FirstRequest_ShouldReturnExecute() Assert.Equal(OnlineIdempotencyOutcomeKind.Execute, outcome.Kind); Assert.Equal(OnlineErrorCode.None, outcome.ErrorCode); Assert.True(outcome.CanExecute); - Assert.Equal("online:1:10:100:10001", outcome.ScopeKey); + Assert.Equal("online:100:10001", outcome.ScopeKey); Assert.Equal("order-create-001", outcome.IdempotencyKey); } @@ -146,7 +146,7 @@ public async Task BeginAsync_AfterComplete_WithSameKeyAndRequest_ShouldReplayFir { // Arrange var service = CreateService(new CollectingAuditSink()); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); var firstResponse = new byte[] { 1, 2, 3, 4 }; // Act @@ -170,7 +170,7 @@ public async Task BeginAsync_WithSameKeyButDifferentRequest_ShouldReturnConflict { // Arrange var service = CreateService(new CollectingAuditSink()); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act var first = await service.BeginAsync(scope, "order-create-003", "{\"amount\":3}", true); @@ -192,7 +192,7 @@ public async Task BeginAsync_WhileProcessing_ShouldReturnBusy() { // Arrange var service = CreateService(new CollectingAuditSink()); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act var first = await service.BeginAsync(scope, "order-create-004", "{\"amount\":4}", true); @@ -213,8 +213,8 @@ public async Task BeginAsync_WithDifferentPlayers_ShouldIsolateRecords() { // Arrange var service = CreateService(new CollectingAuditSink()); - var playerA = new OnlineScope(1, 10, 100, 10001); - var playerB = new OnlineScope(1, 10, 100, 10002); + var playerA = new OnlineScope(100, 10001); + var playerB = new OnlineScope(100, 10002); // Act var outcomeA = await service.BeginAsync(playerA, "order-create-005", "{\"amount\":5}", true); @@ -223,8 +223,8 @@ public async Task BeginAsync_WithDifferentPlayers_ShouldIsolateRecords() // Assert Assert.Equal(OnlineIdempotencyOutcomeKind.Execute, outcomeA.Kind); Assert.Equal(OnlineIdempotencyOutcomeKind.Execute, outcomeB.Kind); - Assert.Equal("online:1:10:100:10001", outcomeA.ScopeKey); - Assert.Equal("online:1:10:100:10002", outcomeB.ScopeKey); + Assert.Equal("online:100:10001", outcomeA.ScopeKey); + Assert.Equal("online:100:10002", outcomeB.ScopeKey); } /// @@ -236,7 +236,7 @@ public async Task BeginAsync_ShouldWriteAuditForEachDecision() // Arrange var auditSink = new CollectingAuditSink(); var service = CreateService(auditSink); - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act await service.BeginAsync(scope, "order-create-006", "{\"amount\":6}", true); diff --git a/Tests/GameFrameX.Tests/Online/OnlineIdentityServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineIdentityServiceTests.cs index c9d1be9bb..04bec6392 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineIdentityServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineIdentityServiceTests.cs @@ -42,12 +42,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineIdentityServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -70,8 +64,8 @@ public async Task ResolveLoginAsync_NewIdentity_ShouldAutoRegisterAndYieldContex var service = CreateService(); // Act - var first = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); - var second = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); + var first = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); + var second = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); // Assert Assert.True(first.IsSuccess); @@ -80,10 +74,8 @@ public async Task ResolveLoginAsync_NewIdentity_ShouldAutoRegisterAndYieldContex Assert.Equal(first.Data.Player.Id, second.Data.Player.Id); Assert.Equal(OnlineGameAccountStatus.Active, first.Data.GameAccount.Status); - var scope = new OnlineScope(TenantId, AppId, ServerId, first.Data.Player.Id); + var scope = new OnlineScope(ServerId, first.Data.Player.Id); var context = OnlinePlayerContext.FromScope(scope, first.Data.GameAccount.Id, "sess-1"); - Assert.Equal(TenantId, context.TenantId); - Assert.Equal(AppId, context.AppId); Assert.Equal(ServerId, context.ServerId); Assert.Equal(first.Data.Player.Id, context.PlayerId); Assert.Equal(first.Data.GameAccount.Id, context.GameAccountId); @@ -97,10 +89,10 @@ public async Task ResolveLoginAsync_NewServer_ShouldReuseAccountAndCreateServerP { // Arrange var service = CreateService(); - var first = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bob" }); + var first = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bob" }); // Act - var second = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId + 1, Kind = OnlineIdentityKind.UserName, Identifier = "bob" }); + var second = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId + 1, Kind = OnlineIdentityKind.UserName, Identifier = "bob" }); // Assert Assert.True(second.IsSuccess); @@ -117,12 +109,12 @@ public async Task RebindDeviceAsync_OldDevice_ShouldBeRejectedOnNextLogin() { // Arrange var service = CreateService(); - var first = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "carol", DeviceIdentifier = "device-old", DevicePlatform = "iOS" }); + var first = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "carol", DeviceIdentifier = "device-old", DevicePlatform = "iOS" }); // Act var rebind = await service.RebindDeviceAsync(first.Data.GameAccount.Id, "device-old", "device-new", "Android"); - var oldDeviceLogin = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "carol", DeviceIdentifier = "device-old", DevicePlatform = "iOS" }); - var newDeviceLogin = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "carol", DeviceIdentifier = "device-new", DevicePlatform = "Android" }); + var oldDeviceLogin = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "carol", DeviceIdentifier = "device-old", DevicePlatform = "iOS" }); + var newDeviceLogin = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "carol", DeviceIdentifier = "device-new", DevicePlatform = "Android" }); // Assert Assert.True(rebind.IsSuccess); @@ -139,11 +131,11 @@ public async Task DeactivateAccountAsync_SubsequentLogin_ShouldBeRejected() { // Arrange var service = CreateService(); - var first = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "dave" }); + var first = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "dave" }); // Act var deactivated = await service.DeactivateAccountAsync(first.Data.GameAccount.Id, 0); - var login = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "dave" }); + var login = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "dave" }); // Assert Assert.True(deactivated.IsSuccess); @@ -160,19 +152,19 @@ public async Task ResolveLoginAsync_UnboundIdentity_ShouldReviveOriginalAccount( // Arrange:账号绑定两个身份后解绑主身份(保留辅身份满足解绑前提)。 var store = new InMemoryOnlineIdentityStore(); var service = new OnlineIdentityService(store, new OnlineAuditService(new InMemoryOnlineAuditStore())); - var first = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "grace" }); + var first = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "grace" }); var originalAccountId = first.Data.GameAccount.Id; - Assert.True((await service.BindIdentityAsync(TenantId, AppId, originalAccountId, OnlineIdentityKind.Email, "grace@example.com")).IsSuccess); - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.UserName, "grace")).IsSuccess); + Assert.True((await service.BindIdentityAsync(originalAccountId, OnlineIdentityKind.Email, "grace@example.com")).IsSuccess); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.UserName, "grace")).IsSuccess); // Act - var reviveLogin = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "grace" }); + var reviveLogin = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "grace" }); // Assert:复用原账号与原玩家,未产生新账号。 Assert.True(reviveLogin.IsSuccess); Assert.Equal(originalAccountId, reviveLogin.Data.GameAccount.Id); Assert.Equal(first.Data.Player.Id, reviveLogin.Data.Player.Id); - var revivedIdentity = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.UserName, "grace", CancellationToken.None); + var revivedIdentity = await store.FindIdentityAsync(OnlineIdentityKind.UserName, "grace", CancellationToken.None); Assert.Equal(0, revivedIdentity.UnboundAtTime); Assert.Equal(originalAccountId, revivedIdentity.GameAccountId); } @@ -185,13 +177,13 @@ public async Task ResolveLoginAsync_UnboundIdentity_DeactivatedAccount_ShouldBeR { // Arrange var service = new OnlineIdentityService(new InMemoryOnlineIdentityStore(), new OnlineAuditService(new InMemoryOnlineAuditStore())); - var first = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "heidi" }); - Assert.True((await service.BindIdentityAsync(TenantId, AppId, first.Data.GameAccount.Id, OnlineIdentityKind.Email, "heidi@example.com")).IsSuccess); - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.UserName, "heidi")).IsSuccess); + var first = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "heidi" }); + Assert.True((await service.BindIdentityAsync(first.Data.GameAccount.Id, OnlineIdentityKind.Email, "heidi@example.com")).IsSuccess); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.UserName, "heidi")).IsSuccess); Assert.True((await service.DeactivateAccountAsync(first.Data.GameAccount.Id, 0)).IsSuccess); // Act - var login = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "heidi" }); + var login = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "heidi" }); // Assert Assert.False(login.IsSuccess); @@ -207,12 +199,12 @@ public async Task MergeAccountsAsync_SourceIdentities_ShouldFollowTargetAccount( { // Arrange var service = CreateService(); - var source = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "erin" }); - var target = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "frank" }); + var source = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "erin" }); + var target = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "frank" }); // Act var merged = await service.MergeAccountsAsync(source.Data.GameAccount.Id, target.Data.GameAccount.Id); - var sourceLogin = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "erin" }); + var sourceLogin = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "erin" }); // Assert:合并后源身份登录跟随目标账号,源玩家档案随合并迁移保留(归属目标账号)。 Assert.True(merged.IsSuccess); @@ -233,8 +225,8 @@ public async Task ResolveLoginAsync_InvalidArguments_ShouldBeRejected() var service = CreateService(); // Act - var badKind = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = (OnlineIdentityKind)99, Identifier = "alice" }); - var emptyIdentifier = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = string.Empty }); + var badKind = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = (OnlineIdentityKind)99, Identifier = "alice" }); + var emptyIdentifier = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = string.Empty }); // Assert Assert.False(badKind.IsSuccess); @@ -253,27 +245,27 @@ public async Task BindIdentityAsync_CrossAccountUnboundIdentity_TicketLifecycle_ var store = new InMemoryOnlineIdentityStore(); var auditStore = new InMemoryOnlineAuditStore(); var service = new OnlineIdentityService(store, new OnlineAuditService(auditStore)); - var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); - var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); - var accountC = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "carol" }); - Assert.True((await service.BindIdentityAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); + var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); + var accountC = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "carol" }); + Assert.True((await service.BindIdentityAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); // Act / Assert ①:无票据 → StateOperationForbidden,身份仍指向 A。 - var withoutTicket = await service.BindIdentityAsync(TenantId, AppId, accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); + var withoutTicket = await service.BindIdentityAsync(accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); Assert.False(withoutTicket.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, withoutTicket.Code); - Assert.Equal(accountA.Data.GameAccount.Id, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).GameAccountId); + Assert.Equal(accountA.Data.GameAccount.Id, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).GameAccountId); // Act / Assert ②:A 签发票据 → B 携票据改绑成功,身份指向 B,审计条目在档。 - var authorization = await service.IssueIdentityRebindAuthorizationAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); + var authorization = await service.IssueIdentityRebindAuthorizationAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); Assert.True(authorization.IsSuccess); - var withTicket = await service.BindIdentityAsync(TenantId, AppId, accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com", authorization.Data.Code); + var withTicket = await service.BindIdentityAsync(accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com", authorization.Data.Code); Assert.True(withTicket.IsSuccess); - var rebound = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com"); + var rebound = await store.FindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com"); Assert.Equal(accountB.Data.GameAccount.Id, rebound.GameAccountId); Assert.Equal(0, rebound.UnboundAtTime); - var auditRecords = (await auditStore.QueryAsync(new OnlineAuditStoreQuery { TenantId = TenantId, AppId = AppId })).Records; + var auditRecords = (await auditStore.QueryAsync(new OnlineAuditStoreQuery())).Records; var auditRecord = auditRecords.Single(record => record.EventType == "online.identity.rebound"); Assert.NotNull(auditRecord); Assert.Equal(OnlineAuditDomain.Operation, auditRecord.Domain); @@ -283,11 +275,11 @@ public async Task BindIdentityAsync_CrossAccountUnboundIdentity_TicketLifecycle_ Assert.Contains(auditRecord.SanitizedFields, pair => pair.Key == "newGameAccountId" && pair.Value == accountB.Data.GameAccount.Id.ToString()); // Act / Assert ③:同一票据第二次使用被拒——B 解绑后第三方(carol)携已消费票据改绑 → 拒绝,身份仍归 B。 - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - var reusedTicket = await service.BindIdentityAsync(TenantId, AppId, accountC.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com", authorization.Data.Code); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + var reusedTicket = await service.BindIdentityAsync(accountC.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com", authorization.Data.Code); Assert.False(reusedTicket.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, reusedTicket.Code); - Assert.Equal(accountB.Data.GameAccount.Id, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).GameAccountId); + Assert.Equal(accountB.Data.GameAccount.Id, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).GameAccountId); } /// @@ -299,16 +291,16 @@ public async Task BindIdentityAsync_OwnerRebindOwnUnboundIdentity_ShouldSucceedW // Arrange var store = new InMemoryOnlineIdentityStore(); var service = new OnlineIdentityService(store, new OnlineAuditService(new InMemoryOnlineAuditStore())); - var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); - Assert.True((await service.BindIdentityAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); + Assert.True((await service.BindIdentityAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); // Act - var rebound = await service.BindIdentityAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); + var rebound = await service.BindIdentityAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); // Assert Assert.True(rebound.IsSuccess); - var identity = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com"); + var identity = await store.FindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com"); Assert.Equal(accountA.Data.GameAccount.Id, identity.GameAccountId); Assert.Equal(0, identity.UnboundAtTime); } @@ -322,20 +314,20 @@ public async Task BindIdentityAsync_ConcurrentSameNewIdentity_ExactlyOneWinner() // Arrange var store = new InMemoryOnlineIdentityStore(); var service = new OnlineIdentityService(store, new OnlineAuditService(new InMemoryOnlineAuditStore())); - var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); - var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); + var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); + var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); // Act:真并发双绑定(InMemory 全锁原子,恰一胜者确定性成立)。 var results = await Task.WhenAll( - service.BindIdentityAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "race@example.com"), - service.BindIdentityAsync(TenantId, AppId, accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "race@example.com")); + service.BindIdentityAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "race@example.com"), + service.BindIdentityAsync(accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "race@example.com")); // Assert:恰一成功;败者拒绝码取决于交错时序——双查皆 miss 后唯一插入冲突为 VersionConflict, // 后查者见到已绑定行则按归属拒绝为 StateOperationForbidden,两者都是诚实的败者回执。 Assert.Equal(1, results.Count(result => result.IsSuccess)); var loser = results.Single(result => !result.IsSuccess); Assert.Contains(loser.Code, new[] { OnlineErrorCode.VersionConflict, OnlineErrorCode.StateOperationForbidden }); - var identity = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "race@example.com"); + var identity = await store.FindIdentityAsync(OnlineIdentityKind.Email, "race@example.com"); Assert.Contains(identity.GameAccountId, new[] { accountA.Data.GameAccount.Id, accountB.Data.GameAccount.Id }); } @@ -348,20 +340,20 @@ public async Task BindIdentityAsync_ExpiredTicket_ShouldBeRejected() // Arrange var store = new InMemoryOnlineIdentityStore(); var service = new OnlineIdentityService(store, new OnlineAuditService(new InMemoryOnlineAuditStore()), 0); - var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); - var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); - Assert.True((await service.BindIdentityAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - var authorization = await service.IssueIdentityRebindAuthorizationAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); + var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); + var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); + Assert.True((await service.BindIdentityAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + var authorization = await service.IssueIdentityRebindAuthorizationAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); Assert.True(authorization.IsSuccess); // Act - var expired = await service.BindIdentityAsync(TenantId, AppId, accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com", authorization.Data.Code); + var expired = await service.BindIdentityAsync(accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com", authorization.Data.Code); // Assert Assert.False(expired.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, expired.Code); - Assert.Equal(accountA.Data.GameAccount.Id, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).GameAccountId); + Assert.Equal(accountA.Data.GameAccount.Id, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).GameAccountId); } /// @@ -373,24 +365,24 @@ public async Task BindIdentityAsync_OriginalAccountDeactivated_ShouldBeRejected( // Arrange var store = new InMemoryOnlineIdentityStore(); var service = new OnlineIdentityService(store, new OnlineAuditService(new InMemoryOnlineAuditStore())); - var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); - var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); - Assert.True((await service.BindIdentityAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - var authorization = await service.IssueIdentityRebindAuthorizationAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); + var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); + var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); + Assert.True((await service.BindIdentityAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + var authorization = await service.IssueIdentityRebindAuthorizationAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); Assert.True(authorization.IsSuccess); Assert.True((await service.DeactivateAccountAsync(accountA.Data.GameAccount.Id, 0)).IsSuccess); // Act - var withTicket = await service.BindIdentityAsync(TenantId, AppId, accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com", authorization.Data.Code); - var withoutTicket = await service.BindIdentityAsync(TenantId, AppId, accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); + var withTicket = await service.BindIdentityAsync(accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com", authorization.Data.Code); + var withoutTicket = await service.BindIdentityAsync(accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); // Assert Assert.False(withTicket.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, withTicket.Code); Assert.False(withoutTicket.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, withoutTicket.Code); - Assert.Equal(accountA.Data.GameAccount.Id, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).GameAccountId); + Assert.Equal(accountA.Data.GameAccount.Id, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).GameAccountId); } /// @@ -402,27 +394,27 @@ public async Task IssueIdentityRebindAuthorizationAsync_OwnershipAndScope_Should // Arrange var store = new InMemoryOnlineIdentityStore(); var service = new OnlineIdentityService(store, new OnlineAuditService(new InMemoryOnlineAuditStore())); - var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); - var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); - Assert.True((await service.BindIdentityAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - Assert.True((await service.BindIdentityAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice-alt@example.com")).IsSuccess); - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); - Assert.True((await service.UnbindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "alice-alt@example.com")).IsSuccess); + var accountA = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "alice" }); + var accountB = await service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "bobby" }); + Assert.True((await service.BindIdentityAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + Assert.True((await service.BindIdentityAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice-alt@example.com")).IsSuccess); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.Email, "alice@example.com")).IsSuccess); + Assert.True((await service.UnbindIdentityAsync(OnlineIdentityKind.Email, "alice-alt@example.com")).IsSuccess); // Act / Assert ①:非归属账号(B)签发 → 拒绝。 - var nonOwner = await service.IssueIdentityRebindAuthorizationAsync(TenantId, AppId, accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); + var nonOwner = await service.IssueIdentityRebindAuthorizationAsync(accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); Assert.False(nonOwner.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, nonOwner.Code); // Act / Assert ②:身份不存在 → 拒绝。 - var unknownIdentity = await service.IssueIdentityRebindAuthorizationAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "nobody@example.com"); + var unknownIdentity = await service.IssueIdentityRebindAuthorizationAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "nobody@example.com"); Assert.False(unknownIdentity.IsSuccess); Assert.Equal(OnlineErrorCode.ResourceNotFound, unknownIdentity.Code); // Act / Assert ③:A 为 alice@example.com 签发票据,B 拿它改绑另一个身份 → 作用域不匹配拒绝。 - var authorization = await service.IssueIdentityRebindAuthorizationAsync(TenantId, AppId, accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); + var authorization = await service.IssueIdentityRebindAuthorizationAsync(accountA.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice@example.com"); Assert.True(authorization.IsSuccess); - var mismatched = await service.BindIdentityAsync(TenantId, AppId, accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice-alt@example.com", authorization.Data.Code); + var mismatched = await service.BindIdentityAsync(accountB.Data.GameAccount.Id, OnlineIdentityKind.Email, "alice-alt@example.com", authorization.Data.Code); Assert.False(mismatched.IsSuccess); Assert.Equal(OnlineErrorCode.StateOperationForbidden, mismatched.Code); } @@ -438,8 +430,6 @@ public async Task InMemoryStore_IdentityConditionalWrites_ShouldMatchContract() var identity = new OnlineIdentity { Id = "ident-1", - TenantId = TenantId, - AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 101, @@ -449,26 +439,26 @@ public async Task InMemoryStore_IdentityConditionalWrites_ShouldMatchContract() // Act / Assert ①:唯一插入成功建档版本 1;同键再插 false 且零覆写。 Assert.True(await store.TryAddIdentityAsync(identity)); - var winner = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "primitive@example.com"); + var winner = await store.FindIdentityAsync(OnlineIdentityKind.Email, "primitive@example.com"); Assert.Equal(1, winner.RowVersion); - var contender = new OnlineIdentity { Id = "ident-2", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 202 }; + var contender = new OnlineIdentity { Id = "ident-2", Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 202 }; Assert.False(await store.TryAddIdentityAsync(contender)); - Assert.Equal(101, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "primitive@example.com")).GameAccountId); + Assert.Equal(101, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "primitive@example.com")).GameAccountId); // Act / Assert ②:CAS 匹配版本写入并 +1;过期版本拒绝零写入。 - var rebound = new OnlineIdentity { Id = "ident-1", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 202 }; + var rebound = new OnlineIdentity { Id = "ident-1", Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 202 }; Assert.True(await store.TryUpdateIdentityIfRowVersionAsync(rebound, winner.RowVersion)); - var updated = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "primitive@example.com"); + var updated = await store.FindIdentityAsync(OnlineIdentityKind.Email, "primitive@example.com"); Assert.Equal(202, updated.GameAccountId); Assert.Equal(2, updated.RowVersion); - var staleAttempt = new OnlineIdentity { Id = "ident-1", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 303 }; + var staleAttempt = new OnlineIdentity { Id = "ident-1", Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 303 }; Assert.False(await store.TryUpdateIdentityIfRowVersionAsync(staleAttempt, 1)); - Assert.Equal(202, (await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "primitive@example.com")).GameAccountId); + Assert.Equal(202, (await store.FindIdentityAsync(OnlineIdentityKind.Email, "primitive@example.com")).GameAccountId); // Act / Assert ③:盲写保留存量版本号(不推进,不回退)。 - var blind = new OnlineIdentity { Id = "ident-1", TenantId = TenantId, AppId = AppId, Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 404 }; + var blind = new OnlineIdentity { Id = "ident-1", Kind = OnlineIdentityKind.Email, Identifier = "primitive@example.com", GameAccountId = 404 }; await store.AddOrUpdateIdentityAsync(blind); - var afterBlindWrite = await store.FindIdentityAsync(TenantId, AppId, OnlineIdentityKind.Email, "primitive@example.com"); + var afterBlindWrite = await store.FindIdentityAsync(OnlineIdentityKind.Email, "primitive@example.com"); Assert.Equal(404, afterBlindWrite.GameAccountId); Assert.Equal(2, afterBlindWrite.RowVersion); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineInMemoryStoreConcurrencyTests.cs b/Tests/GameFrameX.Tests/Online/OnlineInMemoryStoreConcurrencyTests.cs index 8586efd52..b47707b9a 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineInMemoryStoreConcurrencyTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineInMemoryStoreConcurrencyTests.cs @@ -47,12 +47,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineInMemoryStoreConcurrencyTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -73,7 +67,7 @@ public async Task ConcurrentRefresh_ShouldAllowExactlyOneWinner() var sessionStore = new InMemoryOnlineSessionStore(); var writeGate = new OnlineSessionWriteGate(); var tokenService = new OnlineSessionTokenService(sessionStore, recorder, new OnlineSessionManager(sessionStore, recorder, writeGate), writeGate); - var scope = new OnlineScope(TenantId, AppId, ServerId, PlayerId); + var scope = new OnlineScope(ServerId, PlayerId); var issued = await tokenService.IssueSessionAsync(scope, 3600, OnlineMultiDevicePolicy.LatestWins, null); Assert.True(issued.IsSuccess); @@ -111,7 +105,7 @@ public async Task ConcurrentCreateSameKey_ShouldAllowExactlyOneWinner() // Arrange var store = new InMemoryOnlinePlayerStorageStore(); var service = new OnlinePlayerStorageService(store, new OnlinePlayerStorageOptions()); - var scope = new OnlineScope(TenantId, AppId, ServerId, PlayerId); + var scope = new OnlineScope(ServerId, PlayerId); // Act var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(index => service.WriteAsync(scope, "settings", "volume", Encode("v" + index), 0, "sess-" + index))); @@ -146,7 +140,7 @@ public async Task ConcurrentResolveSameIdentity_ShouldYieldSingleAccount() var service = new OnlineIdentityService(new InMemoryOnlineIdentityStore(), new OnlineAuditService(new InMemoryOnlineAuditStore())); // Act - var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => service.ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "concurrent-user" }))); + var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => service.ResolveLoginAsync(new OnlineLoginRequest { ServerId = ServerId, Kind = OnlineIdentityKind.UserName, Identifier = "concurrent-user" }))); // Assert:并发自动注册可能产生多账号(首建竞争),但每次解析必须自洽成功且玩家可见一致。 var accountIds = new HashSet(); diff --git a/Tests/GameFrameX.Tests/Online/OnlineLeaderboardServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineLeaderboardServiceTests.cs index 97f21c776..241e9a43f 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineLeaderboardServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineLeaderboardServiceTests.cs @@ -43,21 +43,12 @@ namespace GameFrameX.Tests.Online /// public class OnlineLeaderboardServiceTests { - /// 租户标识。 - private const long TenantId = 1; - - /// 另一租户标识(跨租户用例)。 - private const long OtherTenantId = 2; - - /// App 标识。 - private const long AppId = 10; - - /// 另一 App 标识(跨 App 用例)。 - private const long OtherAppId = 11; - /// 区服标识。 private const long ServerId = 100; + /// 另一区服标识(跨区服用例)。 + private const long OtherServerId = 200; + /// 基准时刻(UTC 毫秒)。 private const long Now = 1000000L; @@ -74,8 +65,6 @@ public async Task CreateAsync_ShouldCreateAndRejectDuplicate() Assert.True(created.IsSuccess, created.Message); Assert.Equal("board-1", created.Data.LeaderboardId); - Assert.Equal(TenantId, created.Data.TenantId); - Assert.Equal(AppId, created.Data.AppId); Assert.Single(harness.Recorder.Filter(OnlineLeaderboardEvents.LeaderboardCreated)); var duplicated = await harness.Service.CreateAsync(harness.Scope(), request, Now + 1); @@ -109,7 +98,7 @@ public async Task ApplySubmission_Policies_ShouldResolveInStore() var board = await harness.CreateBoardAsync("board-best-desc", OnlineLeaderboardSortOrder.Descending, OnlineLeaderboardScoreUpdatePolicy.Best); await harness.SeedAsync(board, (1001, 100, Now), (1001, 50, Now + 1), (1001, 150, Now + 2)); - var bestDesc = await harness.Store.FindEntryAsync(TenantId, AppId, "board-best-desc", 1001); + var bestDesc = await harness.Store.FindEntryAsync("board-best-desc", 1001); Assert.Equal(150, bestDesc.Score); Assert.Equal(3, bestDesc.SubmissionCount); @@ -118,19 +107,19 @@ public async Task ApplySubmission_Policies_ShouldResolveInStore() var ascBoard = await harness.CreateBoardAsync("board-best-asc", OnlineLeaderboardSortOrder.Ascending, OnlineLeaderboardScoreUpdatePolicy.Best); await harness.SeedAsync(ascBoard, (1001, 100, Now), (1001, 50, Now + 1)); - var bestAsc = await harness.Store.FindEntryAsync(TenantId, AppId, "board-best-asc", 1001); + var bestAsc = await harness.Store.FindEntryAsync("board-best-asc", 1001); Assert.Equal(50, bestAsc.Score); var sumBoard = await harness.CreateBoardAsync("board-sum", OnlineLeaderboardSortOrder.Descending, OnlineLeaderboardScoreUpdatePolicy.Sum); await harness.SeedAsync(sumBoard, (1001, 10, Now), (1001, 20, Now + 1)); - var sum = await harness.Store.FindEntryAsync(TenantId, AppId, "board-sum", 1001); + var sum = await harness.Store.FindEntryAsync("board-sum", 1001); Assert.Equal(30, sum.Score); var latestBoard = await harness.CreateBoardAsync("board-latest", OnlineLeaderboardSortOrder.Descending, OnlineLeaderboardScoreUpdatePolicy.Latest); await harness.SeedAsync(latestBoard, (1001, 5, Now), (1001, 9, Now + 1)); - var latest = await harness.Store.FindEntryAsync(TenantId, AppId, "board-latest", 1001); + var latest = await harness.Store.FindEntryAsync("board-latest", 1001); Assert.Equal(9, latest.Score); } @@ -291,23 +280,22 @@ public async Task GetPlayerRankAsync_ShouldReturnRankOrReject() } /// - /// 验证跨 App / 跨租户读榜与榜单不存在同构拒绝(反预言,不泄露存在性)。 + /// 验证榜单是全局域数据(单键化 D4:同键即同榜)——跨区服作用域读到同一份榜单; + /// 未知榜单仍与「不存在」同构拒绝(反预言,不泄露存在性)。 /// [Fact] - public async Task CrossScopeRead_ShouldBeResourceNotFound() + public async Task CrossServerRead_ShouldShareGlobalBoard_AndUnknownBoardStaysResourceNotFound() { var harness = new Harness(); var board = await harness.CreateBoardAsync("board-scope", OnlineLeaderboardSortOrder.Descending, OnlineLeaderboardScoreUpdatePolicy.Best); await harness.SeedAsync(board, (1001, 100, Now)); - var crossApp = await harness.Service.GetTopAsync(harness.Scope(OtherAppId), new OnlineLeaderboardTopQuery { LeaderboardId = "board-scope", Count = 10, NowUnixMilliseconds = Now + 100 }); - var crossTenant = await harness.Service.GetTopAsync(harness.Scope(AppId, OtherTenantId), new OnlineLeaderboardTopQuery { LeaderboardId = "board-scope", Count = 10, NowUnixMilliseconds = Now + 100 }); + var crossServer = await harness.Service.GetTopAsync(harness.Scope(OtherServerId), new OnlineLeaderboardTopQuery { LeaderboardId = "board-scope", Count = 10, NowUnixMilliseconds = Now + 100 }); var unknownBoard = await harness.Service.GetTopAsync(harness.Scope(), new OnlineLeaderboardTopQuery { LeaderboardId = "board-none", Count = 10, NowUnixMilliseconds = Now + 100 }); - Assert.False(crossApp.IsSuccess); - Assert.Equal(OnlineErrorCode.ResourceNotFound, crossApp.Code); - Assert.False(crossTenant.IsSuccess); - Assert.Equal(OnlineErrorCode.ResourceNotFound, crossTenant.Code); + Assert.True(crossServer.IsSuccess, crossServer.Message); + Assert.Single(crossServer.Data.Entries); + Assert.Equal(1001, crossServer.Data.Entries[0].Entry.PlayerId); Assert.False(unknownBoard.IsSuccess); Assert.Equal(OnlineErrorCode.ResourceNotFound, unknownBoard.Code); } @@ -391,12 +379,11 @@ public OnlineLeaderboardService Service /// /// 构造查询作用域。 /// - /// App 标识(默认本 App)。 - /// 租户标识(默认本租户)。 + /// 区服标识(默认本区服)。 /// 作用域。 - public OnlineScope Scope(long appId = AppId, long tenantId = TenantId) + public OnlineScope Scope(long serverId = ServerId) { - return new OnlineScope(tenantId, appId, ServerId); + return new OnlineScope(serverId); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineLeaderboardSumOverflowTests.cs b/Tests/GameFrameX.Tests/Online/OnlineLeaderboardSumOverflowTests.cs index 195fea076..1e9e2b94c 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineLeaderboardSumOverflowTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineLeaderboardSumOverflowTests.cs @@ -47,12 +47,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineLeaderboardSumOverflowTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; - /// 区服标识。 private const long ServerId = 100; @@ -85,7 +79,7 @@ public async Task SumOverflow_Positive_ShouldRejectAndKeepEntry() Assert.Equal(PlayerOne, projected.Data.FailedPlayers[0].PlayerId); Assert.Equal(OnlineErrorCode.ParameterInvalid, projected.Data.FailedPlayers[0].Code); - var entry = await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-ovf-pos", PlayerOne); + var entry = await harness.LeaderboardStore.FindEntryAsync("board-ovf-pos", PlayerOne); Assert.Equal(long.MaxValue - 1, entry.Score); Assert.Equal(1, entry.SubmissionCount); Assert.Equal("mrs-p1", entry.SourceMatchResultId); @@ -111,7 +105,7 @@ public async Task SumOverflow_Negative_ShouldRejectAndKeepEntry() Assert.Single(projected.Data.FailedPlayers); Assert.Equal(OnlineErrorCode.ParameterInvalid, projected.Data.FailedPlayers[0].Code); - var entry = await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-ovf-neg", PlayerOne); + var entry = await harness.LeaderboardStore.FindEntryAsync("board-ovf-neg", PlayerOne); Assert.Equal(long.MinValue + 1, entry.Score); Assert.Equal(1, entry.SubmissionCount); } @@ -134,7 +128,7 @@ public async Task SumOverflow_MixedBatch_ShouldOnlyRejectOverflowPlayer() Assert.Equal(1, projected.Data.AppliedCount); Assert.Single(projected.Data.FailedPlayers); - Assert.Equal(30, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-ovf-mix", PlayerTwo)).Score); + Assert.Equal(30, (await harness.LeaderboardStore.FindEntryAsync("board-ovf-mix", PlayerTwo)).Score); } /// @@ -153,7 +147,7 @@ public async Task SumNormal_Accumulation_ShouldNotBeAffected() Assert.True(first.IsSuccess, first.Message); Assert.True(second.IsSuccess, second.Message); - Assert.Equal(long.MaxValue / 2 + 100, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-ovf-ok", PlayerOne)).Score); + Assert.Equal(long.MaxValue / 2 + 100, (await harness.LeaderboardStore.FindEntryAsync("board-ovf-ok", PlayerOne)).Score); } /// @@ -221,11 +215,10 @@ public OnlineLeaderboardResultProjector Projector /// /// 构造作用域。 /// - /// App 标识。 /// 作用域。 - public OnlineScope Scope(long appId = AppId) + public OnlineScope Scope() { - return new OnlineScope(TenantId, appId, ServerId, 0); + return new OnlineScope(ServerId, 0); } /// @@ -259,8 +252,6 @@ public async Task CommitResultAsync(string matchId, string matchResultId, params { MatchResultId = matchResultId, MatchId = matchId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Mode = 410, Region = 1, diff --git a/Tests/GameFrameX.Tests/Online/OnlineLeaderboardTrustedResultTests.cs b/Tests/GameFrameX.Tests/Online/OnlineLeaderboardTrustedResultTests.cs index 1762527e4..c3d9fa81d 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineLeaderboardTrustedResultTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineLeaderboardTrustedResultTests.cs @@ -48,18 +48,12 @@ namespace GameFrameX.Tests.Online /// public class OnlineLeaderboardTrustedResultTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; - - /// 另一 App 标识(跨 App 用例)。 - private const long OtherAppId = 11; - /// 区服标识。 private const long ServerId = 100; + /// 另一区服标识(跨区服用例)。 + private const long OtherServerId = 200; + /// 玩家一。 private const long PlayerOne = 1001; @@ -80,7 +74,7 @@ public async Task ProjectAsync_FromRealSettledMatch_ShouldWriteTrustedScores() { var harness = new Harness(); await harness.PlayToSettlingAsync(); - var settled = await harness.Settlement.SettleAsync(TenantId, AppId, MatchId, Now + 100); + var settled = await harness.Settlement.SettleAsync(MatchId, Now + 100); Assert.True(settled.IsSuccess, settled.Message); await harness.CreateBoardAsync("board-trust", OnlineLeaderboardScoreUpdatePolicy.Sum); @@ -94,7 +88,7 @@ public async Task ProjectAsync_FromRealSettledMatch_ShouldWriteTrustedScores() foreach (var entry in settled.Data.Result.Entries) { - var boardEntry = await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-trust", entry.PlayerId); + var boardEntry = await harness.LeaderboardStore.FindEntryAsync("board-trust", entry.PlayerId); Assert.NotNull(boardEntry); Assert.Equal(entry.Score, boardEntry.Score); Assert.Equal(OnlineLeaderboardScoreSource.MatchResult, boardEntry.SourceKind); @@ -126,7 +120,7 @@ public async Task ProjectAsync_ForgedMatchOrResultId_ShouldBeRejected() Assert.False(tampered.IsSuccess); Assert.Equal(OnlineErrorCode.RiskControlRejected, tampered.Code); - Assert.Null(await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-trust", PlayerOne)); + Assert.Null(await harness.LeaderboardStore.FindEntryAsync("board-trust", PlayerOne)); Assert.Empty(harness.Recorder.Filter(OnlineLeaderboardEvents.ScoreUpdated)); // 目标榜单不存在同样拒绝。 @@ -160,9 +154,9 @@ public async Task ProjectAsync_RedeliveredThrice_ShouldCountOnce() Assert.Equal(0, third.Data.AppliedCount); Assert.Equal(2, third.Data.ReplayCount); - Assert.Equal(10, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-idem", PlayerOne)).Score); - Assert.Equal(20, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-idem", PlayerTwo)).Score); - Assert.Equal(1, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-idem", PlayerOne)).SubmissionCount); + Assert.Equal(10, (await harness.LeaderboardStore.FindEntryAsync("board-idem", PlayerOne)).Score); + Assert.Equal(20, (await harness.LeaderboardStore.FindEntryAsync("board-idem", PlayerTwo)).Score); + Assert.Equal(1, (await harness.LeaderboardStore.FindEntryAsync("board-idem", PlayerOne)).SubmissionCount); Assert.Equal(2, harness.Recorder.Filter(OnlineLeaderboardEvents.ScoreUpdated).Count); } @@ -184,8 +178,8 @@ public async Task ProjectAsync_AbnormalScore_ShouldRejectPlayerOnly() Assert.Equal(PlayerTwo, projected.Data.FailedPlayers[0].PlayerId); Assert.Equal(OnlineErrorCode.RiskControlRejected, projected.Data.FailedPlayers[0].Code); - Assert.Equal(50, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-abuse", PlayerOne)).Score); - Assert.Null(await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-abuse", PlayerTwo)); + Assert.Equal(50, (await harness.LeaderboardStore.FindEntryAsync("board-abuse", PlayerOne)).Score); + Assert.Null(await harness.LeaderboardStore.FindEntryAsync("board-abuse", PlayerTwo)); Assert.Single(harness.Recorder.Filter(OnlineLeaderboardEvents.ScoreUpdated)); } @@ -214,33 +208,34 @@ public async Task ProjectAsync_HighFrequency_ShouldRateLimitThenRecover() Assert.Equal(0, third.Data.AppliedCount); Assert.Single(third.Data.FailedPlayers); Assert.Equal(OnlineErrorCode.RateLimitExceeded, third.Data.FailedPlayers[0].Code); - Assert.Equal(3, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-rate", PlayerOne)).Score); + Assert.Equal(3, (await harness.LeaderboardStore.FindEntryAsync("board-rate", PlayerOne)).Score); // 窗口滚动后恢复正常(限流是速率保护不是配额)。 var fourth = await harness.Projector.ProjectAsync(harness.Scope(), "board-rate", "match-r4", "mrs-r4", Now + 2000); Assert.True(fourth.IsSuccess, fourth.Message); Assert.Equal(1, fourth.Data.AppliedCount); - Assert.Equal(7, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-rate", PlayerOne)).Score); + Assert.Equal(7, (await harness.LeaderboardStore.FindEntryAsync("board-rate", PlayerOne)).Score); } /// - /// 验证投影半边:跨 App 作用域无法把结果投影到他 App 榜单(与不存在同构拒绝)。 + /// 验证投影半边:榜单是全局域数据(单键化 D4)——跨区服作用域创建的榜对投影器可见, + /// 可信结果可投影上去并发 ScoreUpdated 事实。 /// [Fact] - public async Task ProjectAsync_CrossAppBoard_ShouldBeResourceNotFound() + public async Task ProjectAsync_CrossServerCreatedBoard_ShouldProjectGlobally() { var harness = new Harness(); await harness.CommitResultAsync("match-x", "mrs-x", (PlayerOne, 100)); - var boardInOtherApp = await harness.Service.CreateAsync(harness.Scope(OtherAppId), new OnlineLeaderboardCreateRequest { LeaderboardId = "board-other-app" }, Now); - Assert.True(boardInOtherApp.IsSuccess, boardInOtherApp.Message); + var boardInOtherServer = await harness.Service.CreateAsync(harness.Scope(OtherServerId), new OnlineLeaderboardCreateRequest { LeaderboardId = "board-other-server" }, Now); + Assert.True(boardInOtherServer.IsSuccess, boardInOtherServer.Message); - var projected = await harness.Projector.ProjectAsync(harness.Scope(), "board-other-app", "match-x", "mrs-x", Now + 100); + var projected = await harness.Projector.ProjectAsync(harness.Scope(), "board-other-server", "match-x", "mrs-x", Now + 100); - Assert.False(projected.IsSuccess); - Assert.Equal(OnlineErrorCode.ResourceNotFound, projected.Code); - Assert.Empty(harness.Recorder.Filter(OnlineLeaderboardEvents.ScoreUpdated)); + Assert.True(projected.IsSuccess, projected.Message); + Assert.Single(harness.Recorder.Filter(OnlineLeaderboardEvents.ScoreUpdated)); + Assert.Equal(100, (await harness.LeaderboardStore.FindEntryAsync("board-other-server", PlayerOne)).Score); } /// @@ -259,7 +254,7 @@ public async Task ProjectAsync_BestPolicy_ShouldKeepBestAcrossResults() await harness.Projector.ProjectAsync(harness.Scope(), "board-best", "match-b2", "mrs-b2", Now + 200); await harness.Projector.ProjectAsync(harness.Scope(), "board-best", "match-b3", "mrs-b3", Now + 300); - var entry = await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, "board-best", PlayerOne); + var entry = await harness.LeaderboardStore.FindEntryAsync("board-best", PlayerOne); Assert.Equal(150, entry.Score); Assert.Equal(3, entry.SubmissionCount); @@ -363,12 +358,12 @@ public OnlineMatchSettlementService Settlement /// /// 构造作用域。 /// - /// App 标识(默认本 App)。 + /// 区服标识(默认本区服)。 /// 玩家位(默认无主体)。 /// 作用域。 - public OnlineScope Scope(long appId = AppId, long playerId = 0) + public OnlineScope Scope(long serverId = ServerId, long playerId = 0) { - return new OnlineScope(TenantId, appId, ServerId, playerId); + return new OnlineScope(serverId, playerId); } /// @@ -402,8 +397,6 @@ public async Task CommitResultAsync(string matchId, string matchResultId, params { MatchResultId = matchResultId, MatchId = matchId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Mode = OnlineRockPaperScissorsGame.MatchMode, Region = 1, @@ -434,18 +427,16 @@ public async Task PlayToSettlingAsync() Region = 1, CreatedAtTime = Now, TicketIds = new List(), - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, }; var created = await runtime.CreateFromAssignmentAsync(assignment, Now); Assert.True(created.IsSuccess, created.Message); - var actor = await runtime.ResolveActorAsync(TenantId, AppId, MatchId); + var actor = await runtime.ResolveActorAsync(MatchId); Assert.NotNull(actor); - await actor.SetReadyAsync(new OnlineScope(TenantId, AppId, ServerId, PlayerOne), true, Now); - await actor.SetReadyAsync(new OnlineScope(TenantId, AppId, ServerId, PlayerTwo), true, Now + 1); - var started = await actor.StartAsync(new OnlineScope(TenantId, AppId, ServerId, PlayerOne), Now + 2); + await actor.SetReadyAsync(new OnlineScope(ServerId, PlayerOne), true, Now); + await actor.SetReadyAsync(new OnlineScope(ServerId, PlayerTwo), true, Now + 1); + var started = await actor.StartAsync(new OnlineScope(ServerId, PlayerOne), Now + 2); Assert.True(started.IsSuccess, started.Message); await SubmitAsync(actor, PlayerOne, 1, OnlineRockPaperScissorsMove.Rock, Now + 10); @@ -474,7 +465,7 @@ private static async Task SubmitAsync(OnlineMatchActor actor, long playerId, int ClientTime = nowUnixMilliseconds, }; - var ack = await actor.SubmitInputAsync(new OnlineScope(TenantId, AppId, ServerId, playerId), input, nowUnixMilliseconds); + var ack = await actor.SubmitInputAsync(new OnlineScope(ServerId, playerId), input, nowUnixMilliseconds); Assert.True(ack.IsSuccess, ack.Message); Assert.True(ack.Data.Accepted, ack.Data.Message); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineLedgerEntryInvariantTests.cs b/Tests/GameFrameX.Tests/Online/OnlineLedgerEntryInvariantTests.cs index 3f5c3a47a..6d815a816 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineLedgerEntryInvariantTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineLedgerEntryInvariantTests.cs @@ -44,7 +44,7 @@ public class OnlineLedgerEntryInvariantTests [Fact] public void ConsistentAmounts_ConstructsSuccessfully() { - var header = new OnlineLedgerHeader { TenantId = 1, AppId = 2, PlayerId = 3, HomeServerId = 4, InitiatingServerId = 5, Source = OnlineAssetChangeSource.SystemCompensation, Operation = OnlineGrantOperation.Grant, Reason = "test", BusinessOrderId = string.Empty, OperatorId = string.Empty, }; + var header = new OnlineLedgerHeader { PlayerId = 3, HomeServerId = 4, InitiatingServerId = 5, Source = OnlineAssetChangeSource.SystemCompensation, Operation = OnlineGrantOperation.Grant, Reason = "test", BusinessOrderId = string.Empty, OperatorId = string.Empty, }; var entry = new OnlineLedgerEntry("led-1", "txn-1", header, OnlineAssetKind.Currency, "gold", 100, -30, 70, string.Empty, 1, 1760000000000); @@ -59,7 +59,7 @@ public void ConsistentAmounts_ConstructsSuccessfully() [Fact] public void InconsistentAmounts_ThrowsArgumentException() { - var header = new OnlineLedgerHeader { TenantId = 1, AppId = 2, PlayerId = 3, HomeServerId = 4, InitiatingServerId = 5, Source = OnlineAssetChangeSource.SystemCompensation, Operation = OnlineGrantOperation.Grant, Reason = "test", BusinessOrderId = string.Empty, OperatorId = string.Empty, }; + var header = new OnlineLedgerHeader { PlayerId = 3, HomeServerId = 4, InitiatingServerId = 5, Source = OnlineAssetChangeSource.SystemCompensation, Operation = OnlineGrantOperation.Grant, Reason = "test", BusinessOrderId = string.Empty, OperatorId = string.Empty, }; Assert.Throws(() => new OnlineLedgerEntry("led-1", "txn-1", header, OnlineAssetKind.Currency, "gold", 100, 30, 200, string.Empty, 1, 1760000000000)); } @@ -70,7 +70,7 @@ public void InconsistentAmounts_ThrowsArgumentException() [Fact] public void OverflowingAmounts_ThrowsArgumentException() { - var header = new OnlineLedgerHeader { TenantId = 1, AppId = 2, PlayerId = 3, HomeServerId = 4, InitiatingServerId = 5, Source = OnlineAssetChangeSource.SystemCompensation, Operation = OnlineGrantOperation.Grant, Reason = "test", BusinessOrderId = string.Empty, OperatorId = string.Empty, }; + var header = new OnlineLedgerHeader { PlayerId = 3, HomeServerId = 4, InitiatingServerId = 5, Source = OnlineAssetChangeSource.SystemCompensation, Operation = OnlineGrantOperation.Grant, Reason = "test", BusinessOrderId = string.Empty, OperatorId = string.Empty, }; // 回绕值 long.MinValue 不得被误判为一致。 Assert.Throws(() => new OnlineLedgerEntry("led-1", "txn-1", header, OnlineAssetKind.Currency, "gold", long.MaxValue, 1, long.MinValue, string.Empty, 1, 1760000000000)); diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchCapabilityLifecycleTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchCapabilityLifecycleTests.cs index dbe73f086..d4ad9b600 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchCapabilityLifecycleTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchCapabilityLifecycleTests.cs @@ -241,7 +241,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => PublishAssignmentCreated(runtime, firstAssignment); runtime.Host.EventBus.Publish( OnlineMatchEvents.AssignmentCreated, - OnlineMatchEvents.CreateAssignmentCreated(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId, "asg-does-not-exist", "match-does-not-exist", 1, 1, 2, PlayerOne, new List())); + OnlineMatchEvents.CreateAssignmentCreated(OnlineCapabilityTestHarness.ServerId, "asg-does-not-exist", "match-does-not-exist", 1, 1, 2, PlayerOne, new List())); PublishAssignmentCreated(runtime, secondAssignment); Assert.Equal(0, domain.RegistrationCount); @@ -284,7 +284,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => /// 玩家作用域。 private static OnlineScope PlayerScope(long playerId) { - return new OnlineScope(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId, playerId); + return new OnlineScope(OnlineCapabilityTestHarness.ServerId, playerId); } /// @@ -334,7 +334,7 @@ private static async Task CommitAssignmentAsync(Capabilit { var enqueue = await domain.EnqueueAsync(PlayerScope(playerId), 1, 1000); Assert.True(enqueue.IsSuccess, enqueue.Message); - var ticket = await store.FindLatestByPlayerAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, playerId); + var ticket = await store.FindLatestByPlayerAsync(playerId); Assert.NotNull(ticket); ticketIds.Add(ticket.TicketId); } @@ -348,8 +348,6 @@ private static async Task CommitAssignmentAsync(Capabilit Region = 1, CreatedAtTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), TicketIds = ticketIds, - TenantId = OnlineCapabilityTestHarness.TenantId, - AppId = OnlineCapabilityTestHarness.AppId, ServerId = OnlineCapabilityTestHarness.ServerId, }; var committed = await store.CommitMatchAsync(assignment, ticketIds, OnlineMatchTicketState.Queued); @@ -366,6 +364,6 @@ private static void PublishAssignmentCreated(CapabilityRuntime runtime, OnlineMa { runtime.Host.EventBus.Publish( OnlineMatchEvents.AssignmentCreated, - OnlineMatchEvents.CreateAssignmentCreated(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId, assignment.AssignmentId, assignment.MatchId, assignment.Mode, assignment.Region, assignment.PlayerIds.Count, assignment.PlayerIds[0], assignment.TicketIds)); + OnlineMatchEvents.CreateAssignmentCreated(OnlineCapabilityTestHarness.ServerId, assignment.AssignmentId, assignment.MatchId, assignment.Mode, assignment.Region, assignment.PlayerIds.Count, assignment.PlayerIds[0], assignment.TicketIds)); } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchDomainBridgeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchDomainBridgeTests.cs index a34407ac3..d653c65fe 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchDomainBridgeTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchDomainBridgeTests.cs @@ -73,7 +73,7 @@ public class OnlineMatchDomainBridgeTests /// 玩家作用域。 private static OnlineScope PlayerScope(long playerId) { - return new OnlineScope(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId, playerId); + return new OnlineScope(OnlineCapabilityTestHarness.ServerId, playerId); } /// @@ -113,7 +113,7 @@ private static async Task EnqueueQueuedPlayerAsync(IOnlineMatchDomain domain, Ca Assert.Equal(0, status.Data.MatchId); var store = runtime.Host.Services.GetService(); - var ticket = await store.FindLatestByPlayerAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, playerId); + var ticket = await store.FindLatestByPlayerAsync(playerId); Assert.NotNull(ticket); Assert.Equal(OnlineMatchTicketState.Queued, ticket.State); Assert.True(string.IsNullOrEmpty(ticket.AssignmentId)); @@ -236,7 +236,7 @@ await WithStartedMatchDomainAsync(async (domain, runtime) => foreach (var playerId in playerIds) { await EnqueueQueuedPlayerAsync(domain, runtime, playerId, 1, 1000); - Assert.Empty(await store.ListAssignmentsAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId)); + Assert.Empty(await store.ListAssignmentsAsync()); } foreach (var playerId in playerIds) @@ -246,13 +246,13 @@ await WithStartedMatchDomainAsync(async (domain, runtime) => Assert.True(status.Data.Queuing); Assert.False(status.Data.Matched); Assert.Equal(0, status.Data.MatchId); - var ticket = await store.FindLatestByPlayerAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, playerId); + var ticket = await store.FindLatestByPlayerAsync(playerId); Assert.Equal(OnlineMatchTicketState.Queued, ticket.State); } await runtime.Host.Scheduler.TickAsync(); - var assignments = await store.ListAssignmentsAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId); + var assignments = await store.ListAssignmentsAsync(); Assert.Equal(2, assignments.Count); Assert.All(assignments, assignment => Assert.Equal(2, assignment.PlayerIds.Count)); var assignedPlayerIds = assignments.SelectMany(assignment => assignment.PlayerIds).ToArray(); @@ -293,13 +293,13 @@ await WithStartedMatchDomainAsync(async (domain, runtime) => var cancelled = await domain.CancelAsync(PlayerScope(PlayerOne)); Assert.True(cancelled.IsSuccess, cancelled.Message); Assert.True(cancelled.Data.Cancelled); - Assert.Empty(await store.ListAssignmentsAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId)); + Assert.Empty(await store.ListAssignmentsAsync()); await runtime.Host.Scheduler.TickAsync(); - var assignment = Assert.Single(await store.ListAssignmentsAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId)); + var assignment = Assert.Single(await store.ListAssignmentsAsync()); Assert.Equal(new[] { PlayerTwo, PlayerThree }, assignment.PlayerIds.OrderBy(playerId => playerId).ToArray()); - var cancelledTicket = await store.FindLatestByPlayerAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, PlayerOne); + var cancelledTicket = await store.FindLatestByPlayerAsync(PlayerOne); Assert.Equal(OnlineMatchTicketState.Cancelled, cancelledTicket.State); Assert.True(string.IsNullOrEmpty(cancelledTicket.AssignmentId)); var cancelledStatus = await domain.GetStatusAsync(PlayerScope(PlayerOne)); @@ -352,7 +352,7 @@ await WithStartedMatchDomainAsync(async (domain, runtime) => await runtime.Host.Scheduler.TickAsync(); var store = runtime.Host.Services.GetService(); - Assert.Empty(await store.ListAssignmentsAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId)); + Assert.Empty(await store.ListAssignmentsAsync()); foreach (var playerId in new[] { PlayerOne, PlayerTwo, PlayerThree }) { var status = await domain.GetStatusAsync(PlayerScope(playerId)); @@ -429,7 +429,7 @@ await WithStartedMatchDomainAsync(async (domain, runtime) => await domain.EnqueueAsync(PlayerScope(PlayerOne), 1, 1000); var later = DateTimeOffset.UtcNow.AddSeconds(400).ToUnixTimeMilliseconds(); - await coordinator.RunOnceAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, later); + await coordinator.RunOnceAsync(later); var status = await domain.GetStatusAsync(PlayerScope(PlayerOne)); Assert.False(status.Data.Queuing); @@ -521,17 +521,17 @@ await WithStartedMatchDomainAsync(async (domain, runtime) => var store = runtime.Host.Services.GetService(); var matchId = await EnqueuePairAndMatchAsync(domain, runtime); - var ticket = await store.FindLatestByPlayerAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, PlayerOne); + var ticket = await store.FindLatestByPlayerAsync(PlayerOne); Assert.NotNull(ticket); Assert.False(string.IsNullOrEmpty(ticket.AssignmentId)); - var resolved = await domain.ResolveAssignmentAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, ticket.AssignmentId); + var resolved = await domain.ResolveAssignmentAsync(ticket.AssignmentId); Assert.True(resolved.IsSuccess, resolved.Message); Assert.Equal(matchId, resolved.Data.MatchId); Assert.Contains(PlayerOne, resolved.Data.PlayerIds); Assert.Contains(PlayerTwo, resolved.Data.PlayerIds); - var again = await domain.ResolveAssignmentAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, ticket.AssignmentId); + var again = await domain.ResolveAssignmentAsync(ticket.AssignmentId); Assert.Equal(resolved.Data.MatchId, again.Data.MatchId); }); } @@ -548,7 +548,7 @@ await WithStartedMatchDomainAsync(async (domain, runtime) => await EnqueuePairAndMatchAsync(domain, runtime); - var ticket = await store.FindLatestByPlayerAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, PlayerTwo); + var ticket = await store.FindLatestByPlayerAsync(PlayerTwo); Assert.NotNull(ticket); Assert.Equal(OnlineMatchTicketState.Matched, ticket.State); }); @@ -617,7 +617,7 @@ public async Task Enqueue_WithoutPlayerPosition_Rejected() { await WithStartedMatchDomainAsync(async (domain, runtime) => { - var scope = new OnlineScope(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId); + var scope = new OnlineScope(OnlineCapabilityTestHarness.ServerId); var rejected = await domain.EnqueueAsync(scope, 1, 1000); Assert.False(rejected.IsSuccess); Assert.Equal(OnlineErrorCode.ParameterInvalid, rejected.Code); diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchDomainRegistrationSweepTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchDomainRegistrationSweepTests.cs index 8907536b1..cd8e28f19 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchDomainRegistrationSweepTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchDomainRegistrationSweepTests.cs @@ -18,12 +18,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchDomainRegistrationSweepTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; - /// 区服标识。 private const long ServerId = 100; @@ -43,14 +37,12 @@ public async Task ExpiredRegistration_ShouldBeSweptAndOldNumericMatchIdRejected( var enqueued = await harness.Domain.EnqueueAsync(harness.ScopeOf(PlayerOne), 1, 1000); Assert.True(enqueued.IsSuccess, enqueued.Message); Assert.Equal(0, enqueued.Data.MatchId); - var activeTicket = await harness.TicketStore.FindActiveByPlayerAsync(TenantId, AppId, PlayerOne, CancellationToken.None); + var activeTicket = await harness.TicketStore.FindActiveByPlayerAsync(PlayerOne, CancellationToken.None); Assert.NotNull(activeTicket); // 手工落档陈年分配(CreatedAtTime = 3 小时前,超过默认 7200 秒生命周期;InMemory 落档保留传入值)。 var staleAssignment = new OnlineMatchAssignment { - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, AssignmentId = "as-stale-assignment-1", MatchId = "matched-s100-m-stale-1", @@ -90,7 +82,7 @@ public async Task UnexpiredRegistration_ShouldSurviveSweepsAndKeepNumericMatchId Assert.True(second.IsSuccess, second.Message); // 定时批次撮合(GFX-1104):入队只建票,撮合由协调器批量驱动;数值对局标识经状态解析惰性登记。 - var matched = await harness.Coordinator.RunOnceAsync(TenantId, AppId); + var matched = await harness.Coordinator.RunOnceAsync(); Assert.True(matched.IsSuccess, matched.Message); var statusOne = await harness.Domain.GetStatusAsync(harness.ScopeOf(PlayerOne)); Assert.True(statusOne.IsSuccess, statusOne.Message); @@ -164,7 +156,7 @@ public Harness(OnlineMatchRegistryOptions registryOptions) public OnlineScope ScopeOf(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchDomainResumeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchDomainResumeTests.cs index e44b2c659..85148eca6 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchDomainResumeTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchDomainResumeTests.cs @@ -16,12 +16,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchDomainResumeTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; - /// 区服标识。 private const long ServerId = 100; @@ -176,7 +170,7 @@ public Harness(OnlineMatchRuntimeOptions options) public OnlineScope ScopeOf(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } public OnlineMatchMember FindMember(long playerId) @@ -209,13 +203,13 @@ public static async Task StartedAsync() Assert.True(queuedStatus.Data.Queuing); Assert.False(queuedStatus.Data.Matched); Assert.Equal(0, queuedStatus.Data.MatchId); - var ticket = await harness.TicketStore.FindLatestByPlayerAsync(TenantId, AppId, playerId); + var ticket = await harness.TicketStore.FindLatestByPlayerAsync(playerId); Assert.NotNull(ticket); Assert.Equal(OnlineMatchTicketState.Queued, ticket.State); Assert.True(string.IsNullOrEmpty(ticket.AssignmentId)); } - var matched = await harness.Coordinator.RunOnceAsync(TenantId, AppId); + var matched = await harness.Coordinator.RunOnceAsync(); Assert.True(matched.IsSuccess, matched.Message); Assert.Single(matched.Data.AssignmentIds); @@ -238,7 +232,7 @@ public static async Task StartedAsync() Assert.True(entered.IsSuccess, entered.Message); } - harness.Actor = await harness.Runtime.ResolveActorAsync(TenantId, AppId, DeriveRuntimeMatchId(harness.NumericMatchId)); + harness.Actor = await harness.Runtime.ResolveActorAsync(DeriveRuntimeMatchId(harness.NumericMatchId)); Assert.NotNull(harness.Actor); return harness; } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchGameBridgeServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchGameBridgeServiceTests.cs index 7544327fc..98ac9560c 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchGameBridgeServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchGameBridgeServiceTests.cs @@ -35,12 +35,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchGameBridgeServiceTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; - /// 区服标识。 private const long ServerId = 100; @@ -324,7 +318,7 @@ public async Task PlayToCompletionAsync() Assert.True((await Bridge.SubmitGestureAsync(ScopeOf(PlayerOne), RoomId, 1, (int)OnlineRockPaperScissorsMove.Paper)).IsSuccess); Assert.True((await Bridge.SubmitGestureAsync(ScopeOf(PlayerTwo), RoomId, 1, (int)OnlineRockPaperScissorsMove.Rock)).IsSuccess); - var settled = await Settlement.SettleAsync(TenantId, AppId, "rps-s100-r5001-g1", 2000000L); + var settled = await Settlement.SettleAsync("rps-s100-r5001-g1", 2000000L); Assert.True(settled.IsSuccess, settled.Message); } @@ -335,7 +329,7 @@ public async Task PlayToCompletionAsync() /// 作用域。 public OnlineScope ScopeOf(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchListingServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchListingServiceTests.cs index b481e0709..af1658767 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchListingServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchListingServiceTests.cs @@ -42,12 +42,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchListingServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -172,8 +166,6 @@ public async Task JoinAsync_WithUnknownPolicy_ShouldBeRejected() var listing = new OnlineMatchListing { ListingId = "lst-unknown", - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, OwnerPlayerId = PlayerOne, Name = "unknown-room", @@ -278,7 +270,7 @@ public async Task UpdateIfRowVersionAsync_WithMatchingVersion_ShouldWriteAndForc // Assert Assert.True(outcome); - var stored = await store.FindAsync(TenantId, AppId, listing.ListingId); + var stored = await store.FindAsync(listing.ListingId); Assert.Equal(2, stored.JoinedCount); Assert.Equal(1, stored.RowVersion); } @@ -303,7 +295,7 @@ public async Task UpdateIfRowVersionAsync_WithStaleVersion_ShouldRejectAndKeepSt // Assert Assert.False(outcome); - var stored = await store.FindAsync(TenantId, AppId, listing.ListingId); + var stored = await store.FindAsync(listing.ListingId); Assert.Equal(1, stored.JoinedCount); Assert.Equal(1, stored.RowVersion); } @@ -319,15 +311,13 @@ public async Task UpdateIfRowVersionAsync_WithMissingListing_ShouldReturnFalse() var ghost = new OnlineMatchListing { ListingId = "lst-missing", - TenantId = TenantId, - AppId = AppId, Capacity = 4, State = OnlineMatchListingState.Open, }; // Act + Assert Assert.False(await store.UpdateIfRowVersionAsync(ghost, expectedRowVersion: 0)); - Assert.Null(await store.FindAsync(TenantId, AppId, "lst-missing")); + Assert.Null(await store.FindAsync("lst-missing")); } /// @@ -364,7 +354,7 @@ public async Task JoinAsync_ConcurrentJoinOnCapacityOne_ShouldAllowExactlyOneWin } Assert.Equal(1, winners); - var stored = await innerStore.FindAsync(TenantId, AppId, listing.ListingId); + var stored = await innerStore.FindAsync(listing.ListingId); Assert.Equal(1, stored.JoinedCount); Assert.Equal(OnlineMatchListingState.Full, stored.State); Assert.Equal(1, stored.RowVersion); @@ -391,7 +381,7 @@ public async Task JoinAsync_RacingWithClose_FinalStateShouldStayClosed() // Assert Assert.True(raceOutcomes[1].IsSuccess); - var stored = await innerStore.FindAsync(TenantId, AppId, listing.ListingId); + var stored = await innerStore.FindAsync(listing.ListingId); Assert.Equal(OnlineMatchListingState.Closed, stored.State); } @@ -433,7 +423,7 @@ public async Task JoinAsync_WhenConditionalWriteAlwaysConflicts_ShouldReturnVers Assert.False(outcome.IsSuccess); Assert.Equal(OnlineErrorCode.VersionConflict, outcome.Code); Assert.Equal(3, conflictStore.ConditionalWriteAttempts); - var stored = await conflictStore.FindAsync(TenantId, AppId, listing.ListingId); + var stored = await conflictStore.FindAsync(listing.ListingId); Assert.Equal(0, stored.JoinedCount); } @@ -501,7 +491,7 @@ private static OnlineMatchListingJoinRequest CreateJoinRequest(long playerId, Li /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// @@ -543,15 +533,15 @@ public async Task UpdateIfRowVersionAsync(OnlineMatchListing listing, long } /// 按标识查找列表项(直接转发)。 - public Task FindAsync(long tenantId, long appId, string listingId, CancellationToken cancellationToken = default) + public Task FindAsync(string listingId, CancellationToken cancellationToken = default) { - return _innerStore.FindAsync(tenantId, appId, listingId, cancellationToken); + return _innerStore.FindAsync(listingId, cancellationToken); } /// 列出作用域内全部列表项(直接转发)。 - public Task> ListAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAsync(CancellationToken cancellationToken = default) { - return _innerStore.ListAsync(tenantId, appId, cancellationToken); + return _innerStore.ListAsync(cancellationToken); } /// @@ -605,15 +595,15 @@ public Task UpdateIfRowVersionAsync(OnlineMatchListing listing, long expec } /// 按标识查找列表项(直接转发)。 - public Task FindAsync(long tenantId, long appId, string listingId, CancellationToken cancellationToken = default) + public Task FindAsync(string listingId, CancellationToken cancellationToken = default) { - return _innerStore.FindAsync(tenantId, appId, listingId, cancellationToken); + return _innerStore.FindAsync(listingId, cancellationToken); } /// 列出作用域内全部列表项(直接转发)。 - public Task> ListAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAsync(CancellationToken cancellationToken = default) { - return _innerStore.ListAsync(tenantId, appId, cancellationToken); + return _innerStore.ListAsync(cancellationToken); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchQueueObserverTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchQueueObserverTests.cs index 0d3d7de6b..46a4d22ce 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchQueueObserverTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchQueueObserverTests.cs @@ -41,12 +41,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchQueueObserverTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -71,10 +65,10 @@ public async Task ObserveAsync_ShouldReportCountsByState() await EnqueueAsync(fixture.Tickets, PlayerTwo); var cancelled = await EnqueueAsync(fixture.Tickets, PlayerThree); await fixture.Tickets.CancelAsync(CreatePlayerScope(PlayerThree), cancelled.TicketId); - await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + await fixture.Coordinator.RunOnceAsync(); // Act - var outcome = await fixture.Observer.ObserveAsync(TenantId, AppId); + var outcome = await fixture.Observer.ObserveAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -98,10 +92,10 @@ public async Task ObserveAsync_ShouldReportZeroDuplicateAssignmentTickets() var fixture = CreateFixture(); await EnqueueAsync(fixture.Tickets, PlayerOne); await EnqueueAsync(fixture.Tickets, PlayerTwo); - await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + await fixture.Coordinator.RunOnceAsync(); // Act - var outcome = await fixture.Observer.ObserveAsync(TenantId, AppId); + var outcome = await fixture.Observer.ObserveAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -120,7 +114,7 @@ public async Task ObserveAsync_WithQueuedTickets_ShouldReportQueuedPlayers() await EnqueueAsync(fixture.Tickets, PlayerTwo); // Act - var outcome = await fixture.Observer.ObserveAsync(TenantId, AppId); + var outcome = await fixture.Observer.ObserveAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -141,7 +135,7 @@ public async Task ObserveAsync_OnEmptyScope_ShouldReportZeros() var fixture = CreateFixture(); // Act - var outcome = await fixture.Observer.ObserveAsync(TenantId, AppId); + var outcome = await fixture.Observer.ObserveAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -196,7 +190,7 @@ private static async Task EnqueueAsync(OnlineMatchTicketServi /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchRuntimeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchRuntimeTests.cs index 3149567c5..7a2345551 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchRuntimeTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchRuntimeTests.cs @@ -46,12 +46,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchRuntimeTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; - /// 区服标识。 private const long ServerId = 100; @@ -154,19 +148,19 @@ public async Task TickAsync_StageTimeout_ShouldReachTimeoutThenReleaseActor() Assert.Equal(OnlineMatchState.Closed, harness.Actor.State); Assert.Equal(0, harness.Runtime.ActiveActorCount); Assert.Equal(1, harness.Runtime.ReleasedActorCount); - Assert.Null(await harness.Store.FindAsync(TenantId, AppId, MatchId)); + Assert.Null(await harness.Store.FindAsync(MatchId)); } /// - /// 验证跨租户作用域不得读写他人对局。 + /// 验证跨区服作用域不得读写他人对局。 /// [Fact] - public async Task CrossTenantScope_ShouldBeDenied() + public async Task CrossServerScope_ShouldBeDenied() { var harness = new Harness(); await harness.CreateAsync(); - var foreign = new OnlineScope(TenantId + 1, AppId, ServerId, PlayerOne); + var foreign = new OnlineScope(ServerId + 1, PlayerOne); var result = await harness.Actor.SetReadyAsync(foreign, true, Now); Assert.False(result.IsSuccess); @@ -236,8 +230,8 @@ public async Task ResolveActorAsync_ConcurrentMiss_ShouldConvergeToSingleActor() var runtime = new OnlineMatchRuntime(store, new OnlineEventRecorder(), new OnlineMatchRuntimeOptions()); runtime.RegisterGame(new OnlineRockPaperScissorsGame()); - var first = Task.Run(() => runtime.ResolveActorAsync(TenantId, AppId, MatchId)); - var second = Task.Run(() => runtime.ResolveActorAsync(TenantId, AppId, MatchId)); + var first = Task.Run(() => runtime.ResolveActorAsync(MatchId)); + var second = Task.Run(() => runtime.ResolveActorAsync(MatchId)); var actors = await Task.WhenAll(first, second); Assert.NotNull(actors[0]); @@ -260,14 +254,14 @@ public async Task CreateFromAssignmentAsync_ConcurrentResolve_ShouldReuseRegiste var createTask = Task.Run(() => runtime.CreateFromAssignmentAsync(BuildAssignment(PlayerOne, PlayerTwo), Now)); await store.CreatePersisted.Task.WaitAsync(OrchestrationTimeout); - var resolverActor = await runtime.ResolveActorAsync(TenantId, AppId, MatchId); + var resolverActor = await runtime.ResolveActorAsync(MatchId); Assert.NotNull(resolverActor); store.ResolverRegistered.TrySetResult(); var created = await createTask; Assert.True(created.IsSuccess, created.Message); - var afterCreate = await runtime.ResolveActorAsync(TenantId, AppId, MatchId); + var afterCreate = await runtime.ResolveActorAsync(MatchId); Assert.Same(resolverActor, afterCreate); Assert.Equal(1, runtime.ActiveActorCount); } @@ -290,7 +284,7 @@ public async Task ResolveActorAsync_ParallelStress_ShouldHoldSingleInstanceInvar var resolves = new Task[8]; for (var index = 0; index < resolves.Length; index++) { - resolves[index] = Task.Run(() => runtime.ResolveActorAsync(TenantId, AppId, MatchId)); + resolves[index] = Task.Run(() => runtime.ResolveActorAsync(MatchId)); } var actors = await Task.WhenAll(resolves); @@ -320,8 +314,6 @@ private static OnlineMatchAssignment BuildAssignment(params long[] playerIds) Region = 1, CreatedAtTime = Now, TicketIds = new List(), - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, }; } @@ -383,7 +375,7 @@ public async Task CreateAsync() { var created = await Runtime.CreateFromAssignmentAsync(BuildAssignment(PlayerOne, PlayerTwo), Now); Assert.True(created.IsSuccess, created.Message); - Actor = await Runtime.ResolveActorAsync(TenantId, AppId, MatchId); + Actor = await Runtime.ResolveActorAsync(MatchId); Assert.NotNull(Actor); } @@ -430,7 +422,7 @@ public async Task SubmitAsync(long playerId, int clientSequ /// 作用域。 public OnlineScope ScopeOf(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } @@ -442,8 +434,6 @@ private static OnlineMatch BuildSeededMatch() { return new OnlineMatch { - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, MatchId = MatchId, Mode = OnlineRockPaperScissorsGame.MatchMode, @@ -479,9 +469,9 @@ private sealed class OrchestratedMatchActorStore : IOnlineMatchActorStore private int _findArrivalCount; /// 并发计数委托内存实现。 - public Task> CountActiveByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public Task> CountActiveByScopeAsync(long serverId, CancellationToken cancellationToken = default) { - return _inner.CountActiveByScopeAsync(tenantId, appId, serverId, cancellationToken); + return _inner.CountActiveByScopeAsync(serverId, cancellationToken); } /// @@ -538,12 +528,10 @@ public async Task CreateAsync(OnlineMatch match, CancellationToken /// /// 对齐模式下前两次查找彼此等待后同时返回,确保两方都越过缓存 miss 各自构造后并发注册。 /// - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 取消令牌。 /// 对局副本;不存在返回 null。 - public async Task FindAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default) + public async Task FindAsync(string matchId, CancellationToken cancellationToken = default) { if (_alignConcurrentFinds) { @@ -560,7 +548,7 @@ public async Task FindAsync(long tenantId, long appId, string match } } - return await _inner.FindAsync(tenantId, appId, matchId, cancellationToken).ConfigureAwait(false); + return await _inner.FindAsync(matchId, cancellationToken).ConfigureAwait(false); } /// 委托内存实现。 @@ -573,24 +561,20 @@ public Task UpdateAsync(OnlineMatch match, CancellationToken cancel } /// 委托内存实现。 - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 取消令牌。 /// 删除结果。 - public Task DeleteAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default) + public Task DeleteAsync(string matchId, CancellationToken cancellationToken = default) { - return _inner.DeleteAsync(tenantId, appId, matchId, cancellationToken); + return _inner.DeleteAsync(matchId, cancellationToken); } /// 委托内存实现。 - /// 租户标识。 - /// App 标识。 /// 取消令牌。 /// 对局副本列表。 - public Task> ListAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListAsync(CancellationToken cancellationToken = default) { - return _inner.ListAsync(tenantId, appId, cancellationToken); + return _inner.ListAsync(cancellationToken); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs index b87b68b14..06d3e2ad8 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs @@ -54,11 +54,6 @@ namespace GameFrameX.Tests.Online [Collection(CapabilityRuntimeCollection.Name)] public class OnlineMatchSettledLeaderboardProjectorTests { - /// 租户标识(直接构造基座用)。 - private const long TenantId = 1; - - /// App 标识(直接构造基座用)。 - private const long AppId = 10; /// 区服标识(直接构造基座用)。 private const long ServerId = 100; @@ -98,7 +93,7 @@ public async Task HandleEventAsync_SettledEvent_ShouldProjectAndDeduplicateByEve Assert.Equal(30, await harness.ScoreOfAsync(PlayerOne)); Assert.Equal(10, await harness.ScoreOfAsync(PlayerTwo)); - Assert.Equal(1, (await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, BoardId, PlayerOne)).SubmissionCount); + Assert.Equal(1, (await harness.LeaderboardStore.FindEntryAsync(BoardId, PlayerOne)).SubmissionCount); Assert.Empty(harness.Projector.QueryStatus()); } @@ -115,7 +110,7 @@ public async Task HandleEventAsync_DifferentEventIdSameMatchResult_ShouldReplayW await harness.Projector.HandleEventAsync(harness.CreateSettledEvent("mrs-2", "match-2", (PlayerOne, 7))); await harness.Projector.HandleEventAsync(harness.CreateSettledEvent("mrs-2", "match-2", (PlayerOne, 7))); - var entry = await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, BoardId, PlayerOne); + var entry = await harness.LeaderboardStore.FindEntryAsync(BoardId, PlayerOne); Assert.Equal(7, entry.Score); Assert.Equal(1, entry.SubmissionCount); Assert.Empty(harness.Projector.QueryStatus()); @@ -143,7 +138,7 @@ public async Task RetryPendingAsync_BoardCreatedLater_ShouldBackfillWithoutDoubl // 重投后再次手动重投:幂等键回放,不双计。 await harness.Projector.RetryPendingAsync(CancellationToken.None); - var entry = await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, BoardId, PlayerOne); + var entry = await harness.LeaderboardStore.FindEntryAsync(BoardId, PlayerOne); Assert.NotNull(entry); Assert.Equal(50, entry.Score); Assert.Equal(1, entry.SubmissionCount); @@ -166,7 +161,7 @@ public async Task RetryPendingAsync_ResultMissing_ShouldDropPendingEntry() await harness.Projector.RetryPendingAsync(CancellationToken.None); Assert.Empty(harness.Projector.QueryStatus()); - Assert.Null(await harness.LeaderboardStore.FindEntryAsync(TenantId, AppId, BoardId, PlayerOne)); + Assert.Null(await harness.LeaderboardStore.FindEntryAsync(BoardId, PlayerOne)); } /// @@ -200,17 +195,17 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => var projector = services.GetService(); Assert.NotNull(projector); - var hostScope = new OnlineScope(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId); + var hostScope = new OnlineScope(OnlineCapabilityTestHarness.ServerId); var probe = await services.GetService().GetTopAsync(hostScope, new OnlineLeaderboardTopQuery { LeaderboardId = BoardId, Count = 1, }); Assert.True(probe.IsSuccess, probe.Message); - await CommitResultAsync(services.GetService(), OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId, "match-mod", "mrs-mod", (PlayerOne, 42)); - var settledEvent = OnlineMatchRuntimeEvents.CreateMatchSettled(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId, "mrs-mod", "match-mod", OnlineRockPaperScissorsGame.MatchMode, 1, OnlineMatchState.Completed.ToString(), Now, new (long PlayerId, int Rank, bool IsWinner, long Score, int RewardCount)[] { (PlayerOne, 1, true, 42, 0) }); + await CommitResultAsync(services.GetService(), OnlineCapabilityTestHarness.ServerId, "match-mod", "mrs-mod", (PlayerOne, 42)); + var settledEvent = OnlineMatchRuntimeEvents.CreateMatchSettled(OnlineCapabilityTestHarness.ServerId, "mrs-mod", "match-mod", OnlineRockPaperScissorsGame.MatchMode, 1, OnlineMatchState.Completed.ToString(), Now, new (long PlayerId, int Rank, bool IsWinner, long Score, int RewardCount)[] { (PlayerOne, 1, true, 42, 0) }); Assert.Equal("online.match.settled", settledEvent.EventType); await services.GetService().PublishAsync(settledEvent); - var entry = await services.GetService().FindEntryAsync(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, BoardId, PlayerOne); + var entry = await services.GetService().FindEntryAsync(BoardId, PlayerOne); Assert.NotNull(entry); Assert.Equal(42, entry.Score); Assert.Empty(projector.QueryStatus()); @@ -218,17 +213,18 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => } /// - /// 验证模块装配半边二:未配置投影榜 id 或 id 空白 → 不装配投影器、不注册重投 tick job(一轮 tick 比投影形态少执行一个 job),也不报错。 + /// 验证模块装配半边二(C460 默认开):零 Settings(缺省装配)与显式配置投影榜 id 均装配投影器 + 重投 tick job + ///(两者 tick job 数相同);显式配置空白榜单 id(覆盖关闭)→ 不装配投影器(一轮 tick 比投影形态少执行一个 job),不报错。 /// [Fact] - public async Task Compose_WithoutProjectionBoard_SkipsProjectorAndRetryJob() + public async Task Compose_ZeroSettingsDefaultsProjectionOn_BlankOverrideTurnsItOff() { - var withProjection = await RunOneTickRoundAsync(ProjectionSettings, true); - var withoutSettings = await RunOneTickRoundAsync(null, false); + var configured = await RunOneTickRoundAsync(ProjectionSettings, true); + var zeroSettings = await RunOneTickRoundAsync(null, true); var blankBoard = await RunOneTickRoundAsync("{\"online-competition\":{\"LeaderboardProjection\":{\"MatchSettledBoardId\":\" \"}}}", false); - Assert.Equal(withProjection - 1, withoutSettings); - Assert.Equal(withProjection - 1, blankBoard); + Assert.Equal(configured, zeroSettings); + Assert.Equal(configured - 1, blankBoard); } /// @@ -308,14 +304,12 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => /// 直接向结算存储落一份服务端形态的结果(模拟已结算事实)。 /// /// 结算结果存储。 - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 对局标识。 /// 结果标识。 /// 条目(玩家, 分数)序列。 /// 完成通知。 - private static async Task CommitResultAsync(IOnlineMatchResultStore resultStore, long tenantId, long appId, long serverId, string matchId, string matchResultId, params (long PlayerId, long Score)[] entries) + private static async Task CommitResultAsync(IOnlineMatchResultStore resultStore, long serverId, string matchId, string matchResultId, params (long PlayerId, long Score)[] entries) { var resultEntries = new List(); foreach (var item in entries) @@ -327,8 +321,6 @@ private static async Task CommitResultAsync(IOnlineMatchResultStore resultStore, { MatchResultId = matchResultId, MatchId = matchId, - TenantId = tenantId, - AppId = appId, ServerId = serverId, Mode = OnlineRockPaperScissorsGame.MatchMode, Region = 1, @@ -433,7 +425,7 @@ public OnlineMatchSettledLeaderboardProjector Projector /// 完成通知。 public async Task CreateBoardAsync() { - var created = await Service.CreateAsync(new OnlineScope(TenantId, AppId, ServerId), new OnlineLeaderboardCreateRequest { LeaderboardId = BoardId, ScoreUpdatePolicy = OnlineLeaderboardScoreUpdatePolicy.Sum }, Now); + var created = await Service.CreateAsync(new OnlineScope(ServerId), new OnlineLeaderboardCreateRequest { LeaderboardId = BoardId, ScoreUpdatePolicy = OnlineLeaderboardScoreUpdatePolicy.Sum }, Now); Assert.True(created.IsSuccess, created.Message); } @@ -446,7 +438,7 @@ public async Task CreateBoardAsync() /// 完成通知。 public async Task CommitResultAsync(string matchId, string matchResultId, params (long PlayerId, long Score)[] entries) { - await OnlineMatchSettledLeaderboardProjectorTests.CommitResultAsync(ResultStore, TenantId, AppId, ServerId, matchId, matchResultId, entries); + await OnlineMatchSettledLeaderboardProjectorTests.CommitResultAsync(ResultStore, ServerId, matchId, matchResultId, entries); } /// @@ -464,7 +456,7 @@ public OnlineEvent CreateSettledEvent(string matchResultId, string matchId, para payloadEntries.Add((item.PlayerId, payloadEntries.Count + 1, payloadEntries.Count == 0, item.Score, 0)); } - return OnlineMatchRuntimeEvents.CreateMatchSettled(TenantId, AppId, ServerId, matchResultId, matchId, OnlineRockPaperScissorsGame.MatchMode, 1, OnlineMatchState.Completed.ToString(), Now, payloadEntries); + return OnlineMatchRuntimeEvents.CreateMatchSettled(ServerId, matchResultId, matchId, OnlineRockPaperScissorsGame.MatchMode, 1, OnlineMatchState.Completed.ToString(), Now, payloadEntries); } /// @@ -474,7 +466,7 @@ public OnlineEvent CreateSettledEvent(string matchResultId, string matchId, para /// 分数。 public async Task ScoreOfAsync(long playerId) { - var entry = await LeaderboardStore.FindEntryAsync(TenantId, AppId, BoardId, playerId); + var entry = await LeaderboardStore.FindEntryAsync(BoardId, playerId); Assert.NotNull(entry); return entry.Score; } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchSettlementPipelineTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchSettlementPipelineTests.cs index a5053d39e..3f9565650 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchSettlementPipelineTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchSettlementPipelineTests.cs @@ -33,11 +33,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchSettlementPipelineTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; /// 区服标识。 private const long ServerId = 100; @@ -479,7 +474,7 @@ public OnlineMatchActor Actor /// 余额(无账户为 0)。 public async Task BalanceOfAsync(long playerId) { - var wallet = await AssetStore.FindWalletAsync(TenantId, AppId, playerId, OnlineRockPaperScissorsGame.RewardAssetId); + var wallet = await AssetStore.FindWalletAsync(playerId, OnlineRockPaperScissorsGame.RewardAssetId); return wallet == null ? 0L : wallet.Balance; } @@ -501,13 +496,11 @@ public async Task PlayToSettlingAsync(string matchId = MatchId, long playerOne = Region = 1, CreatedAtTime = Now, TicketIds = new List(), - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, }; var created = await Runtime.CreateFromAssignmentAsync(assignment, Now); Assert.True(created.IsSuccess, created.Message); - Actor = await Runtime.ResolveActorAsync(TenantId, AppId, matchId); + Actor = await Runtime.ResolveActorAsync(matchId); Assert.NotNull(Actor); await Actor.SetReadyAsync(ScopeOf(playerOne), true, Now); @@ -556,7 +549,7 @@ private async Task SubmitAsync(string matchId, long playerId, int move, long now /// 作用域。 private static OnlineScope ScopeOf(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } @@ -599,14 +592,12 @@ public string ThrowClaimForMatchId private readonly Dictionary _dueMatchIds = new(); /// 委托给内部存储。 - /// 租户标识。 - /// App 标识。 /// 对局标识。 /// 取消令牌。 /// 结果副本。 - public Task FindByMatchAsync(long tenantId, long appId, string matchId, CancellationToken cancellationToken = default) + public Task FindByMatchAsync(string matchId, CancellationToken cancellationToken = default) { - return _inner.FindByMatchAsync(tenantId, appId, matchId, cancellationToken); + return _inner.FindByMatchAsync(matchId, cancellationToken); } /// 委托给内部存储。 @@ -740,55 +731,47 @@ public int ThrowRemainingCount /// /// 查询钱包账户;原样委托给内部真实存储,不受失败注入影响。 /// - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 货币标识。 /// 取消令牌。 /// 内部存储返回的钱包账户。 - public Task FindWalletAsync(long tenantId, long appId, long playerId, string currencyId, CancellationToken cancellationToken = default) + public Task FindWalletAsync(long playerId, string currencyId, CancellationToken cancellationToken = default) { - return _inner.FindWalletAsync(tenantId, appId, playerId, currencyId, cancellationToken); + return _inner.FindWalletAsync(playerId, currencyId, cancellationToken); } /// /// 查询背包堆叠;原样委托给内部真实存储,不受失败注入影响。 /// - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 物品标识。 /// 取消令牌。 /// 内部存储返回的背包堆叠。 - public Task FindInventoryAsync(long tenantId, long appId, long playerId, string itemId, CancellationToken cancellationToken = default) + public Task FindInventoryAsync(long playerId, string itemId, CancellationToken cancellationToken = default) { - return _inner.FindInventoryAsync(tenantId, appId, playerId, itemId, cancellationToken); + return _inner.FindInventoryAsync(playerId, itemId, cancellationToken); } /// /// 列出玩家全部钱包账户;原样委托给内部真实存储。 /// - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 取消令牌。 /// 内部存储返回的钱包账户集合。 - public Task> ListWalletAccountsAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListWalletAccountsAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListWalletAccountsAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListWalletAccountsAsync(playerId, cancellationToken); } /// /// 列出玩家全部背包堆叠;原样委托给内部真实存储。 /// - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 取消令牌。 /// 内部存储返回的背包堆叠集合。 - public Task> ListInventoryStacksAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> ListInventoryStacksAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.ListInventoryStacksAsync(tenantId, appId, playerId, cancellationToken); + return _inner.ListInventoryStacksAsync(playerId, cancellationToken); } /// @@ -834,26 +817,22 @@ public Task> FindLedgerEntriesByTransactionIdAs /// /// 按资产汇总玩家流水增量;原样委托给内部真实存储。 /// - /// 租户标识。 - /// 应用标识。 /// 玩家标识。 /// 取消令牌。 /// 资产标识到增量合计的映射。 - public Task> SumLedgerDeltasByAssetAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task> SumLedgerDeltasByAssetAsync(long playerId, CancellationToken cancellationToken = default) { - return _inner.SumLedgerDeltasByAssetAsync(tenantId, appId, playerId, cancellationToken); + return _inner.SumLedgerDeltasByAssetAsync(playerId, cancellationToken); } /// /// 列出拥有资产记录的玩家标识;原样委托给内部真实存储。 /// - /// 租户标识。 - /// 应用标识。 /// 取消令牌。 /// 内部存储返回的玩家标识集合。 - public Task> ListPlayerIdsAsync(long tenantId, long appId, CancellationToken cancellationToken = default) + public Task> ListPlayerIdsAsync(CancellationToken cancellationToken = default) { - return _inner.ListPlayerIdsAsync(tenantId, appId, cancellationToken); + return _inner.ListPlayerIdsAsync(cancellationToken); } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchSettlementTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchSettlementTests.cs index 432ecb211..684739b1e 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchSettlementTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchSettlementTests.cs @@ -47,11 +47,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchSettlementTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; /// 区服标识。 private const long ServerId = 100; @@ -77,7 +72,7 @@ public async Task SettleAndDispatch_ShouldProduceSingleResultAndGrantOnce() var harness = new Harness(); await harness.PlayToSettlingAsync(); - var settled = await harness.Settlement.SettleAsync(TenantId, AppId, MatchId, Now + 100); + var settled = await harness.Settlement.SettleAsync(MatchId, Now + 100); Assert.True(settled.IsSuccess, settled.Message); Assert.False(settled.Data.IsReplay); @@ -106,8 +101,8 @@ public async Task SettleAndDispatch_ShouldProduceSingleResultAndGrantOnce() Assert.Equal(2, dispatched.Data.SucceededCount); Assert.Empty(dispatched.Data.FailedPlayerIds); - var winnerWallet = await harness.AssetStore.FindWalletAsync(TenantId, AppId, PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId); - var loserWallet = await harness.AssetStore.FindWalletAsync(TenantId, AppId, PlayerTwo, OnlineRockPaperScissorsGame.RewardAssetId); + var winnerWallet = await harness.AssetStore.FindWalletAsync(PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId); + var loserWallet = await harness.AssetStore.FindWalletAsync(PlayerTwo, OnlineRockPaperScissorsGame.RewardAssetId); Assert.Equal(OnlineRockPaperScissorsGame.WinnerRewardAmount, winnerWallet.Balance); Assert.Equal(OnlineRockPaperScissorsGame.ParticipantRewardAmount, loserWallet.Balance); @@ -116,8 +111,8 @@ public async Task SettleAndDispatch_ShouldProduceSingleResultAndGrantOnce() Assert.True(replayed.IsSuccess, replayed.Message); Assert.Equal(2, replayed.Data.ReplayCount); - Assert.Equal(OnlineRockPaperScissorsGame.WinnerRewardAmount, (await harness.AssetStore.FindWalletAsync(TenantId, AppId, PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId)).Balance); - Assert.Equal(OnlineRockPaperScissorsGame.ParticipantRewardAmount, (await harness.AssetStore.FindWalletAsync(TenantId, AppId, PlayerTwo, OnlineRockPaperScissorsGame.RewardAssetId)).Balance); + Assert.Equal(OnlineRockPaperScissorsGame.WinnerRewardAmount, (await harness.AssetStore.FindWalletAsync(PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId)).Balance); + Assert.Equal(OnlineRockPaperScissorsGame.ParticipantRewardAmount, (await harness.AssetStore.FindWalletAsync(PlayerTwo, OnlineRockPaperScissorsGame.RewardAssetId)).Balance); } /// @@ -130,7 +125,7 @@ public async Task SettleAsync_AllIdle_ShouldSuppressRewardsAndPublishSuspiciousE await harness.StartRunningAsync(); await harness.RunIdleToSettlingAsync(); - var settled = await harness.Settlement.SettleAsync(TenantId, AppId, MatchId, Now + 200000); + var settled = await harness.Settlement.SettleAsync(MatchId, Now + 200000); Assert.True(settled.IsSuccess, settled.Message); Assert.False(settled.Data.IsReplay); @@ -147,8 +142,8 @@ public async Task SettleAsync_AllIdle_ShouldSuppressRewardsAndPublishSuspiciousE Assert.True(dispatched.IsSuccess, dispatched.Message); Assert.Equal(0, dispatched.Data.SucceededCount); Assert.Empty(dispatched.Data.FailedPlayerIds); - Assert.Null(await harness.AssetStore.FindWalletAsync(TenantId, AppId, PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId)); - Assert.Null(await harness.AssetStore.FindWalletAsync(TenantId, AppId, PlayerTwo, OnlineRockPaperScissorsGame.RewardAssetId)); + Assert.Null(await harness.AssetStore.FindWalletAsync(PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId)); + Assert.Null(await harness.AssetStore.FindWalletAsync(PlayerTwo, OnlineRockPaperScissorsGame.RewardAssetId)); } /// @@ -160,8 +155,8 @@ public async Task SettleAsync_Twice_ShouldReplaySameResult() var harness = new Harness(); await harness.PlayToSettlingAsync(); - var first = await harness.Settlement.SettleAsync(TenantId, AppId, MatchId, Now + 100); - var second = await harness.Settlement.SettleAsync(TenantId, AppId, MatchId, Now + 200); + var first = await harness.Settlement.SettleAsync(MatchId, Now + 100); + var second = await harness.Settlement.SettleAsync(MatchId, Now + 200); Assert.True(first.IsSuccess, first.Message); Assert.True(second.IsSuccess, second.Message); @@ -180,28 +175,28 @@ public async Task SettleAsync_BeforeSettling_ShouldBeStateNotReady() var harness = new Harness(); await harness.StartRunningAsync(); - var settled = await harness.Settlement.SettleAsync(TenantId, AppId, MatchId, Now + 100); + var settled = await harness.Settlement.SettleAsync(MatchId, Now + 100); Assert.False(settled.IsSuccess); Assert.Equal(OnlineErrorCode.StateNotReady, settled.Code); } /// - /// 验证结算结果存储按 (租户, App, 对局) 唯一——并发提交只保留首份。 + /// 验证结算结果存储按对局唯一——并发提交只保留首份。 /// [Fact] public async Task ResultStore_ConcurrentCommit_ShouldKeepFirstResult() { var store = new InMemoryOnlineMatchSettlementStore(); - var first = new OnlineMatchResult { MatchResultId = "mrs-first", MatchId = MatchId, TenantId = TenantId, AppId = AppId, Entries = new List() }; - var second = new OnlineMatchResult { MatchResultId = "mrs-second", MatchId = MatchId, TenantId = TenantId, AppId = AppId, Entries = new List() }; + var first = new OnlineMatchResult { MatchResultId = "mrs-first", MatchId = MatchId, Entries = new List() }; + var second = new OnlineMatchResult { MatchResultId = "mrs-second", MatchId = MatchId, Entries = new List() }; var committedFirst = await store.CommitAsync(first); var committedSecond = await store.CommitAsync(second); Assert.Equal("mrs-first", committedFirst.MatchResultId); Assert.Equal("mrs-first", committedSecond.MatchResultId); - Assert.Equal("mrs-first", (await store.FindByMatchAsync(TenantId, AppId, MatchId)).MatchResultId); + Assert.Equal("mrs-first", (await store.FindByMatchAsync(MatchId)).MatchResultId); } /// @@ -215,8 +210,6 @@ public async Task DispatchAsync_WithoutRewards_ShouldNotGrant() { MatchResultId = "mrs-empty", MatchId = MatchId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Entries = new List { @@ -228,7 +221,7 @@ public async Task DispatchAsync_WithoutRewards_ShouldNotGrant() Assert.True(dispatched.IsSuccess, dispatched.Message); Assert.Equal(0, dispatched.Data.SucceededCount); - Assert.Null(await harness.AssetStore.FindWalletAsync(TenantId, AppId, PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId)); + Assert.Null(await harness.AssetStore.FindWalletAsync(PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId)); } /// @@ -247,8 +240,6 @@ private static OnlineMatchAssignment BuildAssignment(params long[] playerIds) Region = 1, CreatedAtTime = Now, TicketIds = new List(), - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, }; } @@ -354,7 +345,7 @@ public async Task StartRunningAsync() { var created = await Runtime.CreateFromAssignmentAsync(BuildAssignment(PlayerOne, PlayerTwo), Now); Assert.True(created.IsSuccess, created.Message); - Actor = await Runtime.ResolveActorAsync(TenantId, AppId, MatchId); + Actor = await Runtime.ResolveActorAsync(MatchId); Assert.NotNull(Actor); await Actor.SetReadyAsync(ScopeOf(PlayerOne), true, Now); @@ -424,7 +415,7 @@ public async Task RunIdleToSettlingAsync() /// 作用域。 private static OnlineScope ScopeOf(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchSyncProtocolTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchSyncProtocolTests.cs index 2f0707683..33413cf63 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchSyncProtocolTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchSyncProtocolTests.cs @@ -43,11 +43,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchSyncProtocolTests { - /// 租户标识。 - private const long TenantId = 1; - - /// App 标识。 - private const long AppId = 10; /// 区服标识。 private const long ServerId = 100; @@ -400,8 +395,6 @@ private static OnlineMatchAssignment BuildAssignment(params long[] playerIds) Region = 1, CreatedAtTime = Now, TicketIds = new List(), - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, }; } @@ -466,7 +459,7 @@ public async Task CreateAsync() { var created = await Runtime.CreateFromAssignmentAsync(BuildAssignment(PlayerOne, PlayerTwo), Now); Assert.True(created.IsSuccess, created.Message); - Actor = await Runtime.ResolveActorAsync(TenantId, AppId, MatchId); + Actor = await Runtime.ResolveActorAsync(MatchId); Assert.NotNull(Actor); } @@ -526,7 +519,7 @@ public async Task DisconnectAsync(long playerId, long nowUnixMillisecond /// 作用域。 public OnlineScope ScopeOf(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchTicketServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchTicketServiceTests.cs index c41f4451b..4dc068058 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchTicketServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchTicketServiceTests.cs @@ -42,11 +42,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchTicketServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; /// 测试用区服标识。 private const long ServerId = 100; @@ -95,7 +90,7 @@ public async Task EnqueueAsync_WhenPlayerAlreadyQueued_ShouldBeRejected() // Assert Assert.False(outcome.IsSuccess); Assert.Equal(OnlineErrorCode.DuplicateRequest, outcome.Code); - var queued = await store.ListQueuedAsync(TenantId, AppId); + var queued = await store.ListQueuedAsync(); Assert.Single(queued); } @@ -179,8 +174,6 @@ public async Task CancelAsync_WhenAlreadyMatched_ShouldReturnTerminalReceipt() MatchId = "match-fixed", PlayerIds = new List { PlayerOne }, TicketIds = new List { enqueued.Data.TicketId }, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, }; var committed = await store.CommitMatchAsync(assignment, new List { enqueued.Data.TicketId }, OnlineMatchTicketState.Queued); @@ -245,12 +238,12 @@ public async Task SweepExpiredAsync_ShouldExpireOverdueTicket() var enqueued = await service.EnqueueAsync(CreatePlayerScope(PlayerOne), CreateEnqueueRequest(PlayerOne)); // Act - var outcome = await service.SweepExpiredAsync(TenantId, AppId, enqueued.Data.ExpiresAtTime + 1); + var outcome = await service.SweepExpiredAsync(enqueued.Data.ExpiresAtTime + 1); // Assert Assert.True(outcome.IsSuccess); Assert.Equal(1, outcome.Data); - var expired = await store.FindAsync(TenantId, AppId, enqueued.Data.TicketId); + var expired = await store.FindAsync(enqueued.Data.TicketId); Assert.Equal(OnlineMatchTicketState.Expired, expired.State); Assert.Equal(OnlineMatchFailureReason.WaitTimeout, expired.FailureReason); Assert.Single(recorder.Filter(OnlineMatchEvents.TicketChanged)); @@ -266,7 +259,7 @@ public async Task EnqueueAsync_AfterTicketExpired_ShouldBeAllowed() var service = CreateService(out _, out _, new OnlineMatchmakerOptions { TicketTimeToLiveSeconds = 1 }); var scope = CreatePlayerScope(PlayerOne); var enqueued = await service.EnqueueAsync(scope, CreateEnqueueRequest(PlayerOne)); - await service.SweepExpiredAsync(TenantId, AppId, enqueued.Data.ExpiresAtTime + 1); + await service.SweepExpiredAsync(enqueued.Data.ExpiresAtTime + 1); // Act var outcome = await service.EnqueueAsync(scope, CreateEnqueueRequest(PlayerOne)); @@ -309,7 +302,7 @@ public async Task EnqueueAsync_WhenSamePlayerEnqueuesConcurrently_ShouldYieldSin Assert.Equal(1, successCount); Assert.NotNull(rejected); Assert.Equal(OnlineErrorCode.DuplicateRequest, rejected.Code); - var queued = await store.ListQueuedAsync(TenantId, AppId); + var queued = await store.ListQueuedAsync(); var ticket = Assert.Single(queued); var active = await service.GetActiveAsync(scope); Assert.NotNull(active.Data); @@ -355,7 +348,7 @@ public async Task EnqueueAsync_WhenPartiesShareMemberConcurrently_ShouldYieldSin Assert.Equal(1, successCount); Assert.NotNull(rejected); Assert.Equal(OnlineErrorCode.DuplicateRequest, rejected.Code); - var queued = await store.ListQueuedAsync(TenantId, AppId); + var queued = await store.ListQueuedAsync(); var ticket = Assert.Single(queued); var sharedActive = await service.GetActiveAsync(CreatePlayerScope(sharedMember)); Assert.NotNull(sharedActive.Data); @@ -376,8 +369,6 @@ public async Task TryEnqueueIfAbsentAsync_WhenPlayerAlreadyIndexed_ShouldReturnE TicketId = "tkt-conflict", PartyId = string.Empty, PlayerIds = new List { PlayerOne }, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, State = OnlineMatchTicketState.Queued, CreatedAtTime = 1, @@ -390,9 +381,9 @@ public async Task TryEnqueueIfAbsentAsync_WhenPlayerAlreadyIndexed_ShouldReturnE // Assert Assert.NotEqual(conflicting.TicketId, outcome.TicketId); Assert.Equal(enqueued.Data.TicketId, outcome.TicketId); - var all = await store.ListAllAsync(TenantId, AppId); + var all = await store.ListAllAsync(); Assert.Single(all); - var active = await store.FindActiveByPlayerAsync(TenantId, AppId, PlayerOne); + var active = await store.FindActiveByPlayerAsync(PlayerOne); Assert.Equal(enqueued.Data.TicketId, active.TicketId); } @@ -449,7 +440,7 @@ private static OnlineMatchTicketEnqueueRequest CreateEnqueueRequest(long playerI /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchmakerCoordinatorTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchmakerCoordinatorTests.cs index 17436c761..72dff6841 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchmakerCoordinatorTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchmakerCoordinatorTests.cs @@ -41,11 +41,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineMatchmakerCoordinatorTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; /// 测试用区服标识。 private const long ServerId = 100; @@ -71,7 +66,7 @@ public async Task RunOnceAsync_WithCompatibleTickets_ShouldProduceSingleAssignme await EnqueueAsync(fixture, PlayerTwo); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -79,7 +74,7 @@ public async Task RunOnceAsync_WithCompatibleTickets_ShouldProduceSingleAssignme Assert.Equal(2, outcome.Data.MatchedTicketCount); Assert.Equal(2, outcome.Data.MatchedPlayerCount); - var assignment = await fixture.Store.FindAssignmentAsync(TenantId, AppId, outcome.Data.AssignmentIds[0]); + var assignment = await fixture.Store.FindAssignmentAsync(outcome.Data.AssignmentIds[0]); Assert.Equal(new List { PlayerOne, PlayerTwo }, assignment.PlayerIds); Assert.Equal(2, assignment.TicketIds.Count); Assert.Single(fixture.Recorder.Filter(OnlineMatchEvents.AssignmentCreated)); @@ -96,16 +91,16 @@ public async Task RunOnceAsync_WhenRunAgain_ShouldNotProduceSecondAssignment() var fixture = CreateFixture(); await EnqueueAsync(fixture, PlayerOne); await EnqueueAsync(fixture, PlayerTwo); - await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + await fixture.Coordinator.RunOnceAsync(); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); Assert.Empty(outcome.Data.AssignmentIds); Assert.Equal(0, outcome.Data.MatchedTicketCount); - var assignments = await fixture.Store.ListAssignmentsAsync(TenantId, AppId); + var assignments = await fixture.Store.ListAssignmentsAsync(); Assert.Single(assignments); } @@ -120,12 +115,12 @@ public async Task RunOnceAsync_WithSingleTicket_ShouldKeepQueued() var ticket = await EnqueueAsync(fixture, PlayerOne); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); Assert.Empty(outcome.Data.AssignmentIds); - var queued = await fixture.Store.FindAsync(TenantId, AppId, ticket.TicketId); + var queued = await fixture.Store.FindAsync(ticket.TicketId); Assert.Equal(OnlineMatchTicketState.Queued, queued.State); } @@ -141,13 +136,13 @@ public async Task RunOnceAsync_WithPartyTicket_ShouldNotSplitParty() var lone = await EnqueueAsync(fixture, PlayerThree); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); - var assignment = await fixture.Store.FindAssignmentAsync(TenantId, AppId, outcome.Data.AssignmentIds[0]); + var assignment = await fixture.Store.FindAssignmentAsync(outcome.Data.AssignmentIds[0]); Assert.Equal(new List { PlayerOne, PlayerTwo }, assignment.PlayerIds); - var queued = await fixture.Store.FindAsync(TenantId, AppId, lone.TicketId); + var queued = await fixture.Store.FindAsync(lone.TicketId); Assert.Equal(OnlineMatchTicketState.Queued, queued.State); } @@ -163,7 +158,7 @@ public async Task RunOnceAsync_WithDisjointSkillRange_ShouldNotMatch() await EnqueueAsync(fixture, PlayerTwo, skillMin: 900, skillMax: 1000); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -188,17 +183,17 @@ public async Task RunOnceAsync_AfterWaitExpansion_ShouldMatchAndRecordSnapshot() var waiting = await EnqueueAsync(fixture, PlayerOne, skillMin: 100, skillMax: 200); await EnqueueAsync(fixture, PlayerTwo, skillMin: 250, skillMax: 300); - var stale = await fixture.Store.FindAsync(TenantId, AppId, waiting.TicketId); + var stale = await fixture.Store.FindAsync(waiting.TicketId); stale.CreatedAtTime = waiting.CreatedAtTime - 60000; await fixture.Store.SaveAsync(stale); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId, waiting.CreatedAtTime); + var outcome = await fixture.Coordinator.RunOnceAsync(waiting.CreatedAtTime); // Assert Assert.True(outcome.IsSuccess); Assert.Single(outcome.Data.AssignmentIds); - var assignment = await fixture.Store.FindAssignmentAsync(TenantId, AppId, outcome.Data.AssignmentIds[0]); + var assignment = await fixture.Store.FindAssignmentAsync(outcome.Data.AssignmentIds[0]); Assert.True(assignment.RuleSnapshot.SkillRangeExpanded); Assert.Equal(0, assignment.RuleSnapshot.SkillMin); Assert.True(assignment.RuleSnapshot.WaitSeconds >= 60); @@ -217,14 +212,14 @@ public async Task RunOnceAsync_AfterCancel_ShouldNotMatchCancelledTicket() await fixture.Tickets.CancelAsync(CreatePlayerScope(PlayerOne), cancelled.TicketId); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); Assert.Empty(outcome.Data.AssignmentIds); - var queued = await fixture.Store.FindAsync(TenantId, AppId, remaining.TicketId); + var queued = await fixture.Store.FindAsync(remaining.TicketId); Assert.Equal(OnlineMatchTicketState.Queued, queued.State); - var assignments = await fixture.Store.ListAssignmentsAsync(TenantId, AppId); + var assignments = await fixture.Store.ListAssignmentsAsync(); Assert.Empty(assignments); } @@ -239,13 +234,13 @@ public async Task RunOnceAsync_WithOverdueTicket_ShouldExpireItFirst() var ticket = await EnqueueAsync(fixture, PlayerOne); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId, ticket.ExpiresAtTime + 1); + var outcome = await fixture.Coordinator.RunOnceAsync(ticket.ExpiresAtTime + 1); // Assert Assert.True(outcome.IsSuccess); Assert.Equal(1, outcome.Data.ExpiredTicketCount); Assert.Equal(0, outcome.Data.ScannedTicketCount); - var expired = await fixture.Store.FindAsync(TenantId, AppId, ticket.TicketId); + var expired = await fixture.Store.FindAsync(ticket.TicketId); Assert.Equal(OnlineMatchTicketState.Expired, expired.State); } @@ -262,28 +257,28 @@ public async Task RunOnceAsync_WhenAssignmentEventPublishFails_ShouldRedeliverOn await EnqueueAsync(fixture, PlayerTwo); // Act:第一轮——assignment-created 发布抛异常,落档与逐票据事件不受影响。 - var firstOutcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var firstOutcome = await fixture.Coordinator.RunOnceAsync(); // Assert:撮合结果完整,失败事件保留在发件箱待投递。 Assert.True(firstOutcome.IsSuccess); Assert.Single(firstOutcome.Data.AssignmentIds); Assert.Empty(fixture.Recorder.Filter(OnlineMatchEvents.AssignmentCreated)); Assert.Equal(2, fixture.Recorder.Filter(OnlineMatchEvents.TicketChanged).Count); - var pendingAfterFirstRun = await fixture.Outbox.ListPendingAsync(TenantId, AppId); + var pendingAfterFirstRun = await fixture.Outbox.ListPendingAsync(); Assert.Single(pendingAfterFirstRun); Assert.Equal(OnlineMatchEvents.AssignmentCreated, pendingAfterFirstRun[0].Event.EventType); // Act:第二轮——无新票据,故障桩已恢复,仅重投待投递事件。 - var secondOutcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var secondOutcome = await fixture.Coordinator.RunOnceAsync(); // Assert:事件补投送达且不重复,assignment 仍唯一,发件箱清空。 Assert.True(secondOutcome.IsSuccess); Assert.Empty(secondOutcome.Data.AssignmentIds); Assert.Single(fixture.Recorder.Filter(OnlineMatchEvents.AssignmentCreated)); Assert.Equal(2, fixture.Recorder.Filter(OnlineMatchEvents.TicketChanged).Count); - var assignments = await fixture.Store.ListAssignmentsAsync(TenantId, AppId); + var assignments = await fixture.Store.ListAssignmentsAsync(); Assert.Single(assignments); - Assert.Empty(await fixture.Outbox.ListPendingAsync(TenantId, AppId)); + Assert.Empty(await fixture.Outbox.ListPendingAsync()); } /// @@ -300,17 +295,17 @@ public async Task RunOnceAsync_WhenPublishKeepsFailing_ShouldRetainPendingWithou await EnqueueAsync(fixture, PlayerTwo); // Act - var firstOutcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); - var secondOutcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var firstOutcome = await fixture.Coordinator.RunOnceAsync(); + var secondOutcome = await fixture.Coordinator.RunOnceAsync(); // Assert:两轮撮合结果正确,assignment 唯一;失败事件保留且不重复。 Assert.True(firstOutcome.IsSuccess); Assert.Single(firstOutcome.Data.AssignmentIds); Assert.True(secondOutcome.IsSuccess); Assert.Empty(secondOutcome.Data.AssignmentIds); - var assignments = await fixture.Store.ListAssignmentsAsync(TenantId, AppId); + var assignments = await fixture.Store.ListAssignmentsAsync(); Assert.Single(assignments); - var pending = await fixture.Outbox.ListPendingAsync(TenantId, AppId); + var pending = await fixture.Outbox.ListPendingAsync(); Assert.Single(pending); Assert.Equal(OnlineMatchEvents.AssignmentCreated, pending[0].Event.EventType); } @@ -327,7 +322,7 @@ public async Task RunOnceAsync_WithOutbox_ShouldPreserveEventOrder() await EnqueueAsync(fixture, PlayerTwo); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -360,12 +355,12 @@ public async Task RunOnceAsync_WithSoloTicketWithoutSkillRange_ShouldSnapshotZer Assert.True(outcome.IsSuccess); // Act - var run = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var run = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(run.IsSuccess); Assert.Single(run.Data.AssignmentIds); - var assignment = await fixture.Store.FindAssignmentAsync(TenantId, AppId, run.Data.AssignmentIds[0]); + var assignment = await fixture.Store.FindAssignmentAsync(run.Data.AssignmentIds[0]); Assert.NotNull(assignment); Assert.Equal(0, assignment.RuleSnapshot.SkillMin); Assert.Equal(0, assignment.RuleSnapshot.SkillMax); @@ -450,7 +445,7 @@ private static async Task EnqueueAsync(Fixture fixture, long /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineNotificationServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineNotificationServiceTests.cs index 9fed1aae4..cbe5bb328 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineNotificationServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineNotificationServiceTests.cs @@ -45,11 +45,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineNotificationServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; /// 测试用区服标识。 private const long ServerId = 100; @@ -201,7 +196,7 @@ public async Task EnqueueAsync_WhenDispatcherFailsNonRetryably_ShouldReachFailed Assert.Equal("接收者不存在", outcome.Data.LastError); Assert.Equal(1, outcome.Data.AttemptCount); - var retried = await service.RetryPendingAsync(TenantId, AppId, 100); + var retried = await service.RetryPendingAsync(100); Assert.True(retried.IsSuccess); Assert.Equal(1, retried.Data); @@ -304,7 +299,7 @@ public async Task RetryPendingAsync_ShouldExhaustRetryBudgetIntoFailed() Assert.Equal(1, enqueued.Data.AttemptCount); // Act:本轮配额给 1,只重投 Retrying 批次,一次重投即耗尽 maxAttempts - var retried = await service.RetryPendingAsync(TenantId, AppId, 1); + var retried = await service.RetryPendingAsync(1); // Assert Assert.True(retried.IsSuccess); @@ -343,7 +338,7 @@ public async Task SweepExpiredAsync_ShouldExpireOverdueNotificationAndHideItFrom await Task.Delay(120); // Act - var sweep = await service.SweepExpiredAsync(TenantId, AppId); + var sweep = await service.SweepExpiredAsync(); // Assert Assert.True(sweep.IsSuccess); @@ -402,7 +397,7 @@ public async Task MarkReadAsync_WhenExpired_ShouldReturnStateOperationForbidden( var scope = CreateReceiverScope(ReceiverId); var expiredAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - 1_000; var enqueued = await service.EnqueueAsync(scope, OnlineNotificationKind.Mail, DedupeKey, PayloadBody, expiredAt); - var sweep = await service.SweepExpiredAsync(TenantId, AppId); + var sweep = await service.SweepExpiredAsync(); Assert.Equal(OnlineNotificationState.Expired, enqueued.Data.State); Assert.Equal(0, sweep.Data); @@ -442,7 +437,7 @@ public async Task TryDispatchAsync_WhenDispatchInFlight_ShouldNotPushAgain() Assert.True(listed.IsSuccess); var notificationId = Assert.Single(listed.Data).NotificationId; - var repeated = await service.TryDispatchAsync(TenantId, AppId, ReceiverId, notificationId); + var repeated = await service.TryDispatchAsync(ReceiverId, notificationId); // Assert:第二次被「已在途」拦下,没有再次调用推送出口。 Assert.False(repeated.IsSuccess); @@ -487,7 +482,7 @@ public async Task SweepExpiredAsync_WhenDispatchLeaseActive_ShouldNotExpireInFli await dispatcher.Entered; await Task.Delay(450); - var sweep = await service.SweepExpiredAsync(TenantId, AppId); + var sweep = await service.SweepExpiredAsync(); // Assert:租约保护生效,本轮零终结,记录仍在途。 Assert.True(sweep.IsSuccess); @@ -529,7 +524,7 @@ public async Task SweepExpiredAsync_WhenDispatchLeaseLapsed_ShouldExpireAbandone await dispatcher.Entered; await Task.Delay(1_400); - var sweep = await service.SweepExpiredAsync(TenantId, AppId); + var sweep = await service.SweepExpiredAsync(); // Assert:死在途被终结。 Assert.True(sweep.IsSuccess); @@ -573,7 +568,7 @@ public async Task TryDispatchAsync_WhenDispatchInFlightAndExpired_ShouldNotTermi var listed = await service.ListAsync(scope, true); Assert.True(listed.IsSuccess); var notificationId = Assert.Single(listed.Data).NotificationId; - var repeated = await service.TryDispatchAsync(TenantId, AppId, ReceiverId, notificationId); + var repeated = await service.TryDispatchAsync(ReceiverId, notificationId); // Assert:第二次被「已在途」拦下(而非就地终结成 Expired),记录原样在途。 Assert.False(repeated.IsSuccess); @@ -749,7 +744,7 @@ private static OnlineNotificationService CreateService(out OnlineEventRecorder r /// 作用域。 private static OnlineScope CreateReceiverScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// 推送出口桩的行为模式。 diff --git a/Tests/GameFrameX.Tests/Online/OnlineOverviewServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineOverviewServiceTests.cs index 185fe07a8..5c9dbc7e4 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineOverviewServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineOverviewServiceTests.cs @@ -45,11 +45,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineOverviewServiceTests { - /// 测试用租户标识。 - private const long TenantId = OnlineOverviewTimelineTestHarness.TenantId; - - /// 测试用应用标识。 - private const long AppId = OnlineOverviewTimelineTestHarness.AppId; /// 测试用区服标识。 private const long ServerId = OnlineOverviewTimelineTestHarness.ServerId; @@ -97,8 +92,6 @@ public async Task ReviewAsync_ShouldCountPlayersSessionsPartiesAndMatches() // Assert Assert.True(outcome.IsSuccess); var snapshot = outcome.Data; - Assert.Equal(TenantId, snapshot.TenantId); - Assert.Equal(AppId, snapshot.AppId); Assert.Equal(ServerId, snapshot.ServerId); Assert.True(snapshot.ObservedTime > 0); @@ -141,7 +134,7 @@ public async Task ReviewAsync_ShouldGroupQueueSummaryByModeAndRegion() await harness.EnqueueAsync(OtherServerId, 1005, mode: 5, region: 5); var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var queued = await harness.TicketStore.ListQueuedAsync(TenantId, AppId); + var queued = await harness.TicketStore.ListQueuedAsync(); // Act var outcome = await harness.CreateOverviewService().ReviewAsync(OnlineOverviewTimelineTestHarness.CreateScope(), now); @@ -229,14 +222,11 @@ public async Task ReviewAsync_InvalidScope_ShouldReturnParameterInvalid() var service = new OnlineOverviewTimelineTestHarness().CreateOverviewService(); // Act - var missingServer = await service.ReviewAsync(new OnlineScope(TenantId, AppId, 0)); - var missingTenant = await service.ReviewAsync(new OnlineScope(0, AppId, ServerId)); + var missingServer = await service.ReviewAsync(new OnlineScope(0)); // Assert Assert.False(missingServer.IsSuccess); Assert.Equal(OnlineErrorCode.ParameterInvalid, missingServer.Code); - Assert.False(missingTenant.IsSuccess); - Assert.Equal(OnlineErrorCode.ParameterInvalid, missingTenant.Code); await Assert.ThrowsAsync(() => service.ReviewAsync(null)); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineOverviewTimelineTestHarness.cs b/Tests/GameFrameX.Tests/Online/OnlineOverviewTimelineTestHarness.cs index 51d40c5c7..89f3df2e3 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineOverviewTimelineTestHarness.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineOverviewTimelineTestHarness.cs @@ -59,11 +59,6 @@ namespace GameFrameX.Tests.Online /// internal sealed class OnlineOverviewTimelineTestHarness { - /// 测试用租户标识。 - internal const long TenantId = 1; - - /// 测试用应用标识。 - internal const long AppId = 10; /// 测试用区服标识。 internal const long ServerId = 100; @@ -161,7 +156,7 @@ internal OnlinePlayerTimelineService CreateTimelineService(IOnlineConfigHitProbe /// 作用域实例。 internal static OnlineScope CreateScope(long serverId = ServerId, long playerId = 0) { - return new OnlineScope(TenantId, AppId, serverId, playerId); + return new OnlineScope(serverId, playerId); } /// @@ -172,7 +167,7 @@ internal static OnlineScope CreateScope(long serverId = ServerId, long playerId /// 登录解析结果(身份 / 账号 / 玩家档案三件套)。 internal async Task RegisterPlayerAsync(long serverId, string userName) { - var outcome = await new OnlineIdentityService(IdentityStore, new OnlineAuditService(new InMemoryOnlineAuditStore())).ResolveLoginAsync(new OnlineLoginRequest { TenantId = TenantId, AppId = AppId, ServerId = serverId, Kind = OnlineIdentityKind.UserName, Identifier = userName }); + var outcome = await new OnlineIdentityService(IdentityStore, new OnlineAuditService(new InMemoryOnlineAuditStore())).ResolveLoginAsync(new OnlineLoginRequest { ServerId = serverId, Kind = OnlineIdentityKind.UserName, Identifier = userName }); Assert.True(outcome.IsSuccess); return outcome.Data; } @@ -290,7 +285,7 @@ internal async Task RunMatchmakerAsync(long serverId) var matchmakerOptions = new OnlineMatchmakerOptions(); var tickets = new OnlineMatchTicketService(TicketStore, Recorder, matchmakerOptions); var coordinator = new OnlineMatchmakerCoordinator(TicketStore, tickets, Recorder, matchmakerOptions); - var outcome = await coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await coordinator.RunOnceAsync(); Assert.True(outcome.IsSuccess); } @@ -308,8 +303,6 @@ internal async Task CreateMatchAsync(long serverId, long playerId, { var match = new OnlineMatch { - TenantId = TenantId, - AppId = AppId, ServerId = serverId, MatchId = matchId, AssignmentId = "assign-" + matchId, @@ -367,7 +360,7 @@ internal async Task GrantAsync(long serverId, long playerId, /// 处罚记录。 internal async Task PunishAsync(long playerId, string reason) { - var outcome = await new OnlinePunishmentService(SocialGraphStore, Recorder).ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = playerId, Kind = OnlinePunishmentKind.Mute, Reason = reason, AdminId = AdminId }); + var outcome = await new OnlinePunishmentService(SocialGraphStore, Recorder).ApplyAsync(new OnlinePunishmentRequest { PlayerId = playerId, Kind = OnlinePunishmentKind.Mute, Reason = reason, AdminId = AdminId }); Assert.True(outcome.IsSuccess); return outcome.Data; } @@ -379,7 +372,7 @@ internal async Task PunishAsync(long playerId, string reason) /// 异步任务。 internal async Task RevokePunishmentAsync(string punishmentId) { - var outcome = await new OnlinePunishmentService(SocialGraphStore, Recorder).RevokeAsync(TenantId, AppId, punishmentId, AdminId); + var outcome = await new OnlinePunishmentService(SocialGraphStore, Recorder).RevokeAsync(punishmentId, AdminId); Assert.True(outcome.IsSuccess); } @@ -432,42 +425,37 @@ internal sealed class FakeConfigHitProbe : IOnlineConfigHitProbe /// /// 登记一条命中记录。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 玩家标识。 /// 命中记录。 - internal void Add(long tenantId, long appId, long serverId, long playerId, OnlineConfigHitRecord record) + internal void Add(long serverId, long playerId, OnlineConfigHitRecord record) { _entries.Add(new Entry { - TenantId = tenantId, - AppId = appId, ServerId = serverId, PlayerId = playerId, Record = record, }); } + /// - /// 回放按 (租户, App, 区服, 玩家) 四键登记的命中记录,未登记的作用域返回空集合。 + /// 回放按 (区服, 玩家) 双键登记的命中记录,未登记的作用域返回空集合。 /// /// - /// Replays the records registered under the (tenant, app, server, player) four-part key; + /// Replays the records registered under the (server, player) two-part key; /// unregistered scopes yield an empty list. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 区服标识 / Server id /// 玩家标识 / Player id /// 取消令牌 / Cancellation token /// 该作用域登记的命中记录 / The hit records registered for the scope - public Task> ListHitsAsync(long tenantId, long appId, long serverId, long playerId, CancellationToken cancellationToken = default) + public Task> ListHitsAsync(long serverId, long playerId, CancellationToken cancellationToken = default) { var matched = new List(); foreach (var entry in _entries) { - if (entry.TenantId == tenantId && entry.AppId == appId && entry.ServerId == serverId && entry.PlayerId == playerId) + if (entry.ServerId == serverId && entry.PlayerId == playerId) { matched.Add(entry.Record); } @@ -479,20 +467,6 @@ public Task> ListHitsAsync(long tenantId, l /// 登记项(记录 + 归属作用域键)。 private sealed class Entry { - /// 获取或设置租户标识。 - public long TenantId - { - get; - set; - } - - /// 获取或设置 App 标识。 - public long AppId - { - get; - set; - } - /// 获取或设置区服标识。 public long ServerId { diff --git a/Tests/GameFrameX.Tests/Online/OnlinePartyServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlinePartyServiceTests.cs index 68b8706d1..38421220b 100644 --- a/Tests/GameFrameX.Tests/Online/OnlinePartyServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlinePartyServiceTests.cs @@ -43,11 +43,6 @@ namespace GameFrameX.Tests.Online /// public class OnlinePartyServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; /// 测试用区服标识。 private const long ServerId = 100; @@ -346,7 +341,7 @@ private static async Task FormPartyAsync(OnlinePartyService service /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// @@ -372,12 +367,10 @@ public StubPresenceProbe(params long[] onlinePlayerIds) /// /// Only checks whether the player is in the online whitelist supplied at construction. /// - /// 租户标识 / Tenant id - /// App 标识 / App id /// 玩家标识 / Player id /// 取消令牌 / Cancellation token /// 在白名单中返回 true / True when present in the whitelist - public Task IsOnlineAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + public Task IsOnlineAsync(long playerId, CancellationToken cancellationToken = default) { return Task.FromResult(_online.Contains(playerId)); } diff --git a/Tests/GameFrameX.Tests/Online/OnlinePlayerStorageServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlinePlayerStorageServiceTests.cs index f2923618b..aa0ed0f8b 100644 --- a/Tests/GameFrameX.Tests/Online/OnlinePlayerStorageServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlinePlayerStorageServiceTests.cs @@ -42,12 +42,6 @@ namespace GameFrameX.Tests.Online /// public class OnlinePlayerStorageServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用玩家一标识。 private const long PlayerOne = 1001; @@ -55,7 +49,7 @@ public class OnlinePlayerStorageServiceTests private const long PlayerTwo = 1002; /// - /// 验证三向隔离:跨玩家/跨 App/跨租户读取一律同构 ResourceNotFound(防存在性探测)。 + /// 验证跨玩家隔离:跨玩家读取同构 ResourceNotFound(防存在性探测)。 /// [Fact] public async Task ReadAsync_CrossScope_ShouldReturnUniformNotFound() @@ -68,18 +62,12 @@ public async Task ReadAsync_CrossScope_ShouldReturnUniformNotFound() // Act var own = await service.ReadAsync(scope, "settings", "volume"); var crossPlayer = await service.ReadAsync(CreateScope(PlayerTwo), "settings", "volume"); - var crossApp = await service.ReadAsync(new OnlineScope(TenantId, AppId + 1, 100, PlayerOne), "settings", "volume"); - var crossTenant = await service.ReadAsync(new OnlineScope(TenantId + 1, AppId, 100, PlayerOne), "settings", "volume"); // Assert Assert.True(own.IsSuccess); Assert.Equal("42", Decode(own.Data.Payload)); Assert.False(crossPlayer.IsSuccess); Assert.Equal(OnlineErrorCode.ResourceNotFound, crossPlayer.Code); - Assert.False(crossApp.IsSuccess); - Assert.Equal(OnlineErrorCode.ResourceNotFound, crossApp.Code); - Assert.False(crossTenant.IsSuccess); - Assert.Equal(OnlineErrorCode.ResourceNotFound, crossTenant.Code); } /// @@ -93,7 +81,7 @@ public async Task ReadAsync_SamePlayerDifferentServer_ShouldShareData() await service.WriteAsync(CreateScope(PlayerOne), "settings", "volume", Encode("42"), 0, "sess-1"); // Act - var otherServer = await service.ReadAsync(new OnlineScope(TenantId, AppId, 200, PlayerOne), "settings", "volume"); + var otherServer = await service.ReadAsync(new OnlineScope(200, PlayerOne), "settings", "volume"); // Assert Assert.True(otherServer.IsSuccess); @@ -273,7 +261,7 @@ public async Task WriteAsync_WithoutPlayerScope_ShouldBeRejected() { // Arrange var service = CreateService(); - var scope = new OnlineScope(TenantId, AppId, 100); + var scope = new OnlineScope(100); // Act var outcome = await service.WriteAsync(scope, "settings", "volume", Encode("42"), 0, "sess-1"); @@ -300,7 +288,7 @@ private static OnlinePlayerStorageService CreateService() /// 作用域实例。 private static OnlineScope CreateScope(long playerId) { - return new OnlineScope(TenantId, AppId, 100, playerId); + return new OnlineScope(100, playerId); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlinePlayerTimelineServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlinePlayerTimelineServiceTests.cs index 2c74499f5..cb6b56a68 100644 --- a/Tests/GameFrameX.Tests/Online/OnlinePlayerTimelineServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlinePlayerTimelineServiceTests.cs @@ -48,11 +48,6 @@ namespace GameFrameX.Tests.Online /// public class OnlinePlayerTimelineServiceTests { - /// 测试用租户标识。 - private const long TenantId = OnlineOverviewTimelineTestHarness.TenantId; - - /// 测试用应用标识。 - private const long AppId = OnlineOverviewTimelineTestHarness.AppId; /// 测试用区服标识。 private const long ServerId = OnlineOverviewTimelineTestHarness.ServerId; @@ -351,7 +346,7 @@ public async Task QueryAsync_ConfigHitLeg_ShouldBeEmptySlotWhenUnwiredAndScopedW var scope = OnlineOverviewTimelineTestHarness.CreateScope(playerId: alice.Player.Id); var probe = new OnlineOverviewTimelineTestHarness.FakeConfigHitProbe(); - probe.Add(TenantId, AppId, ServerId, alice.Player.Id, new OnlineConfigHitRecord + probe.Add(ServerId, alice.Player.Id, new OnlineConfigHitRecord { EventId = "config:local", EventType = OnlinePlayerTimelineEventTypes.ConfigHit, @@ -360,7 +355,7 @@ public async Task QueryAsync_ConfigHitLeg_ShouldBeEmptySlotWhenUnwiredAndScopedW CorrelationId = "cfg-local", PayloadSummary = "命中活动 A", }); - probe.Add(TenantId, AppId, ServerId, alice.Player.Id, new OnlineConfigHitRecord + probe.Add(ServerId, alice.Player.Id, new OnlineConfigHitRecord { EventId = "config:season", EventType = OnlinePlayerTimelineEventTypes.ConfigHit, @@ -369,7 +364,7 @@ public async Task QueryAsync_ConfigHitLeg_ShouldBeEmptySlotWhenUnwiredAndScopedW CorrelationId = "cfg-season", PayloadSummary = "命中赛季 B", }); - probe.Add(TenantId, AppId, ServerId, alice.Player.Id, new OnlineConfigHitRecord + probe.Add(ServerId, alice.Player.Id, new OnlineConfigHitRecord { EventId = string.Empty, EventType = OnlinePlayerTimelineEventTypes.ConfigHit, @@ -378,7 +373,7 @@ public async Task QueryAsync_ConfigHitLeg_ShouldBeEmptySlotWhenUnwiredAndScopedW CorrelationId = "cfg-anonymous", PayloadSummary = "命中活动 C(探针未给行标识)", }); - probe.Add(TenantId, AppId, ServerId, alice.Player.Id, new OnlineConfigHitRecord + probe.Add(ServerId, alice.Player.Id, new OnlineConfigHitRecord { EventId = string.Empty, EventType = OnlinePlayerTimelineEventTypes.ConfigHit, @@ -387,7 +382,7 @@ public async Task QueryAsync_ConfigHitLeg_ShouldBeEmptySlotWhenUnwiredAndScopedW CorrelationId = string.Empty, PayloadSummary = "不可定位的命中", }); - probe.Add(TenantId, AppId, OtherServerId, alice.Player.Id, new OnlineConfigHitRecord + probe.Add(OtherServerId, alice.Player.Id, new OnlineConfigHitRecord { EventId = "config:foreign-server", EventType = OnlinePlayerTimelineEventTypes.ConfigHit, @@ -489,7 +484,7 @@ public async Task QueryAsync_CrossScope_ShouldBeIndistinguishableFromUnknownPlay await harness.PunishAsync(dave.Player.Id, "他服处罚"); // 前置事实:该玩家在处罚读取面确实有记录(处罚没有区服维度,扣掉作用域门就会泄露存在性) - var punishments = await harness.SocialGraphStore.ListPunishmentsByPlayerAsync(TenantId, AppId, dave.Player.Id); + var punishments = await harness.SocialGraphStore.ListPunishmentsByPlayerAsync(dave.Player.Id); Assert.NotEmpty(punishments); var service = harness.CreateTimelineService(); @@ -525,7 +520,7 @@ public async Task QueryAsync_InvalidInput_ShouldReturnParameterInvalid() // Act var noPlayer = await service.QueryAsync(OnlineOverviewTimelineTestHarness.CreateScope()); - var noServer = await service.QueryAsync(new OnlineScope(TenantId, AppId, 0, alice.Player.Id)); + var noServer = await service.QueryAsync(new OnlineScope(0, alice.Player.Id)); var tooMany = await service.QueryAsync(scope, new OnlinePlayerTimelineQuery { PageSize = 201 }); var badCursor = await service.QueryAsync(scope, new OnlinePlayerTimelineQuery { Cursor = "not-a-cursor" }); var emptyEventId = await service.QueryAsync(scope, new OnlinePlayerTimelineQuery { Cursor = "1800000000|" }); diff --git a/Tests/GameFrameX.Tests/Online/OnlinePresenceServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlinePresenceServiceTests.cs index 82ba274ab..8a8c853bc 100644 --- a/Tests/GameFrameX.Tests/Online/OnlinePresenceServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlinePresenceServiceTests.cs @@ -42,12 +42,6 @@ namespace GameFrameX.Tests.Online /// public class OnlinePresenceServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -65,7 +59,7 @@ public async Task SetOnlineAsync_WithoutPlayerScope_ShouldBeRejected() { // Arrange var service = CreateService(out var recorder); - var scope = new OnlineScope(TenantId, AppId, ServerId, 0); + var scope = new OnlineScope(ServerId, 0); // Act var outcome = await service.SetOnlineAsync(scope, "sess-a"); @@ -164,7 +158,7 @@ public async Task SweepTimeoutsAsync_ReconnectWindowExpired_ShouldRemoveRecordAn // Act:窗口 30 秒,基准时刻推到 31 秒后。 var futureNow = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + 31_000; - var swept = await service.SweepTimeoutsAsync(TenantId, AppId, futureNow); + var swept = await service.SweepTimeoutsAsync(futureNow); var state = await service.GetAsync(scope); // Assert @@ -189,7 +183,7 @@ public async Task SweepThenHeartbeat_ShouldIdleThenResumeOnline() // Act:心跳推到 301 秒前(等效无操作 301 秒)。 var futureNow = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + 301_000; - var swept = await service.SweepTimeoutsAsync(TenantId, AppId, futureNow); + var swept = await service.SweepTimeoutsAsync(futureNow); var idleState = await service.GetAsync(scope); var resumed = await service.HeartbeatAsync(scope); var finalState = await service.GetAsync(scope); @@ -219,8 +213,8 @@ public async Task SweepTimeoutsAsync_MoreThanSweepLimit_ShouldCapAndContinueNext // Act:心跳全部推到 301 秒前。 var futureNow = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + 301_000; - var firstSweep = await service.SweepTimeoutsAsync(TenantId, AppId, futureNow); - var secondSweep = await service.SweepTimeoutsAsync(TenantId, AppId, futureNow); + var firstSweep = await service.SweepTimeoutsAsync(futureNow); + var secondSweep = await service.SweepTimeoutsAsync(futureNow); var idleCount = 0; foreach (var playerId in playerIdentifiers) { @@ -249,7 +243,7 @@ public async Task SweepTimeoutsAsync_WithinIdleThreshold_ShouldNotBeSwept() await service.SetOnlineAsync(scope, "sess-a"); var futureNow = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + 100_000; - var swept = await service.SweepTimeoutsAsync(TenantId, AppId, futureNow); + var swept = await service.SweepTimeoutsAsync(futureNow); var state = await service.GetAsync(scope); // Assert @@ -298,9 +292,9 @@ public async Task CountOnlineAsync_ShouldExcludeBlockedPlayers() await service.SetOnlineAsync(CreatePlayerScope(PlayerTwo), "sess-b"); // Act - var before = await service.CountOnlineAsync(TenantId, AppId); + var before = await service.CountOnlineAsync(); await service.MarkBlockedAsync(CreatePlayerScope(PlayerOne)); - var after = await service.CountOnlineAsync(TenantId, AppId); + var after = await service.CountOnlineAsync(); // Assert Assert.Equal(2, before); @@ -384,8 +378,6 @@ public async Task SweepTimeoutsAsync_BoundaryEqualFullBatch_ShouldTerminate() { await store.SetAsync(new OnlinePresenceRecord { - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, PlayerId = playerId, SessionId = "sess-" + playerId, @@ -395,13 +387,13 @@ await store.SetAsync(new OnlinePresenceRecord } // Act:清扫不得挂起。 - var sweepTask = service.SweepTimeoutsAsync(TenantId, AppId, now); + var sweepTask = service.SweepTimeoutsAsync(now); var completed = await Task.WhenAny(sweepTask, Task.Delay(5000)); // Assert:边界记录本轮不计入清扫量,但时钟推进后应被清扫。 Assert.Same(sweepTask, completed); Assert.Equal(0, await sweepTask); - Assert.Equal(2, await service.SweepTimeoutsAsync(TenantId, AppId, now + 1)); + Assert.Equal(2, await service.SweepTimeoutsAsync(now + 1)); } /// @@ -411,7 +403,7 @@ await store.SetAsync(new OnlinePresenceRecord /// 作用域实例。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlinePunishmentServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlinePunishmentServiceTests.cs index d92cab011..15d212325 100644 --- a/Tests/GameFrameX.Tests/Online/OnlinePunishmentServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlinePunishmentServiceTests.cs @@ -45,11 +45,6 @@ namespace GameFrameX.Tests.Online /// public class OnlinePunishmentServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; /// 测试用被处罚玩家标识。 private const long PlayerId = 1002; @@ -67,7 +62,7 @@ public async Task ApplyAsync_ShouldStorePermanentPunishmentVisibleInActiveList() var service = CreateService(out var recorder); // Act - var outcome = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId, AdminCaseId = "ADM-9" }); + var outcome = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId, AdminCaseId = "ADM-9" }); // Assert Assert.True(outcome.IsSuccess); @@ -78,7 +73,7 @@ public async Task ApplyAsync_ShouldStorePermanentPunishmentVisibleInActiveList() Assert.False(outcome.Data.Revoked); Assert.Equal(0, outcome.Data.ExpiresAtTime); - var active = await service.ListActiveAsync(TenantId, AppId, PlayerId); + var active = await service.ListActiveAsync(PlayerId); Assert.True(active.IsSuccess); Assert.Single(active.Data); Assert.Equal(outcome.Data.PunishmentId, active.Data[0].PunishmentId); @@ -99,13 +94,13 @@ public async Task ListActiveAsync_ShouldRespectEffectiveWindow() var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var effective = now - 1000; var expires = now + 60000; - var applied = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = effective, ExpiresAtTime = expires, AdminId = AdminId }); + var applied = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = effective, ExpiresAtTime = expires, AdminId = AdminId }); Assert.True(applied.IsSuccess); // Act & Assert - var beforeEffective = await service.ListActiveAsync(TenantId, AppId, PlayerId, effective - 1000); - var duringWindow = await service.ListActiveAsync(TenantId, AppId, PlayerId, now); - var afterExpiry = await service.ListActiveAsync(TenantId, AppId, PlayerId, expires + 1000); + var beforeEffective = await service.ListActiveAsync(PlayerId, effective - 1000); + var duringWindow = await service.ListActiveAsync(PlayerId, now); + var afterExpiry = await service.ListActiveAsync(PlayerId, expires + 1000); Assert.Empty(beforeEffective.Data); Assert.Single(duringWindow.Data); @@ -123,8 +118,8 @@ public async Task ApplyAsync_WhenExpiryNotAfterEffective_ShouldDenyAsInvalid() var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // Act - var equal = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = now, ExpiresAtTime = now, AdminId = AdminId }); - var earlier = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = now, ExpiresAtTime = now - 1000, AdminId = AdminId }); + var equal = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = now, ExpiresAtTime = now, AdminId = AdminId }); + var earlier = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = now, ExpiresAtTime = now - 1000, AdminId = AdminId }); // Assert Assert.False(equal.IsSuccess); @@ -143,8 +138,8 @@ public async Task ApplyAsync_WhenReasonOrAdminMissing_ShouldDenyAsInvalid() var service = CreateService(out _); // Act - var noReason = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = " ", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); - var noAdmin = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = 0 }); + var noReason = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = " ", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); + var noAdmin = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = 0 }); // Assert Assert.False(noReason.IsSuccess); @@ -163,12 +158,9 @@ public async Task ApplyAsync_WhenLocatorInvalid_ShouldDenyAsInvalid() var service = CreateService(out _); // Act - var noTenant = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = 0, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); - var noPlayer = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = 0, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); + var noPlayer = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = 0, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); // Assert - Assert.False(noTenant.IsSuccess); - Assert.Equal(OnlineErrorCode.ParameterInvalid, noTenant.Code); Assert.False(noPlayer.IsSuccess); Assert.Equal(OnlineErrorCode.ParameterInvalid, noPlayer.Code); } @@ -181,11 +173,11 @@ public async Task RevokeAsync_ShouldRemoveFromActiveButKeepHistoryAndPublishEven { // Arrange var service = CreateService(out var recorder); - var applied = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); + var applied = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); Assert.True(applied.IsSuccess); // Act - var revoked = await service.RevokeAsync(TenantId, AppId, applied.Data.PunishmentId, AdminId); + var revoked = await service.RevokeAsync(applied.Data.PunishmentId, AdminId); // Assert Assert.True(revoked.IsSuccess); @@ -193,10 +185,10 @@ public async Task RevokeAsync_ShouldRemoveFromActiveButKeepHistoryAndPublishEven Assert.Equal(AdminId, revoked.Data.RevokedByAdminId); Assert.True(revoked.Data.RevokedAtTime > 0); - var active = await service.ListActiveAsync(TenantId, AppId, PlayerId); + var active = await service.ListActiveAsync(PlayerId); Assert.Empty(active.Data); - var history = await service.ListHistoryAsync(TenantId, AppId, PlayerId); + var history = await service.ListHistoryAsync(PlayerId); Assert.Single(history.Data); Assert.True(history.Data[0].Revoked); @@ -215,7 +207,7 @@ public async Task RevokeAsync_WhenPunishmentMissing_ShouldReturnResourceNotFound var service = CreateService(out _); // Act - var outcome = await service.RevokeAsync(TenantId, AppId, "pun-missing", AdminId); + var outcome = await service.RevokeAsync("pun-missing", AdminId); // Assert Assert.False(outcome.IsSuccess); @@ -230,11 +222,11 @@ public async Task RevokeAsync_WhenAdminMissing_ShouldDenyAsInvalid() { // Arrange var service = CreateService(out _); - var applied = await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); + var applied = await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); Assert.True(applied.IsSuccess); // Act - var outcome = await service.RevokeAsync(TenantId, AppId, applied.Data.PunishmentId, 0); + var outcome = await service.RevokeAsync(applied.Data.PunishmentId, 0); // Assert Assert.False(outcome.IsSuccess); @@ -250,11 +242,11 @@ public async Task ListHistoryAsync_ShouldReturnPunishmentsRegardlessOfWindow() // Arrange var service = CreateService(out _); var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - Assert.True((await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); - Assert.True((await service.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "历史封禁", EffectiveAtTime = now - 100000, ExpiresAtTime = now - 50000, AdminId = AdminId })).IsSuccess); + Assert.True((await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); + Assert.True((await service.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerId, Kind = OnlinePunishmentKind.Ban, Reason = "历史封禁", EffectiveAtTime = now - 100000, ExpiresAtTime = now - 50000, AdminId = AdminId })).IsSuccess); // Act - var history = await service.ListHistoryAsync(TenantId, AppId, PlayerId); + var history = await service.ListHistoryAsync(PlayerId); // Assert Assert.True(history.IsSuccess); @@ -271,8 +263,6 @@ public void IsActiveAt_ShouldJudgeWindowAndRevocation() var punishment = new OnlinePunishment { PunishmentId = "pun-1", - TenantId = TenantId, - AppId = AppId, PlayerId = PlayerId, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", diff --git a/Tests/GameFrameX.Tests/Online/OnlineRateLimiterSweepTests.cs b/Tests/GameFrameX.Tests/Online/OnlineRateLimiterSweepTests.cs index 475d1f41f..1b13bcc46 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineRateLimiterSweepTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineRateLimiterSweepTests.cs @@ -47,20 +47,20 @@ public void ChatLimiter_SweepExpired_RemovesExpiredKeepsActive() var limiter = new OnlineChatRateLimiter(3, 10); // 玩家 1 在旧窗口发过消息(已过期),玩家 2 在当前窗口活跃。 - Assert.True(limiter.TryAcquire(1, 1, 1, "global", BaseTime)); - Assert.True(limiter.TryAcquire(1, 1, 2, "global", BaseTime + 5_000)); + Assert.True(limiter.TryAcquire(1, "global", BaseTime)); + Assert.True(limiter.TryAcquire(2, "global", BaseTime + 5_000)); var removed = limiter.SweepExpired(BaseTime + 10_000); Assert.Equal(1, removed); // 玩家 2 的桶被保留:同窗口继续计数(1→3)并在超限时拒绝。 - Assert.True(limiter.TryAcquire(1, 1, 2, "global", BaseTime + 5_000 + 1)); - Assert.True(limiter.TryAcquire(1, 1, 2, "global", BaseTime + 5_000 + 2)); - Assert.False(limiter.TryAcquire(1, 1, 2, "global", BaseTime + 5_000 + 3)); + Assert.True(limiter.TryAcquire(2, "global", BaseTime + 5_000 + 1)); + Assert.True(limiter.TryAcquire(2, "global", BaseTime + 5_000 + 2)); + Assert.False(limiter.TryAcquire(2, "global", BaseTime + 5_000 + 3)); // 玩家 1 的桶已被删除:过期窗口后重新从 1 计数。 - Assert.True(limiter.TryAcquire(1, 1, 1, "global", BaseTime + 10_001)); + Assert.True(limiter.TryAcquire(1, "global", BaseTime + 10_001)); // 全部过期后清扫清零。 Assert.Equal(2, limiter.SweepExpired(BaseTime + 30_000)); @@ -72,14 +72,14 @@ public void MatchLimiter_SweepExpired_RemovesExpiredKeepsActive() { var limiter = new OnlineMatchRateLimiter(2, 10); - Assert.True(limiter.TryAcquire(1, 1, 1, BaseTime)); - Assert.True(limiter.TryAcquire(1, 1, 2, BaseTime + 5_000)); + Assert.True(limiter.TryAcquire(1, BaseTime)); + Assert.True(limiter.TryAcquire(2, BaseTime + 5_000)); var removed = limiter.SweepExpired(BaseTime + 10_000); Assert.Equal(1, removed); - Assert.True(limiter.TryAcquire(1, 1, 2, BaseTime + 5_000 + 1)); - Assert.False(limiter.TryAcquire(1, 1, 2, BaseTime + 5_000 + 2)); + Assert.True(limiter.TryAcquire(2, BaseTime + 5_000 + 1)); + Assert.False(limiter.TryAcquire(2, BaseTime + 5_000 + 2)); } [Fact] @@ -87,14 +87,14 @@ public void LeaderboardLimiter_SweepExpired_RemovesExpiredKeepsActive() { var limiter = new OnlineLeaderboardRateLimiter(2, 10); - Assert.True(limiter.TryAcquire(1, 1, 1, BaseTime)); - Assert.True(limiter.TryAcquire(1, 1, 2, BaseTime + 5_000)); + Assert.True(limiter.TryAcquire(1, BaseTime)); + Assert.True(limiter.TryAcquire(2, BaseTime + 5_000)); var removed = limiter.SweepExpired(BaseTime + 10_000); Assert.Equal(1, removed); - Assert.True(limiter.TryAcquire(1, 1, 2, BaseTime + 5_000 + 1)); - Assert.False(limiter.TryAcquire(1, 1, 2, BaseTime + 5_000 + 2)); + Assert.True(limiter.TryAcquire(2, BaseTime + 5_000 + 1)); + Assert.False(limiter.TryAcquire(2, BaseTime + 5_000 + 2)); } [Fact] @@ -103,19 +103,19 @@ public void TryAcquire_SweepsExpiredBucketsAutomatically_AfterThrottleInterval() var limiter = new OnlineMatchRateLimiter(2, 1); // 稀疏的一次性玩家:只来一次,之后不再出现——这类键正是内存泄漏源。 - Assert.True(limiter.TryAcquire(1, 1, 100 + 0, BaseTime)); + Assert.True(limiter.TryAcquire(100 + 0, BaseTime)); // 清扫间隔为 max(window, 60s) = 60s;窗口 1s 早已过期。 // 距上次清扫不足间隔时不触发全量清扫,但单键访问路径仍按窗口重建,行为不受影响。 - Assert.True(limiter.TryAcquire(1, 1, 200, BaseTime + 10_000)); + Assert.True(limiter.TryAcquire(200, BaseTime + 10_000)); // 跨过清扫间隔后,任何流量都会推进全量回收。 - Assert.True(limiter.TryAcquire(1, 1, 300, BaseTime + 60_000)); + Assert.True(limiter.TryAcquire(300, BaseTime + 60_000)); // 清扫后历史一次性玩家重新从 1 计数(桶已被物理删除)。 - Assert.True(limiter.TryAcquire(1, 1, 100, BaseTime + 60_001)); - Assert.True(limiter.TryAcquire(1, 1, 100, BaseTime + 60_002)); - Assert.False(limiter.TryAcquire(1, 1, 100, BaseTime + 60_003)); + Assert.True(limiter.TryAcquire(100, BaseTime + 60_001)); + Assert.True(limiter.TryAcquire(100, BaseTime + 60_002)); + Assert.False(limiter.TryAcquire(100, BaseTime + 60_003)); } [Fact] @@ -123,11 +123,11 @@ public void SweepExpired_DoesNotChangeRateLimitSemantics_WithinWindow() { var limiter = new OnlineChatRateLimiter(2, 10); - Assert.True(limiter.TryAcquire(1, 1, 1, "private", BaseTime)); + Assert.True(limiter.TryAcquire(1, "private", BaseTime)); // 窗口内的清扫必须保留活跃桶(不会把在窗计数误删)。 Assert.Equal(0, limiter.SweepExpired(BaseTime + 1)); - Assert.True(limiter.TryAcquire(1, 1, 1, "private", BaseTime + 2)); - Assert.False(limiter.TryAcquire(1, 1, 1, "private", BaseTime + 3)); + Assert.True(limiter.TryAcquire(1, "private", BaseTime + 2)); + Assert.False(limiter.TryAcquire(1, "private", BaseTime + 3)); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineReportRateLimiterTests.cs b/Tests/GameFrameX.Tests/Online/OnlineReportRateLimiterTests.cs index 06b40d218..a237c5e9d 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineReportRateLimiterTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineReportRateLimiterTests.cs @@ -8,38 +8,36 @@ namespace GameFrameX.Tests.Online { /// - /// 举报提交限流器回归:双固定窗口额度、边界重开、失败不烧额度、三维隔离、并发与过期清扫。 + /// 举报提交限流器回归:双固定窗口额度、边界重开、失败不烧额度、按举报人隔离、并发与过期清扫。 /// public sealed class OnlineReportRateLimiterTests { - private const long TenantId = 1; - private const long AppId = 2; private const long ReporterId = 100; [Fact] public void TryAcquire_WhenWithinBothWindows_ShouldAllow() { var limiter = new OnlineReportRateLimiter(3, 10); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 1000)); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 2000)); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 3000)); + Assert.True(limiter.TryAcquire(ReporterId, 1000)); + Assert.True(limiter.TryAcquire(ReporterId, 2000)); + Assert.True(limiter.TryAcquire(ReporterId, 3000)); } [Fact] public void TryAcquire_WhenMinuteLimitExceeded_ShouldRejectWithoutTouchingDayWindow() { var limiter = new OnlineReportRateLimiter(2, 10); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 1000)); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 2000)); - Assert.False(limiter.TryAcquire(TenantId, AppId, ReporterId, 3000)); + Assert.True(limiter.TryAcquire(ReporterId, 1000)); + Assert.True(limiter.TryAcquire(ReporterId, 2000)); + Assert.False(limiter.TryAcquire(ReporterId, 3000)); // 拒绝不消耗日额度:分钟窗过期后仍可继续提交,直到日额度用尽。 var minuteWindowStart = 1000; var afterMinuteWindow = minuteWindowStart + 60000L; - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, afterMinuteWindow)); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, afterMinuteWindow + 1000)); - Assert.False(limiter.TryAcquire(TenantId, AppId, ReporterId, afterMinuteWindow + 2000)); - Assert.False(limiter.TryAcquire(TenantId, AppId, ReporterId, afterMinuteWindow + 3000)); + Assert.True(limiter.TryAcquire(ReporterId, afterMinuteWindow)); + Assert.True(limiter.TryAcquire(ReporterId, afterMinuteWindow + 1000)); + Assert.False(limiter.TryAcquire(ReporterId, afterMinuteWindow + 2000)); + Assert.False(limiter.TryAcquire(ReporterId, afterMinuteWindow + 3000)); } [Fact] @@ -47,25 +45,23 @@ public void TryAcquire_WhenDayLimitExceeded_ShouldRejectEvenAfterMinuteWindowRol { // 两个分钟窗共消耗 4 次,日额度 3 已用尽。 var limiter = new OnlineReportRateLimiter(2, 3); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 1000)); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 2000)); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 61000)); - Assert.False(limiter.TryAcquire(TenantId, AppId, ReporterId, 62000)); + Assert.True(limiter.TryAcquire(ReporterId, 1000)); + Assert.True(limiter.TryAcquire(ReporterId, 2000)); + Assert.True(limiter.TryAcquire(ReporterId, 61000)); + Assert.False(limiter.TryAcquire(ReporterId, 62000)); // 日窗整体过期后额度重开。 var dayWindowStart = 1000; - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, dayWindowStart + 86400000L)); + Assert.True(limiter.TryAcquire(ReporterId, dayWindowStart + 86400000L)); } [Fact] - public void TryAcquire_ShouldIsolateByTenantAppAndReporter() + public void TryAcquire_ShouldIsolateByReporter() { var limiter = new OnlineReportRateLimiter(1, 1); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 1000)); - Assert.False(limiter.TryAcquire(TenantId, AppId, ReporterId, 1000)); - Assert.True(limiter.TryAcquire(TenantId + 1, AppId, ReporterId, 1000)); - Assert.True(limiter.TryAcquire(TenantId, AppId + 1, ReporterId, 1000)); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId + 1, 1000)); + Assert.True(limiter.TryAcquire(ReporterId, 1000)); + Assert.False(limiter.TryAcquire(ReporterId, 1000)); + Assert.True(limiter.TryAcquire(ReporterId + 1, 1000)); } [Fact] @@ -80,7 +76,7 @@ public void TryAcquire_UnderConcurrency_ShouldNotExceedMinuteLimit() workers[index] = Task.Run(() => { gate.Wait(); - if (limiter.TryAcquire(TenantId, AppId, ReporterId, 1000)) + if (limiter.TryAcquire(ReporterId, 1000)) { Interlocked.Increment(ref allowed); } @@ -96,14 +92,14 @@ public void TryAcquire_UnderConcurrency_ShouldNotExceedMinuteLimit() public void SweepExpired_ShouldRemoveOnlyFullyExpiredBuckets() { var limiter = new OnlineReportRateLimiter(5, 50); - limiter.TryAcquire(TenantId, AppId, ReporterId, 1000); + limiter.TryAcquire(ReporterId, 1000); // 分钟窗已过、日窗未过:不得删除(删除即凭空重置日额度)。 Assert.Equal(0, limiter.SweepExpired(1000 + 60000L)); // 两窗均过期:可删除,且删除后额度重开。 Assert.Equal(1, limiter.SweepExpired(1000 + 86400000L)); - Assert.True(limiter.TryAcquire(TenantId, AppId, ReporterId, 1000 + 86400000L)); + Assert.True(limiter.TryAcquire(ReporterId, 1000 + 86400000L)); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineReportStoreUniquenessTests.cs b/Tests/GameFrameX.Tests/Online/OnlineReportStoreUniquenessTests.cs index 8e2b8e89d..58378cafd 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineReportStoreUniquenessTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineReportStoreUniquenessTests.cs @@ -8,12 +8,10 @@ namespace GameFrameX.Tests.Online { /// - /// 举报存储组合唯一性回归:五维组合去重、Reviewing 占位、终态释放、CAS 冲突、身份不可改与并发新建。 + /// 举报存储组合唯一性回归:三维组合去重、Reviewing 占位、终态释放、CAS 冲突、身份不可改与并发新建。 /// public sealed class OnlineReportStoreUniquenessTests { - private const long TenantId = 1; - private const long AppId = 2; private const long ReporterId = 100; private const long ReportedPlayerId = 200; @@ -36,15 +34,11 @@ public async Task SaveIfAbsentAsync_WhenDifferentCombinationDimension_ShouldCrea var otherTarget = await store.SaveIfAbsentAsync(CreateCase("rpt-2", reportedPlayerId: ReportedPlayerId + 1)); var otherScene = await store.SaveIfAbsentAsync(CreateCase("rpt-3", scene: OnlineReportScene.Chat, channelId: "chan-1")); var otherReporter = await store.SaveIfAbsentAsync(CreateCase("rpt-4", reporterId: ReporterId + 1)); - var otherScope = await store.SaveIfAbsentAsync(CreateCase("rpt-5", tenantId: TenantId + 1)); - var otherApp = await store.SaveIfAbsentAsync(CreateCase("rpt-6", appId: AppId + 1)); - Assert.Equal(4, (await store.ListByReporterAsync(TenantId, AppId, ReporterId)).Count + (await store.ListByReporterAsync(TenantId + 1, AppId, ReporterId)).Count); + Assert.Equal(4, (await store.ListByReporterAsync(ReporterId)).Count + (await store.ListByReporterAsync(ReporterId + 1)).Count); Assert.NotEqual("rpt-1", otherTarget.ReportId); Assert.NotEqual("rpt-1", otherScene.ReportId); Assert.NotEqual("rpt-1", otherReporter.ReportId); - Assert.NotEqual("rpt-1", otherScope.ReportId); - Assert.NotEqual("rpt-1", otherApp.ReportId); } [Fact] @@ -114,7 +108,7 @@ public async Task ReplaceAsync_WhenIdentityChanged_ShouldFail() tampered.State = OnlineReportState.Reviewing; Assert.Null(await store.ReplaceAsync(tampered, OnlineReportState.Submitted)); - var unchanged = await store.FindAsync(TenantId, AppId, "rpt-1"); + var unchanged = await store.FindAsync("rpt-1"); Assert.Equal(OnlineReportState.Submitted, unchanged.State); } @@ -143,13 +137,11 @@ public async Task ReplaceAsync_WhenStaleTerminalUpdate_ShouldNotReleaseNewCaseSl /// /// 构造测试案件。 /// - private static OnlineReportCase CreateCase(string reportId, long tenantId = TenantId, long appId = AppId, long reporterId = ReporterId, long reportedPlayerId = ReportedPlayerId, OnlineReportScene scene = OnlineReportScene.Profile, string channelId = "", string evidence = "") + private static OnlineReportCase CreateCase(string reportId, long reporterId = ReporterId, long reportedPlayerId = ReportedPlayerId, OnlineReportScene scene = OnlineReportScene.Profile, string channelId = "", string evidence = "") { return new OnlineReportCase { ReportId = reportId, - TenantId = tenantId, - AppId = appId, ReporterId = reporterId, ReportedPlayerId = reportedPlayerId, Scene = scene, diff --git a/Tests/GameFrameX.Tests/Online/OnlineReportSubmissionProtectionTests.cs b/Tests/GameFrameX.Tests/Online/OnlineReportSubmissionProtectionTests.cs index 33e16bb6c..78e21f978 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineReportSubmissionProtectionTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineReportSubmissionProtectionTests.cs @@ -14,8 +14,6 @@ namespace GameFrameX.Tests.Online /// public sealed class OnlineReportSubmissionProtectionTests { - private const long TenantId = 1; - private const long AppId = 2; private const long PlayerOne = 100; private const long PlayerTwo = 200; @@ -52,7 +50,7 @@ public async Task SubmissionAboveMinuteLimit_ShouldRejectWithoutCaseOrEvent() Assert.Equal(OnlineErrorCode.RateLimitExceeded, last.Code); Assert.Equal(5, recorder.Filter(OnlineSocialEvents.ReportChanged).Count); - var cases = await reportStore.ListByReporterAsync(TenantId, AppId, PlayerOne); + var cases = await reportStore.ListByReporterAsync(PlayerOne); Assert.Equal(5, cases.Count); } @@ -86,7 +84,7 @@ private static OnlineSocialDecisionService CreateService(out OnlineEventRecorder /// 创建玩家作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, 1, playerId); + return new OnlineScope(1, playerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineRockPaperScissorsGameTests.cs b/Tests/GameFrameX.Tests/Online/OnlineRockPaperScissorsGameTests.cs index 6dff18e86..038b99898 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineRockPaperScissorsGameTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineRockPaperScissorsGameTests.cs @@ -299,8 +299,6 @@ private static OnlineMatch BuildMatch() { var match = new OnlineMatch { - TenantId = 1, - AppId = 10, ServerId = 100, MatchId = "match-1", Mode = OnlineRockPaperScissorsGame.MatchMode, diff --git a/Tests/GameFrameX.Tests/Online/OnlineRowKeyShapeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineRowKeyShapeTests.cs new file mode 100644 index 000000000..a1209b9ed --- /dev/null +++ b/Tests/GameFrameX.Tests/Online/OnlineRowKeyShapeTests.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 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 see the LICENSE file at 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/ +// ========================================================================================== + +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Keys; +using GameFrameX.Capability.Online.Abstractions.Scope; +using Xunit; + +namespace GameFrameX.Tests.Online +{ + /// + /// C462 单键化键形断言(D4 裁决铁律):全局域键(好友/身份/设备/玩家存储/钱包/账本/库存/资产去重/对局结算) + /// 键内不得出现 ServerId 位;区服维度由行实体 ServerId 快照列承载;作用域键与守卫只剩区服位。 + /// + public class OnlineRowKeyShapeTests + { + /// + /// 好友无向对键 = friend:{低玩家}:{高玩家},两位玩家位、无任何区服位(跨服好友天然成立,合服零操作)。 + /// + [Fact] + public void Friendship_GlobalDomainKey_ShouldContainPlayerPairOnly() + { + Assert.Equal("friend:100:200", OnlineRowKey.Friendship(100, 200)); + Assert.Equal("friend:200:100", OnlineRowKey.Friendship(200, 100)); + } + + /// + /// 身份/设备/玩家存储键 = 主体自身位组成,无区服位。 + /// + [Fact] + public void Identity_Device_Storage_GlobalDomainKeys_ShouldContainNoServerSegment() + { + Assert.Equal("3:device-token-abc", OnlineRowKey.Identity(3, "device-token-abc")); + Assert.Equal("5001:device-xyz", OnlineRowKey.PlayerDevice(5001, "device-xyz")); + Assert.Equal("5001:inventory:slot-1", OnlineRowKey.PlayerStorage(5001, "inventory", "slot-1")); + } + + /// + /// 钱包/库存/账本序/资产去重键 = 玩家位 + 资产位,无区服位。 + /// + [Fact] + public void Assets_GlobalDomainKeys_ShouldContainNoServerSegment() + { + Assert.Equal("5001", OnlineRowKey.LedgerSequence(5001)); + Assert.Equal("5001:gold", OnlineRowKey.WalletAccount(5001, "gold")); + Assert.Equal("5001:item-sword", OnlineRowKey.InventoryStack(5001, "item-sword")); + Assert.Equal("5001:c:gold", OnlineRowKey.AssetDedup(5001, true, "gold")); + Assert.Equal("5001:i:item-sword", OnlineRowKey.AssetDedup(5001, false, "item-sword")); + } + + /// + /// 对局结算键 = 对局标识本身(match-{Guid:N} 全局唯一消解跨服碰撞;区服维度由行实体 ServerId 快照列承载)。 + /// + [Fact] + public void MatchResult_ServerDomainKey_ShouldEqualMatchId() + { + Assert.Equal("match-0123456789abcdef0123456789abcdef", OnlineRowKey.MatchResult("match-0123456789abcdef0123456789abcdef")); + } + + /// + /// 键 schema 代际常量可追溯:单键键形首代 = 1(键形演进须递增并走迁移评审)。 + /// + [Fact] + public void RowKeySchemaVersion_ShouldBeFirstGeneration() + { + Assert.Equal(1, OnlineRowKey.RowKeySchemaVersion); + } + + /// + /// 作用域幂等绑定键 = online:{区服}[:{玩家}],无租户位/App 位。 + /// + [Fact] + public void ToScopeKey_ShouldContainServerOnly() + { + var scope = new OnlineScope(7); + Assert.Equal("online:7", scope.ToScopeKey(false)); + Assert.Equal("online:7:9", new OnlineScope(7, 9).ToScopeKey(true)); + } + + /// + /// 守卫只剩区服判定:跨服拒绝映射 3004;任一侧缺失映射 3005;不再产生 3002/3003(保留位)。 + /// + [Fact] + public void Guard_ShouldOnlyJudgeServerScope() + { + Assert.Null(OnlineScopeGuard.Validate(new OnlineScope(7), new OnlineScope(7, 9))); + Assert.Equal(OnlineErrorCode.ServerScopeDenied, OnlineScopeGuard.Validate(new OnlineScope(7), new OnlineScope(8))); + Assert.Equal(OnlineErrorCode.ScopeMissing, OnlineScopeGuard.Validate(new OnlineScope(0), new OnlineScope(7))); + Assert.Equal(OnlineErrorCode.ScopeMissing, OnlineScopeGuard.Validate(new OnlineScope(7), null)); + } + } +} diff --git a/Tests/GameFrameX.Tests/Online/OnlineScopeGuardTests.cs b/Tests/GameFrameX.Tests/Online/OnlineScopeGuardTests.cs index 56c4f1d86..34b428833 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineScopeGuardTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineScopeGuardTests.cs @@ -34,7 +34,7 @@ namespace GameFrameX.Tests.Online { /// - /// OnlineScopeGuard 作用域越界判定测试(跨租户/跨 App/跨服稳定拒绝 3xxx)。 + /// OnlineScopeGuard 作用域越界判定测试(跨服 / 缺失稳定拒绝 3xxx)。 /// public class OnlineScopeGuardTests { @@ -45,8 +45,8 @@ public class OnlineScopeGuardTests public void Validate_WithMatchingScope_ShouldAccept() { // Arrange - var target = new OnlineScope(1, 10, 100, 10001); - var actual = new OnlineScope(1, 10, 100, 10001); + var target = new OnlineScope(100, 10001); + var actual = new OnlineScope(100, 10001); // Act var error = OnlineScopeGuard.Validate(target, actual); @@ -55,40 +55,6 @@ public void Validate_WithMatchingScope_ShouldAccept() Assert.Null(error); } - /// - /// 验证租户不一致映射跨租户拒绝码。 - /// - [Fact] - public void Validate_WithDifferentTenant_ShouldReturnCrossTenantDenied() - { - // Arrange - var target = new OnlineScope(2, 10, 100); - var actual = new OnlineScope(1, 10, 100); - - // Act - var error = OnlineScopeGuard.Validate(target, actual); - - // Assert - Assert.Equal(OnlineErrorCode.CrossTenantDenied, error); - } - - /// - /// 验证 App 不一致映射跨 App 拒绝码。 - /// - [Fact] - public void Validate_WithDifferentApp_ShouldReturnCrossAppDenied() - { - // Arrange - var target = new OnlineScope(1, 11, 100); - var actual = new OnlineScope(1, 10, 100); - - // Act - var error = OnlineScopeGuard.Validate(target, actual); - - // Assert - Assert.Equal(OnlineErrorCode.CrossAppDenied, error); - } - /// /// 验证区服不一致映射区服作用域拒绝码。 /// @@ -96,8 +62,8 @@ public void Validate_WithDifferentApp_ShouldReturnCrossAppDenied() public void Validate_WithDifferentServer_ShouldReturnServerScopeDenied() { // Arrange - var target = new OnlineScope(1, 10, 101); - var actual = new OnlineScope(1, 10, 100); + var target = new OnlineScope(101); + var actual = new OnlineScope(100); // Act var error = OnlineScopeGuard.Validate(target, actual); @@ -107,24 +73,22 @@ public void Validate_WithDifferentServer_ShouldReturnServerScopeDenied() } /// - /// 验证租户优先于 App/区服判定(多层不一致时按数据隔离根边界报告)。 + /// 验证单键化后守卫只映射跨服(3004)与缺失(3005)两种拒绝;3002/3003 保留枚举位但不再产生。 /// [Fact] - public void Validate_WithMultipleMismatches_ShouldReportTenantFirst() + public void Validate_WithAnyScopeMismatch_ShouldNeverProduceCrossTenantOrCrossApp() { - // Arrange - var target = new OnlineScope(2, 11, 101); - var actual = new OnlineScope(1, 10, 100); - - // Act - var error = OnlineScopeGuard.Validate(target, actual); + // Arrange:玩家位差异不是越界(同区服不同主体合法);区服位差异唯一越界源。 + var sameServerDifferentPlayer = OnlineScopeGuard.Validate(new OnlineScope(100), new OnlineScope(100, 10001)); + var crossServer = OnlineScopeGuard.Validate(new OnlineScope(101), new OnlineScope(100)); // Assert - Assert.Equal(OnlineErrorCode.CrossTenantDenied, error); + Assert.Null(sameServerDifferentPlayer); + Assert.Equal(OnlineErrorCode.ServerScopeDenied, crossServer); } /// - /// 验证缺失任一作用域(null 或三元组不完整)映射作用域缺失码。 + /// 验证缺失任一作用域(null 或区服位非正值)映射作用域缺失码。 /// [Theory] [InlineData(true, false)] @@ -132,8 +96,8 @@ public void Validate_WithMultipleMismatches_ShouldReportTenantFirst() public void Validate_WithMissingScope_ShouldReturnScopeMissing(bool targetNull, bool actualNull) { // Arrange - var target = targetNull ? null : new OnlineScope(1, 10, 100); - var actual = actualNull ? null : new OnlineScope(1, 10, 100); + var target = targetNull ? null : new OnlineScope(100); + var actual = actualNull ? null : new OnlineScope(100); // Act var error = OnlineScopeGuard.Validate(target, actual); diff --git a/Tests/GameFrameX.Tests/Online/OnlineScopeResolverTests.cs b/Tests/GameFrameX.Tests/Online/OnlineScopeResolverTests.cs index 99a2d5265..1c358cbd8 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineScopeResolverTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineScopeResolverTests.cs @@ -46,11 +46,9 @@ public class OnlineScopeResolverTests public void TryResolve_WithCamelCaseParameters_ShouldReturnAuthorizedScope() { // Arrange - var authorized = new OnlineScope(1, 10, 100, 10001); + var authorized = new OnlineScope(100, 10001); var parameters = new Dictionary { - { "tenantId", 1L }, - { "appId", 10L }, { "serverId", 100L }, }; @@ -60,8 +58,6 @@ public void TryResolve_WithCamelCaseParameters_ShouldReturnAuthorizedScope() // Assert Assert.Equal(OnlineErrorCode.None, error); Assert.NotNull(resolved); - Assert.Equal(1, resolved.TenantId); - Assert.Equal(10, resolved.AppId); Assert.Equal(100, resolved.ServerId); Assert.Equal(10001, resolved.PlayerId); } @@ -73,11 +69,9 @@ public void TryResolve_WithCamelCaseParameters_ShouldReturnAuthorizedScope() public void TryResolve_WithPascalCaseParameters_ShouldMatchCaseInsensitively() { // Arrange - var authorized = new OnlineScope(2, 20, 200); + var authorized = new OnlineScope(200); var parameters = new Dictionary { - { "TenantId", "2" }, - { "AppId", "20" }, { "ServerId", "200" }, }; @@ -87,8 +81,6 @@ public void TryResolve_WithPascalCaseParameters_ShouldMatchCaseInsensitively() // Assert Assert.Equal(OnlineErrorCode.None, error); Assert.NotNull(resolved); - Assert.Equal(2, resolved.TenantId); - Assert.Equal(20, resolved.AppId); Assert.Equal(200, resolved.ServerId); } @@ -99,11 +91,9 @@ public void TryResolve_WithPascalCaseParameters_ShouldMatchCaseInsensitively() public void TryResolve_WithForgedClientFields_ShouldEnforceAuthorizedValues() { // Arrange - var authorized = new OnlineScope(1, 10, 100, 10001); + var authorized = new OnlineScope(100, 10001); var parameters = new Dictionary { - { "tenantId", 999L }, - { "appId", 999L }, { "serverId", 999L }, }; @@ -113,8 +103,6 @@ public void TryResolve_WithForgedClientFields_ShouldEnforceAuthorizedValues() // Assert Assert.Equal(OnlineErrorCode.None, error); Assert.NotNull(resolved); - Assert.Equal(1, resolved.TenantId); - Assert.Equal(10, resolved.AppId); Assert.Equal(100, resolved.ServerId); Assert.Equal(10001, resolved.PlayerId); } @@ -133,17 +121,14 @@ public void TryResolve_WithoutAuthorizedScope_ShouldReturnScopeMissing() Assert.Null(resolved); } - /// - /// 验证鉴权上下文三元组不完整(非正值)时返回作用域缺失错误。 + /// 验证鉴权上下文区服位不完整(非正值)时返回作用域缺失错误。 /// [Theory] - [InlineData(0, 10, 100)] - [InlineData(1, 0, 100)] - [InlineData(1, 10, 0)] - public void TryResolve_WithIncompleteAuthorizedScope_ShouldReturnScopeMissing(long tenantId, long appId, long serverId) + [InlineData(0)] + public void TryResolve_WithIncompleteAuthorizedScope_ShouldReturnScopeMissing(long serverId) { // Arrange - var authorized = new OnlineScope(tenantId, appId, serverId); + var authorized = new OnlineScope(serverId); // Act var resolved = OnlineScopeResolver.TryResolve(null, authorized, out var error); @@ -160,8 +145,8 @@ public void TryResolve_WithIncompleteAuthorizedScope_ShouldReturnScopeMissing(lo public void EnforceAuthorized_ShouldAlwaysReturnAuthorizedScope() { // Arrange - var authorized = new OnlineScope(1, 10, 100, 10001); - var claimed = new OnlineScope(999, 999, 999, 999); + var authorized = new OnlineScope(100, 10001); + var claimed = new OnlineScope(999, 999); // Act var enforced = OnlineScopeResolver.EnforceAuthorized(authorized, claimed); @@ -177,15 +162,15 @@ public void EnforceAuthorized_ShouldAlwaysReturnAuthorizedScope() public void ToScopeKey_ShouldIncludePlayerSegmentOnlyWhenRequested() { // Arrange - var scope = new OnlineScope(1, 10, 100, 10001); + var scope = new OnlineScope(100, 10001); // Act var withoutPlayer = scope.ToScopeKey(false); var withPlayer = scope.ToScopeKey(true); // Assert - Assert.Equal("online:1:10:100", withoutPlayer); - Assert.Equal("online:1:10:100:10001", withPlayer); + Assert.Equal("online:100", withoutPlayer); + Assert.Equal("online:100:10001", withPlayer); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineSeasonLifecycleTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSeasonLifecycleTests.cs index c0442f997..f9165a054 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSeasonLifecycleTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSeasonLifecycleTests.cs @@ -289,11 +289,11 @@ public async Task StateMachine_IllegalTransitions_ShouldBeRejected() } /// - /// 验证反预言:跨 App 作用域访问他 App 赛季的四种操作一律与「赛季不存在」同构返回 ResourceNotFound, - /// 既不泄露存在性也不产生副作用。 + /// 验证赛季是全局域数据(单键化 D4:同键即同季)——跨区服作用域可操作同一赛季 + ///(重复开赛按状态机拒绝、结束/快照/结算作用于同一季);未知赛季仍与「不存在」同构拒绝。 /// [Fact] - public async Task CrossApp_SeasonOperations_ShouldBeResourceNotFound() + public async Task CrossServer_Operations_ShouldShareGlobalSeason() { var harness = new OnlineSeasonTestHarness(); await harness.CreateBoardAsync("board-x"); @@ -301,20 +301,23 @@ public async Task CrossApp_SeasonOperations_ShouldBeResourceNotFound() await harness.CreateSeasonAsync("s1", "board-x", OnlineSeasonTestHarness.Rule(1, 1, 100)); await harness.StartSeasonAsync("s1"); - var scope = harness.Scope(OnlineSeasonTestHarness.OtherAppId); + var scope = harness.Scope(OnlineSeasonTestHarness.OtherServerId); var start = await harness.SeasonService.StartAsync(scope, "s1", OnlineSeasonTestHarness.Now + 400); var end = await harness.SeasonService.EndAsync(scope, "s1", OnlineSeasonTestHarness.Now + 400); var snapshot = await harness.SeasonService.GetSnapshotAsync(scope, "s1"); - var settle = await harness.SeasonService.SettleAsync(scope, "s1", OnlineSeasonTestHarness.Now + 400); + var settle = await harness.SeasonService.SettleAsync(scope, "s1", OnlineSeasonTestHarness.Now + 500); + var unknownSnapshot = await harness.SeasonService.GetSnapshotAsync(scope, "s-absent"); - Assert.Equal(OnlineErrorCode.ResourceNotFound, start.Code); - Assert.Equal(OnlineErrorCode.ResourceNotFound, end.Code); - Assert.Equal(OnlineErrorCode.ResourceNotFound, snapshot.Code); - Assert.Equal(OnlineErrorCode.ResourceNotFound, settle.Code); + // 同键即同季:已开赛的季再开赛按状态机拒绝(不是按作用域拒绝);结束后的历史快照跨区服可读。 + Assert.Equal(OnlineErrorCode.StateOperationForbidden, start.Code); + Assert.True(end.IsSuccess, end.Message); + Assert.True(snapshot.IsSuccess, snapshot.Message); + Assert.True(settle.IsSuccess, settle.Message); + Assert.Equal(OnlineErrorCode.ResourceNotFound, unknownSnapshot.Code); - // 本 App 赛季不受影响:仍在进行中,榜单未被误清。 - Assert.Equal(OnlineSeasonState.Active, await harness.SeasonStateAsync("s1")); - Assert.Single(await harness.BoardEntriesAsync("board-x")); + // 全季生命周期经跨区服作用域正常推进:已结算、榜单随结算归档清空(成绩入历史快照)。 + Assert.Equal(OnlineSeasonState.Settled, await harness.SeasonStateAsync("s1")); + Assert.Empty(await harness.BoardEntriesAsync("board-x")); } /// @@ -390,7 +393,7 @@ public async Task CreateAsync_MissingBoard_ShouldBeResourceNotFound() Assert.False(result.IsSuccess); Assert.Equal(OnlineErrorCode.ResourceNotFound, result.Code); - Assert.Null(await harness.SeasonStore.FindAsync(OnlineSeasonTestHarness.TenantId, OnlineSeasonTestHarness.AppId, "s1")); + Assert.Null(await harness.SeasonStore.FindAsync("s1")); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineSeasonSettlementTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSeasonSettlementTests.cs index 1f47959ea..b5cb8e7ff 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSeasonSettlementTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSeasonSettlementTests.cs @@ -270,8 +270,6 @@ public async Task SettleAsync_MissingSnapshot_ShouldRefuseAndGrantNothing() await harness.SeasonStore.CreateAsync(new OnlineSeason { SeasonId = "s-orphan", - TenantId = OnlineSeasonTestHarness.TenantId, - AppId = OnlineSeasonTestHarness.AppId, LeaderboardId = "board-orphan", StartTime = OnlineSeasonTestHarness.Now, EndTime = OnlineSeasonTestHarness.Now + 10000, diff --git a/Tests/GameFrameX.Tests/Online/OnlineSeasonTestHarness.cs b/Tests/GameFrameX.Tests/Online/OnlineSeasonTestHarness.cs index 5e61635ef..ea5256627 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSeasonTestHarness.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSeasonTestHarness.cs @@ -52,14 +52,9 @@ namespace GameFrameX.Tests.Online /// internal sealed class OnlineSeasonTestHarness { - /// 租户标识。 - public const long TenantId = 1; + /// 另一区服标识(跨区服反预言用例)。 + public const long OtherServerId = 200; - /// App 标识。 - public const long AppId = 10; - - /// 另一 App 标识(跨 App 反预言用例)。 - public const long OtherAppId = 11; /// 区服标识。 public const long ServerId = 100; @@ -204,13 +199,13 @@ public OnlineSeasonService SeasonService } /// - /// 构造作用域(默认本 App、无玩家主体位——赛季与榜单均为 (TenantId, AppId) 作用域)。 + /// 构造作用域(默认本区服、无玩家主体位——赛季与榜单均为区服键作用域)。 /// - /// App 标识。 + /// 区服标识。 /// 作用域。 - public OnlineScope Scope(long appId = AppId) + public OnlineScope Scope(long serverId = ServerId) { - return new OnlineScope(TenantId, appId, ServerId, 0); + return new OnlineScope(serverId, 0); } /// @@ -246,8 +241,6 @@ public async Task WriteScoresAsync(string leaderboardId, params (long PlayerId, { MatchResultId = matchResultId, MatchId = matchId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Mode = OnlineRockPaperScissorsGame.MatchMode, Region = 1, @@ -319,7 +312,7 @@ public Task> SettleSeasonAsync(strin /// 赛季状态。 public async Task SeasonStateAsync(string seasonId) { - var season = await SeasonStore.FindAsync(TenantId, AppId, seasonId); + var season = await SeasonStore.FindAsync(seasonId); Assert.NotNull(season); return season.State; } @@ -331,7 +324,7 @@ public async Task SeasonStateAsync(string seasonId) /// 币余额。 public async Task BalanceAsync(long playerId) { - var wallet = await RawAssetStore.FindWalletAsync(TenantId, AppId, playerId, CoinAssetId); + var wallet = await RawAssetStore.FindWalletAsync(playerId, CoinAssetId); return wallet == null ? 0 : wallet.Balance; } @@ -342,7 +335,7 @@ public async Task BalanceAsync(long playerId) /// 账本条目数。 public async Task LedgerCountAsync(long playerId) { - var entries = await RawAssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = playerId, AfterSequenceNumber = 0, MaxCount = 1000 }); + var entries = await RawAssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = playerId, AfterSequenceNumber = 0, MaxCount = 1000 }); return entries.Count; } @@ -353,7 +346,7 @@ public async Task LedgerCountAsync(long playerId) /// 全序条目。 public async Task> BoardEntriesAsync(string leaderboardId) { - var board = await RawLeaderboardStore.FindAsync(TenantId, AppId, leaderboardId); + var board = await RawLeaderboardStore.FindAsync(leaderboardId); Assert.NotNull(board); return await RawLeaderboardStore.ListOrderedEntriesAsync(board); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineSessionManagerTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSessionManagerTests.cs index e878da950..b49c4d672 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSessionManagerTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSessionManagerTests.cs @@ -43,12 +43,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineSessionManagerTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -235,7 +229,7 @@ private static OnlineSessionManager CreateManager(out OnlineEventRecorder record /// 作用域实例。 private static OnlineScope CreatePlayerScope() { - return new OnlineScope(TenantId, AppId, ServerId, PlayerId); + return new OnlineScope(ServerId, PlayerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineSessionReconnectServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSessionReconnectServiceTests.cs index af1e43f61..3073fd02f 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSessionReconnectServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSessionReconnectServiceTests.cs @@ -15,12 +15,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineSessionReconnectServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -182,12 +176,12 @@ public async Task IssueLoginAsync(string connectio public OnlineScope PlayerScope() { - return new OnlineScope(TenantId, AppId, ServerId, PlayerId); + return new OnlineScope(ServerId, PlayerId); } public OnlineScope ScopeWithPlayer(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineSessionSingleWriterConcurrencyTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSessionSingleWriterConcurrencyTests.cs index fba3a2e07..8e7ec71cb 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSessionSingleWriterConcurrencyTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSessionSingleWriterConcurrencyTests.cs @@ -46,12 +46,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineSessionSingleWriterConcurrencyTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -72,7 +66,7 @@ public async Task ConcurrentMarkConnectedAndRefresh_BothWritesSurvive() var writeGate = new OnlineSessionWriteGate(); var sessions = new OnlineSessionManager(store, recorder, writeGate); var tokens = new OnlineSessionTokenService(store, recorder, sessions, writeGate); - var scope = new OnlineScope(TenantId, AppId, ServerId, PlayerId); + var scope = new OnlineScope(ServerId, PlayerId); var issued = await tokens.IssueSessionAsync(scope, 3600, OnlineMultiDevicePolicy.Coexist, null); Assert.True(issued.IsSuccess); @@ -117,7 +111,7 @@ private sealed class CopyingOnlineSessionStore : IOnlineSessionStore /// 并发计数(本桩不承载该路径,返回空字典)。 - public Task> CountNonTerminalByScopeAsync(long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public Task> CountNonTerminalByScopeAsync(long serverId, CancellationToken cancellationToken = default) { return Task.FromResult>(new Dictionary()); } @@ -168,15 +162,15 @@ public Task FindByTokenHashAsync(string tokenHash, CancellationTo } } - /// 列出玩家在 (TenantId, AppId) 下的非终态会话(返回副本)。 - public Task> ListActiveByPlayerAsync(long tenantId, long appId, long playerId, CancellationToken cancellationToken = default) + /// 列出玩家的非终态会话(返回副本)。 + public Task> ListActiveByPlayerAsync(long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { var result = new List(); foreach (var session in _sessions.Values) { - if (session.TenantId == tenantId && session.AppId == appId && session.PlayerId == playerId && !session.State.IsTerminal()) + if (session.PlayerId == playerId && !session.State.IsTerminal()) { result.Add(Clone(session)); } @@ -227,8 +221,6 @@ private static OnlineSession Clone(OnlineSession source) return new OnlineSession { Id = source.Id, - TenantId = source.TenantId, - AppId = source.AppId, ServerId = source.ServerId, GameAccountId = source.GameAccountId, PlayerId = source.PlayerId, diff --git a/Tests/GameFrameX.Tests/Online/OnlineSessionTokenServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSessionTokenServiceTests.cs index c63d9d19d..54fffd68e 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSessionTokenServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSessionTokenServiceTests.cs @@ -44,12 +44,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineSessionTokenServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; - /// 测试用区服标识。 private const long ServerId = 100; @@ -89,7 +83,7 @@ public async Task IssueSessionAsync_InvalidScopeOrTtl_ShouldBeRejected() var service = CreateService(out var _); // Act - var noPlayer = await service.IssueSessionAsync(new OnlineScope(TenantId, AppId, ServerId), 3600, OnlineMultiDevicePolicy.LatestWins, null); + var noPlayer = await service.IssueSessionAsync(new OnlineScope(ServerId), 3600, OnlineMultiDevicePolicy.LatestWins, null); var badTtl = await service.IssueSessionAsync(CreatePlayerScope(), 0, OnlineMultiDevicePolicy.LatestWins, null); // Assert @@ -230,7 +224,7 @@ public async Task RevokeAsync_ShouldCloseSessionAndInvalidateToken() } /// - /// 验证跨租户/跨区服刷新被拒绝(作用域一致性)。 + /// 验证跨区服刷新被拒绝(作用域一致性)。 /// [Fact] public async Task RefreshAsync_ScopeMismatch_ShouldBeDenied() @@ -241,12 +235,9 @@ public async Task RefreshAsync_ScopeMismatch_ShouldBeDenied() var issued = await service.IssueSessionAsync(scope, 3600, OnlineMultiDevicePolicy.LatestWins, null); // Act - var crossTenant = await service.RefreshSessionTokenAsync(new OnlineScope(TenantId + 1, AppId, ServerId, PlayerId), issued.Data.Token); - var crossServer = await service.RefreshSessionTokenAsync(new OnlineScope(TenantId, AppId, ServerId + 1, PlayerId), issued.Data.Token); + var crossServer = await service.RefreshSessionTokenAsync(new OnlineScope(ServerId + 1, PlayerId), issued.Data.Token); // Assert - Assert.False(crossTenant.IsSuccess); - Assert.Equal(OnlineErrorCode.CrossTenantDenied, crossTenant.Code); Assert.False(crossServer.IsSuccess); Assert.Equal(OnlineErrorCode.ServerScopeDenied, crossServer.Code); } @@ -384,7 +375,7 @@ private static OnlineSessionTokenService CreateService(out OnlineEventRecorder r /// 作用域实例。 private static OnlineScope CreatePlayerScope() { - return new OnlineScope(TenantId, AppId, ServerId, PlayerId); + return new OnlineScope(ServerId, PlayerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineSocialCapabilityPackageTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSocialCapabilityPackageTests.cs index 84a87275a..de147c2b8 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSocialCapabilityPackageTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSocialCapabilityPackageTests.cs @@ -67,7 +67,7 @@ private static void SocialClosure(CapabilityCompositionOptions options) /// 玩家作用域。 private static OnlineScope PlayerScope(long playerId) { - return new OnlineScope(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId, playerId); + return new OnlineScope(OnlineCapabilityTestHarness.ServerId, playerId); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineSocialDecisionServiceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSocialDecisionServiceTests.cs index a59901db5..330e4f832 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSocialDecisionServiceTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSocialDecisionServiceTests.cs @@ -48,11 +48,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineSocialDecisionServiceTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; /// 测试用区服标识。 private const long ServerId = 100; @@ -79,7 +74,7 @@ public async Task EvaluateAsync_WhenNoRelationAndNoPunishment_ShouldAllow() var service = CreateService(out _); // Act - var decision = await service.EvaluateAsync(TenantId, AppId, PlayerOne, PlayerTwo, OnlineSocialInteractionPurpose.DirectMessage); + var decision = await service.EvaluateAsync(PlayerOne, PlayerTwo, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.True(decision.Allowed); @@ -95,7 +90,7 @@ public async Task EvaluateAsync_WhenBothSidesAreSamePlayer_ShouldDenyAsInvalid() var service = CreateService(out _); // Act - var decision = await service.EvaluateAsync(TenantId, AppId, PlayerOne, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); + var decision = await service.EvaluateAsync(PlayerOne, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.False(decision.Allowed); @@ -112,8 +107,8 @@ public async Task EvaluateAsync_WhenPlayerIdInvalid_ShouldDenyAsInvalid() var service = CreateService(out _); // Act - var zeroFrom = await service.EvaluateAsync(TenantId, AppId, 0, PlayerTwo, OnlineSocialInteractionPurpose.DirectMessage); - var negativeTo = await service.EvaluateAsync(TenantId, AppId, PlayerOne, -1, OnlineSocialInteractionPurpose.DirectMessage); + var zeroFrom = await service.EvaluateAsync(0, PlayerTwo, OnlineSocialInteractionPurpose.DirectMessage); + var negativeTo = await service.EvaluateAsync(PlayerOne, -1, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.False(zeroFrom.Allowed); @@ -145,8 +140,8 @@ public async Task EvaluateAsync_WhenBlocked_ShouldDenyAllPurposesInBothDirection // Act & Assert foreach (var purpose in purposes) { - var forward = await service.EvaluateAsync(TenantId, AppId, PlayerOne, PlayerTwo, purpose); - var backward = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, purpose); + var forward = await service.EvaluateAsync(PlayerOne, PlayerTwo, purpose); + var backward = await service.EvaluateAsync(PlayerTwo, PlayerOne, purpose); Assert.False(forward.Allowed); Assert.False(backward.Allowed); } @@ -167,8 +162,8 @@ public async Task EvaluateAsync_WhenBlocked_ShouldNotRevealBlockDirection() Assert.True((await service.BlockAsync(CreatePlayerScope(PlayerOne), PlayerTwo)).IsSuccess); // Act - var blockedByOwner = await service.EvaluateAsync(TenantId, AppId, PlayerOne, PlayerTwo, OnlineSocialInteractionPurpose.DirectMessage); - var blockedByTarget = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); + var blockedByOwner = await service.EvaluateAsync(PlayerOne, PlayerTwo, OnlineSocialInteractionPurpose.DirectMessage); + var blockedByTarget = await service.EvaluateAsync(PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.Equal(blockedByOwner.Code, blockedByTarget.Code); @@ -199,8 +194,8 @@ public async Task EvaluateAsync_WhenDisplayMuted_ShouldNeverDenyAnyPurpose() // Act & Assert foreach (var purpose in purposes) { - var forward = await service.EvaluateAsync(TenantId, AppId, PlayerOne, PlayerTwo, purpose); - var backward = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, purpose); + var forward = await service.EvaluateAsync(PlayerOne, PlayerTwo, purpose); + var backward = await service.EvaluateAsync(PlayerTwo, PlayerOne, purpose); Assert.True(forward.Allowed); Assert.True(backward.Allowed); } @@ -217,9 +212,9 @@ public async Task EvaluateAsync_WhenPunishedWithMute_ShouldDenyOnlyDirectMessage await ApplyPunishmentAsync(graphStore, PlayerTwo, OnlinePunishmentKind.Mute); // Act - var direct = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); - var invite = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.PartyInvite); - var match = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.Matchmaking); + var direct = await service.EvaluateAsync(PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); + var invite = await service.EvaluateAsync(PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.PartyInvite); + var match = await service.EvaluateAsync(PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.Matchmaking); // Assert Assert.False(direct.Allowed); @@ -239,7 +234,7 @@ public async Task EvaluateAsync_WhenPunishedWithMute_ShouldNotBlockOthersInitiat await ApplyPunishmentAsync(graphStore, PlayerTwo, OnlinePunishmentKind.Mute); // Act - var otherInitiates = await service.EvaluateAsync(TenantId, AppId, PlayerOne, PlayerTwo, OnlineSocialInteractionPurpose.DirectMessage); + var otherInitiates = await service.EvaluateAsync(PlayerOne, PlayerTwo, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.True(otherInitiates.Allowed); @@ -264,7 +259,7 @@ public async Task EvaluateAsync_WhenPunishedWithBan_ShouldDenyAllPurposesAsAccou // Act & Assert foreach (var purpose in purposes) { - var decision = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, purpose); + var decision = await service.EvaluateAsync(PlayerTwo, PlayerOne, purpose); Assert.False(decision.Allowed); Assert.Equal(OnlineErrorCode.AccountBanned, decision.Code); } @@ -280,11 +275,11 @@ public async Task EvaluateAsync_WhenPunishmentNotEffectiveYet_ShouldAllow() var service = CreateService(out _, out var graphStore); var future = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + 60000; var punishmentService = new OnlinePunishmentService(graphStore, new OnlineEventRecorder()); - var scheduled = await punishmentService.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerTwo, Kind = OnlinePunishmentKind.Ban, Reason = "预置封禁", EffectiveAtTime = future, ExpiresAtTime = 0, AdminId = AdminId }); + var scheduled = await punishmentService.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerTwo, Kind = OnlinePunishmentKind.Ban, Reason = "预置封禁", EffectiveAtTime = future, ExpiresAtTime = 0, AdminId = AdminId }); Assert.True(scheduled.IsSuccess); // Act - var decision = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); + var decision = await service.EvaluateAsync(PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.True(decision.Allowed); @@ -300,11 +295,11 @@ public async Task EvaluateAsync_WhenPunishmentExpired_ShouldAllow() var service = CreateService(out _, out var graphStore); var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var punishmentService = new OnlinePunishmentService(graphStore, new OnlineEventRecorder()); - var expired = await punishmentService.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerTwo, Kind = OnlinePunishmentKind.Ban, Reason = "历史封禁", EffectiveAtTime = now - 100000, ExpiresAtTime = now - 50000, AdminId = AdminId }); + var expired = await punishmentService.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerTwo, Kind = OnlinePunishmentKind.Ban, Reason = "历史封禁", EffectiveAtTime = now - 100000, ExpiresAtTime = now - 50000, AdminId = AdminId }); Assert.True(expired.IsSuccess); // Act - var decision = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); + var decision = await service.EvaluateAsync(PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.True(decision.Allowed); @@ -320,11 +315,11 @@ public async Task EvaluateAsync_WhenPunishmentRevoked_ShouldAllow() var service = CreateService(out _, out var graphStore); var applied = await ApplyPunishmentAsync(graphStore, PlayerTwo, OnlinePunishmentKind.Ban); var punishmentService = new OnlinePunishmentService(graphStore, new OnlineEventRecorder()); - var revoked = await punishmentService.RevokeAsync(TenantId, AppId, applied.PunishmentId, AdminId); + var revoked = await punishmentService.RevokeAsync(applied.PunishmentId, AdminId); Assert.True(revoked.IsSuccess); // Act - var decision = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); + var decision = await service.EvaluateAsync(PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.True(decision.Allowed); @@ -347,7 +342,7 @@ public async Task EvaluateAsync_WhenBothBannedAndBlocked_ShouldReportBanFirst() await ApplyPunishmentAsync(graphStore, PlayerTwo, OnlinePunishmentKind.Ban); // Act - var decision = await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); + var decision = await service.EvaluateAsync(PlayerTwo, PlayerOne, OnlineSocialInteractionPurpose.DirectMessage); // Assert Assert.False(decision.Allowed); @@ -382,7 +377,7 @@ public async Task EvaluateSendAsync_WhenScopeLacksPlayer_ShouldDenyAsInvalid() var service = CreateService(out _); // Act - var decision = await service.EvaluateSendAsync(new OnlineScope(TenantId, AppId, ServerId, 0)); + var decision = await service.EvaluateSendAsync(new OnlineScope(ServerId)); // Assert Assert.False(decision.Allowed); @@ -459,8 +454,8 @@ public async Task UnblockAsync_ShouldLiftDenialForAllPurposes() Assert.True(unblocked.Data); foreach (var purpose in purposes) { - Assert.True((await service.EvaluateAsync(TenantId, AppId, PlayerOne, PlayerTwo, purpose)).Allowed); - Assert.True((await service.EvaluateAsync(TenantId, AppId, PlayerTwo, PlayerOne, purpose)).Allowed); + Assert.True((await service.EvaluateAsync(PlayerOne, PlayerTwo, purpose)).Allowed); + Assert.True((await service.EvaluateAsync(PlayerTwo, PlayerOne, purpose)).Allowed); } } @@ -600,7 +595,7 @@ public async Task TransitionReportAsync_WhenIllegalEdge_ShouldReturnStateOperati var submitted = await service.SubmitReportAsync(CreatePlayerScope(PlayerOne), new OnlineReportSubmission { ReportedPlayerId = PlayerTwo, Scene = OnlineReportScene.Profile, Reason = OnlineReportReason.Spam }); // Act - var outcome = await service.TransitionReportAsync(new OnlineReportTransition { TenantId = TenantId, AppId = AppId, ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Actioned, Resolution = OnlineReportResolution.Banned, HandlerAdminId = AdminId }); + var outcome = await service.TransitionReportAsync(new OnlineReportTransition { ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Actioned, Resolution = OnlineReportResolution.Banned, HandlerAdminId = AdminId }); // Assert Assert.False(outcome.IsSuccess); @@ -616,10 +611,10 @@ public async Task TransitionReportAsync_WhenActionedWithoutResolution_ShouldDeny // Arrange var service = CreateService(out _); var submitted = await service.SubmitReportAsync(CreatePlayerScope(PlayerOne), new OnlineReportSubmission { ReportedPlayerId = PlayerTwo, Scene = OnlineReportScene.Profile, Reason = OnlineReportReason.Spam }); - Assert.True((await service.TransitionReportAsync(new OnlineReportTransition { TenantId = TenantId, AppId = AppId, ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Reviewing, Resolution = OnlineReportResolution.None, HandlerAdminId = AdminId })).IsSuccess); + Assert.True((await service.TransitionReportAsync(new OnlineReportTransition { ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Reviewing, Resolution = OnlineReportResolution.None, HandlerAdminId = AdminId })).IsSuccess); // Act - var outcome = await service.TransitionReportAsync(new OnlineReportTransition { TenantId = TenantId, AppId = AppId, ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Actioned, Resolution = OnlineReportResolution.None, HandlerAdminId = AdminId }); + var outcome = await service.TransitionReportAsync(new OnlineReportTransition { ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Actioned, Resolution = OnlineReportResolution.None, HandlerAdminId = AdminId }); // Assert Assert.False(outcome.IsSuccess); @@ -637,8 +632,8 @@ public async Task TransitionReportAsync_WhenRejected_ShouldRequireNoViolation() var submitted = await service.SubmitReportAsync(CreatePlayerScope(PlayerOne), new OnlineReportSubmission { ReportedPlayerId = PlayerTwo, Scene = OnlineReportScene.Profile, Reason = OnlineReportReason.Spam }); // Act - var contradictory = await service.TransitionReportAsync(new OnlineReportTransition { TenantId = TenantId, AppId = AppId, ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Rejected, Resolution = OnlineReportResolution.Banned, HandlerAdminId = AdminId }); - var consistent = await service.TransitionReportAsync(new OnlineReportTransition { TenantId = TenantId, AppId = AppId, ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Rejected, Resolution = OnlineReportResolution.NoViolation, HandlerAdminId = AdminId, AdminCaseId = "ADM-1" }); + var contradictory = await service.TransitionReportAsync(new OnlineReportTransition { ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Rejected, Resolution = OnlineReportResolution.Banned, HandlerAdminId = AdminId }); + var consistent = await service.TransitionReportAsync(new OnlineReportTransition { ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Rejected, Resolution = OnlineReportResolution.NoViolation, HandlerAdminId = AdminId, AdminCaseId = "ADM-1" }); // Assert Assert.False(contradictory.IsSuccess); @@ -660,11 +655,11 @@ public async Task TransitionReportAsync_WhenSameStateRepeated_ShouldBeIdempotent // Arrange var service = CreateService(out _); var submitted = await service.SubmitReportAsync(CreatePlayerScope(PlayerOne), new OnlineReportSubmission { ReportedPlayerId = PlayerTwo, Scene = OnlineReportScene.Profile, Reason = OnlineReportReason.Spam }); - var first = await service.TransitionReportAsync(new OnlineReportTransition { TenantId = TenantId, AppId = AppId, ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Reviewing, Resolution = OnlineReportResolution.None, HandlerAdminId = AdminId }); + var first = await service.TransitionReportAsync(new OnlineReportTransition { ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Reviewing, Resolution = OnlineReportResolution.None, HandlerAdminId = AdminId }); Assert.True(first.IsSuccess); // Act - var second = await service.TransitionReportAsync(new OnlineReportTransition { TenantId = TenantId, AppId = AppId, ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Reviewing, Resolution = OnlineReportResolution.None, HandlerAdminId = AdminId }); + var second = await service.TransitionReportAsync(new OnlineReportTransition { ReportId = submitted.Data.ReportId, TargetState = OnlineReportState.Reviewing, Resolution = OnlineReportResolution.None, HandlerAdminId = AdminId }); // Assert Assert.True(second.IsSuccess); @@ -753,7 +748,7 @@ private static OnlineSocialDecisionService CreateService(out OnlineEventRecorder private static async Task ApplyPunishmentAsync(InMemoryOnlineSocialGraphStore graphStore, long playerId, OnlinePunishmentKind kind) { var punishmentService = new OnlinePunishmentService(graphStore, new OnlineEventRecorder()); - var outcome = await punishmentService.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = playerId, Kind = kind, Reason = "测试处罚", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); + var outcome = await punishmentService.ApplyAsync(new OnlinePunishmentRequest { PlayerId = playerId, Kind = kind, Reason = "测试处罚", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId }); Assert.True(outcome.IsSuccess); return outcome.Data; } @@ -765,7 +760,7 @@ private static async Task ApplyPunishmentAsync(InMemoryOnlineS /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineSocialGateIntegrationTests.cs b/Tests/GameFrameX.Tests/Online/OnlineSocialGateIntegrationTests.cs index 495eb8bac..dd8e31a6b 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineSocialGateIntegrationTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineSocialGateIntegrationTests.cs @@ -48,11 +48,6 @@ namespace GameFrameX.Tests.Online /// public class OnlineSocialGateIntegrationTests { - /// 测试用租户标识。 - private const long TenantId = 1; - - /// 测试用应用标识。 - private const long AppId = 10; /// 测试用区服标识。 private const long ServerId = 100; @@ -218,7 +213,7 @@ public async Task InviteAsync_WhenInviterMuted_ShouldStillAllow() // Arrange var fixture = CreatePartyFixture(withGate: true); var party = await CreatePartyAsync(fixture.Party, PlayerOne); - Assert.True((await fixture.Punishments.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerOne, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); + Assert.True((await fixture.Punishments.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerOne, Kind = OnlinePunishmentKind.Mute, Reason = "刷屏", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); // Act var invite = await fixture.Party.InviteAsync(CreatePlayerScope(PlayerOne), party.PartyId, PlayerTwo); @@ -236,7 +231,7 @@ public async Task InviteAsync_WhenInviterBanned_ShouldDenyWithAccountBanned() // Arrange var fixture = CreatePartyFixture(withGate: true); var party = await CreatePartyAsync(fixture.Party, PlayerOne); - Assert.True((await fixture.Punishments.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerOne, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); + Assert.True((await fixture.Punishments.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerOne, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); // Act var invite = await fixture.Party.InviteAsync(CreatePlayerScope(PlayerOne), party.PartyId, PlayerTwo); @@ -258,7 +253,7 @@ public async Task RunOnceAsync_WhenSocialGateMissing_ShouldKeepLegacyBehavior() await EnqueueAsync(fixture, PlayerTwo, 2, new List { PlayerTwo }); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -278,7 +273,7 @@ public async Task RunOnceAsync_WithGateAndNoBlock_ShouldStillMatch() await EnqueueAsync(fixture, PlayerTwo, 2, new List { PlayerTwo }); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); @@ -306,19 +301,19 @@ public async Task RunOnceAsync_WhenCandidateBlocked_ShouldSkipWholeTicketAndMatc Assert.True((await fixture.Decision.BlockAsync(CreatePlayerScope(PlayerOne), PlayerTwo)).IsSuccess); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); Assert.Single(outcome.Data.AssignmentIds); - var assignment = await fixture.Store.FindAssignmentAsync(TenantId, AppId, outcome.Data.AssignmentIds[0]); + var assignment = await fixture.Store.FindAssignmentAsync(outcome.Data.AssignmentIds[0]); Assert.Equal(new List { PlayerOne, PlayerFour, PlayerFive }, assignment.PlayerIds); Assert.Equal(new List { anchorTicket.TicketId, healthyTicket.TicketId }, assignment.TicketIds); Assert.DoesNotContain(blockedTicket.TicketId, assignment.TicketIds); // 被跳过的票据整票留在队列里(既没被消费,也没被拆散)。 - var stillQueued = await fixture.Store.FindAsync(TenantId, AppId, blockedTicket.TicketId); + var stillQueued = await fixture.Store.FindAsync(blockedTicket.TicketId); Assert.NotNull(stillQueued); Assert.Equal(OnlineMatchTicketState.Queued, stillQueued.State); Assert.Equal(new List { PlayerTwo, PlayerThree }, stillQueued.PlayerIds); @@ -341,20 +336,20 @@ public async Task RunOnceAsync_WhenCandidateTicketHoldsBannedPlayer_ShouldSkipTi var bannedTicket = await EnqueueAsync(fixture, PlayerTwo, 3, new List { PlayerTwo, PlayerThree }); await NextArrivalTickAsync(); await EnqueueAsync(fixture, PlayerFour, 3, new List { PlayerFour, PlayerFive }); - Assert.True((await fixture.Punishments.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerTwo, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); + Assert.True((await fixture.Punishments.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerTwo, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); Assert.Single(outcome.Data.AssignmentIds); - var assignment = await fixture.Store.FindAssignmentAsync(TenantId, AppId, outcome.Data.AssignmentIds[0]); + var assignment = await fixture.Store.FindAssignmentAsync(outcome.Data.AssignmentIds[0]); Assert.Equal(new List { PlayerOne, PlayerFour, PlayerFive }, assignment.PlayerIds); Assert.DoesNotContain(bannedTicket.TicketId, assignment.TicketIds); - var stillQueued = await fixture.Store.FindAsync(TenantId, AppId, bannedTicket.TicketId); + var stillQueued = await fixture.Store.FindAsync(bannedTicket.TicketId); Assert.Equal(OnlineMatchTicketState.Queued, stillQueued.State); } @@ -369,16 +364,16 @@ public async Task RunOnceAsync_WhenAnchorBanned_ShouldNotProduceAssignment() var bannedTicket = await EnqueueAsync(fixture, PlayerOne, 2, new List { PlayerOne }); await NextArrivalTickAsync(); await EnqueueAsync(fixture, PlayerTwo, 2, new List { PlayerTwo }); - Assert.True((await fixture.Punishments.ApplyAsync(new OnlinePunishmentRequest { TenantId = TenantId, AppId = AppId, PlayerId = PlayerOne, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); + Assert.True((await fixture.Punishments.ApplyAsync(new OnlinePunishmentRequest { PlayerId = PlayerOne, Kind = OnlinePunishmentKind.Ban, Reason = "使用外挂", EffectiveAtTime = 0, ExpiresAtTime = 0, AdminId = AdminId })).IsSuccess); // Act - var outcome = await fixture.Coordinator.RunOnceAsync(TenantId, AppId); + var outcome = await fixture.Coordinator.RunOnceAsync(); // Assert Assert.True(outcome.IsSuccess); Assert.Empty(outcome.Data.AssignmentIds); - var stillQueued = await fixture.Store.FindAsync(TenantId, AppId, bannedTicket.TicketId); + var stillQueued = await fixture.Store.FindAsync(bannedTicket.TicketId); Assert.Equal(OnlineMatchTicketState.Queued, stillQueued.State); } @@ -476,7 +471,7 @@ private static async Task EnqueueAsync(MatchFixture fixture, /// 作用域。 private static OnlineScope CreatePlayerScope(long playerId) { - return new OnlineScope(TenantId, AppId, ServerId, playerId); + return new OnlineScope(ServerId, playerId); } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineTournamentLifecycleTests.cs b/Tests/GameFrameX.Tests/Online/OnlineTournamentLifecycleTests.cs index 819510849..f76d4cd49 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineTournamentLifecycleTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineTournamentLifecycleTests.cs @@ -65,7 +65,7 @@ public async Task RegisterAsync_DuplicateRegistration_ShouldReplayWithoutNewRegi Assert.True(second.Data.IsReplay); Assert.Equal(first.Data.Registration.RegisteredTime, second.Data.Registration.RegisteredTime); - var registrations = await harness.TournamentStore.ListRegistrationsAsync(OnlineTournamentTestHarness.TenantId, OnlineTournamentTestHarness.AppId, "t1"); + var registrations = await harness.TournamentStore.ListRegistrationsAsync("t1"); Assert.Single(registrations); Assert.Single(harness.Recorder.Filter(OnlineTournamentEvents.TournamentRegistered)); } @@ -99,7 +99,7 @@ public async Task RegisterAsync_EligibilityNotMet_ShouldRejectWithMachineReadabl Assert.False(notRanked.Data.Accepted); Assert.Equal(OnlineTournamentRegistrationRejection.NotRanked, notRanked.Data.Rejection); - var registrations = await harness.TournamentStore.ListRegistrationsAsync(OnlineTournamentTestHarness.TenantId, OnlineTournamentTestHarness.AppId, "t1"); + var registrations = await harness.TournamentStore.ListRegistrationsAsync("t1"); Assert.Equal(2, registrations.Count); Assert.Equal(2, harness.Recorder.Filter(OnlineTournamentEvents.TournamentRegistered).Count); } @@ -186,11 +186,11 @@ await harness.WriteScoresAsync( } /// - /// 验证创建校验(奖励规则区间重叠会重复发奖,必须拒绝)与跨 App 反预言 - /// (跨 App 读写与「赛事不存在」同构返回 ResourceNotFound)。 + /// 验证创建校验(奖励规则区间重叠会重复发奖,必须拒绝)与赛事全局域语义 + /// (单键化 D4:同键即同赛——跨区服作用域可操作同一赛事;未知赛事仍与「不存在」同构拒绝)。 /// [Fact] - public async Task CreateAsync_ShouldRejectOverlappingRulesAndHideCrossAppTournaments() + public async Task CreateAsync_ShouldRejectOverlappingRules_AndCrossServerSharesGlobalTournament() { var harness = new OnlineTournamentTestHarness(); await harness.CreateBoardAsync("board-validate"); @@ -211,16 +211,20 @@ public async Task CreateAsync_ShouldRejectOverlappingRulesAndHideCrossAppTournam Assert.True((await harness.CreateTournamentAsync("t1", "board-validate", null, OnlineTournamentTestHarness.Rule(1, 1, 100))).IsSuccess); Assert.Equal(OnlineTournamentState.Scheduled, await harness.TournamentStateAsync("t1")); - // 跨 App:与不存在同构。 - var crossApp = await harness.TournamentService.StartAsync(harness.Scope(OnlineTournamentTestHarness.OtherAppId), "t1"); - Assert.False(crossApp.IsSuccess); - Assert.Equal(OnlineErrorCode.ResourceNotFound, crossApp.Code); + // 跨区服:同键即同赛——可开赛、可结束、可读冻结成绩。 + var crossServer = await harness.TournamentService.StartAsync(harness.Scope(OnlineTournamentTestHarness.OtherServerId), "t1"); + Assert.True(crossServer.IsSuccess, crossServer.Message); + Assert.Equal(OnlineTournamentState.Active, await harness.TournamentStateAsync("t1")); - var crossAppStandings = await harness.TournamentService.GetStandingsAsync(harness.Scope(OnlineTournamentTestHarness.OtherAppId), "t1"); - Assert.False(crossAppStandings.IsSuccess); - Assert.Equal(OnlineErrorCode.ResourceNotFound, crossAppStandings.Code); + var crossServerEnd = await harness.TournamentService.EndAsync(harness.Scope(OnlineTournamentTestHarness.OtherServerId), "t1", OnlineTournamentTestHarness.Now + 500); + Assert.True(crossServerEnd.IsSuccess, crossServerEnd.Message); - Assert.Equal(OnlineTournamentState.Scheduled, await harness.TournamentStateAsync("t1")); + var crossServerStandings = await harness.TournamentService.GetStandingsAsync(harness.Scope(OnlineTournamentTestHarness.OtherServerId), "t1"); + Assert.True(crossServerStandings.IsSuccess, crossServerStandings.Message); + + var unknownTournament = await harness.TournamentService.GetStandingsAsync(harness.Scope(), "t-absent"); + Assert.False(unknownTournament.IsSuccess); + Assert.Equal(OnlineErrorCode.ResourceNotFound, unknownTournament.Code); } /// @@ -265,7 +269,7 @@ public async Task Lifecycle_ShouldPublishAuditableFacts() Assert.Equal(OnlineTournamentEvents.Source, registered.Source); // 报名时刻冻结的判定输入随登记留存(事后榜单变化不影响已通过的报名)。 - var stored = await harness.TournamentStore.FindRegistrationAsync(OnlineTournamentTestHarness.TenantId, OnlineTournamentTestHarness.AppId, "t1", OnlineTournamentTestHarness.PlayerOne); + var stored = await harness.TournamentStore.FindRegistrationAsync("t1", OnlineTournamentTestHarness.PlayerOne); Assert.NotNull(stored); Assert.Equal(1, stored.RankAtRegistration); Assert.Equal(300, stored.ScoreAtRegistration); @@ -360,7 +364,7 @@ public async Task RegisterAsync_ConcurrentDuplicate_ShouldStoreSingleRegistratio } Assert.Equal(1, results.Count(result => !result.Data.IsReplay)); - var registrations = await harness.TournamentStore.ListRegistrationsAsync(OnlineTournamentTestHarness.TenantId, OnlineTournamentTestHarness.AppId, "t1"); + var registrations = await harness.TournamentStore.ListRegistrationsAsync("t1"); Assert.Single(registrations); } } diff --git a/Tests/GameFrameX.Tests/Online/OnlineTournamentSettlementTests.cs b/Tests/GameFrameX.Tests/Online/OnlineTournamentSettlementTests.cs index 64ebc0d2f..0875e364a 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineTournamentSettlementTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineTournamentSettlementTests.cs @@ -209,7 +209,7 @@ public async Task SettleAsync_FromOtherServerScope_ShouldReplayInsteadOfDoubleGr Assert.True((await harness.SettleTournamentAsync("t1")).IsSuccess); // 从另一个区服作用域重复触发(无归属服 → 幂等键不随调用方区服漂移)。 - var otherServerScope = new GameFrameX.Capability.Online.Abstractions.Scope.OnlineScope(OnlineTournamentTestHarness.TenantId, OnlineTournamentTestHarness.AppId, 999, 0); + var otherServerScope = new GameFrameX.Capability.Online.Abstractions.Scope.OnlineScope(999, 0); var replay = await harness.TournamentService.SettleAsync(otherServerScope, "t1", OnlineTournamentTestHarness.Now + 400); Assert.True(replay.IsSuccess, replay.Message); diff --git a/Tests/GameFrameX.Tests/Online/OnlineTournamentTestHarness.cs b/Tests/GameFrameX.Tests/Online/OnlineTournamentTestHarness.cs index 2cdeed62a..172c1d0aa 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineTournamentTestHarness.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineTournamentTestHarness.cs @@ -52,14 +52,9 @@ namespace GameFrameX.Tests.Online /// internal sealed class OnlineTournamentTestHarness { - /// 租户标识。 - public const long TenantId = 1; + /// 另一区服标识(跨区服反预言用例)。 + public const long OtherServerId = 200; - /// App 标识。 - public const long AppId = 10; - - /// 另一 App 标识(跨 App 反预言用例)。 - public const long OtherAppId = 11; /// 区服标识。 public const long ServerId = 100; @@ -196,13 +191,13 @@ public OnlineTournamentService TournamentService } /// - /// 构造作用域(默认本 App、无玩家主体位——赛事与榜单均为 (TenantId, AppId) 作用域)。 + /// 构造作用域(默认本区服、无玩家主体位——赛事与榜单均为区服键作用域)。 /// - /// App 标识。 + /// 区服标识。 /// 作用域。 - public OnlineScope Scope(long appId = AppId) + public OnlineScope Scope(long serverId = ServerId) { - return new OnlineScope(TenantId, appId, ServerId, 0); + return new OnlineScope(serverId, 0); } /// @@ -238,8 +233,6 @@ public async Task WriteScoresAsync(string leaderboardId, params (long PlayerId, { MatchResultId = matchResultId, MatchId = matchId, - TenantId = TenantId, - AppId = AppId, ServerId = ServerId, Mode = OnlineRockPaperScissorsGame.MatchMode, Region = 1, @@ -324,7 +317,7 @@ public Task> SettleTournamentAsy /// 赛事状态。 public async Task TournamentStateAsync(string tournamentId) { - var tournament = await TournamentStore.FindAsync(TenantId, AppId, tournamentId); + var tournament = await TournamentStore.FindAsync(tournamentId); Assert.NotNull(tournament); return tournament.State; } @@ -336,7 +329,7 @@ public async Task TournamentStateAsync(string tournamentI /// 币余额。 public async Task BalanceAsync(long playerId) { - var wallet = await RawAssetStore.FindWalletAsync(TenantId, AppId, playerId, CoinAssetId); + var wallet = await RawAssetStore.FindWalletAsync(playerId, CoinAssetId); return wallet == null ? 0 : wallet.Balance; } @@ -347,7 +340,7 @@ public async Task BalanceAsync(long playerId) /// 账本条目数。 public async Task LedgerCountAsync(long playerId) { - var entries = await RawAssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { TenantId = TenantId, AppId = AppId, PlayerId = playerId, AfterSequenceNumber = 0, MaxCount = 1000 }); + var entries = await RawAssetStore.ListLedgerEntriesAsync(new OnlineLedgerPageQuery { PlayerId = playerId, AfterSequenceNumber = 0, MaxCount = 1000 }); return entries.Count; } @@ -358,7 +351,7 @@ public async Task LedgerCountAsync(long playerId) /// 全序条目。 public async Task> BoardEntriesAsync(string leaderboardId) { - var board = await RawLeaderboardStore.FindAsync(TenantId, AppId, leaderboardId); + var board = await RawLeaderboardStore.FindAsync(leaderboardId); Assert.NotNull(board); return await RawLeaderboardStore.ListOrderedEntriesAsync(board); } diff --git a/Tests/GameFrameX.Tests/Online/RockPaperScissorsMatchBridgeTests.cs b/Tests/GameFrameX.Tests/Online/RockPaperScissorsMatchBridgeTests.cs index a07ee4b2c..cd4d8dac3 100644 --- a/Tests/GameFrameX.Tests/Online/RockPaperScissorsMatchBridgeTests.cs +++ b/Tests/GameFrameX.Tests/Online/RockPaperScissorsMatchBridgeTests.cs @@ -42,11 +42,6 @@ namespace GameFrameX.Tests.Online [Collection(CapabilityRuntimeCollection.Name)] public class RockPaperScissorsMatchBridgeTests { - /// 授权作用域租户标识。 - private const long TenantId = 1; - - /// 授权作用域应用标识。 - private const long AppId = 1; /// 授权作用域区服标识。 private const long ServerId = 1001; @@ -76,7 +71,7 @@ private static async Task WithPublishedBridgeAsync(StubMatchBridge stub, bool pu context.Bridges.Publish(stub); if (publishScopeProvider) { - context.Bridges.Publish(new StubScopeProvider(new OnlineScope(TenantId, AppId, ServerId))); + context.Bridges.Publish(new StubScopeProvider(new OnlineScope(ServerId))); } return Task.CompletedTask; @@ -84,7 +79,7 @@ private static async Task WithPublishedBridgeAsync(StubMatchBridge stub, bool pu var options = new CapabilityCompositionOptions(default, new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = 1, AppId = 1, ServerId = 1, }, + HostOptions = new CapabilityHostOptions { ServerId = 1, }, Filter = new CapabilityAssemblyFilter(new[] { MechanismScenario.First.DefaultId }), }; var runtime = CapabilityComposition.Compose(new MechanismTestFamily(), options); @@ -275,8 +270,6 @@ await WithPublishedBridgeAsync(stub, true, async runtime => Assert.True(startHandled); Assert.Equal(0, startResponse.ErrorCode); Assert.Equal(1, stub.StartCallCount); - Assert.Equal(TenantId, stub.LastStartScope.TenantId); - Assert.Equal(AppId, stub.LastStartScope.AppId); Assert.Equal(ServerId, stub.LastStartScope.ServerId); Assert.Equal(ActorId, stub.LastStartScope.PlayerId); Assert.Equal(RoomId, stub.LastStartRoomId); @@ -290,7 +283,6 @@ await WithPublishedBridgeAsync(stub, true, async runtime => Assert.Equal(0, submitResponse.ErrorCode); Assert.NotNull(submitResponse.GameInfo); Assert.Equal(ActorId, stub.LastSubmitScope.PlayerId); - Assert.Equal(TenantId, stub.LastSubmitScope.TenantId); Assert.Equal(ServerId, stub.LastSubmitScope.ServerId); Assert.Equal(RoomId, stub.LastSubmitRoomId); Assert.Equal(Round, stub.LastSubmitRound); diff --git a/Tests/GameFrameX.Tests/Utility/OnlineCapabilityConfigSectionTests.cs b/Tests/GameFrameX.Tests/Utility/OnlineCapabilityConfigSectionTests.cs index c313b64c9..388325181 100644 --- a/Tests/GameFrameX.Tests/Utility/OnlineCapabilityConfigSectionTests.cs +++ b/Tests/GameFrameX.Tests/Utility/OnlineCapabilityConfigSectionTests.cs @@ -121,9 +121,8 @@ public void Deserialize_EmptyArrays_BindEmptyLists() Assert.Empty(section.Disable); } - /// - /// 双闸并入配置段:EnableRuntime / EnableAdminApi / EnableRoles / UseGameDbStores 在 "Online" 节点内绑定, - /// 与平铺的作用域字段(OnlineTenantId / OnlineAppId)并存互不干扰;未配置的过滤表保持 null。 + /// 双闸并入配置段:EnableRuntime / EnableAdminApi / EnableRoles / UseGameDbStores 在 "Online" 节点内绑定; + /// 老 JSON 遗留的废键(OnlineTenantId / OnlineAppId)仅被忽略不炸;未配置的过滤表保持 null。 /// [Fact] public void Deserialize_SectionGatesAndFlatScopeFields_Coexist() @@ -150,8 +149,6 @@ public void Deserialize_SectionGatesAndFlatScopeFields_Coexist() Assert.NotNull(settings); var setting = Assert.Single(settings); - Assert.Equal(1, setting.OnlineTenantId); - Assert.Equal(1, setting.OnlineAppId); Assert.NotNull(setting.Online); Assert.True(setting.Online.EnableRuntime); Assert.True(setting.Online.EnableAdminApi);