feat(all): Big Bang
- Support the October 8 official update with current game data, schedules and seeds. - Add profiles, friends, guilds, PvP, realtime chat, fishing and multiplayer modes. - Persist shared rewards and settlements with transactional delivery and recovery. - Fix activity rewards, mission periods, monster-hunt ranking and replay, and field progression. - Improve login, network connectivity, session recovery and unfinished story restoration. - Add configurable AI chat translation and server-authoritative text moderation. - Add Minecraft-style SDK text components with five-language JSON catalogs. - Support isolated second clients and update build, resource, capture and source-analysis tools and docs.
This commit is contained in:
1 parent
d46863b3f1
commit
8d5d7dfb76
295 files changed
+35048
-460
No files matched your search
+19
-10
@@ -72,22 +72,31 @@ https://bd2.example.com/auth/google/callback
|
||||
|
||||
## 3. 创建 Google OAuth 应用
|
||||
|
||||
Google 当前主要在 **Google Auth Platform → Branding / Audience / Data Access / Clients** 中管理 OAuth。控制台名称以后可能调整,但需要完成的对象不变:配置应用展示与受众,并创建一个 **Web application** 类型的 OAuth client。
|
||||
Google 当前主要在 **Google Auth Platform → Branding / Audience / Data Access / Clients** 中管理 OAuth。
|
||||
|
||||
1. 登录 <https://console.cloud.google.com/> 并选择或创建项目。
|
||||
2. 在 **Branding** 中配置应用名称、支持邮箱等公开信息。
|
||||
3. 在 **Audience** 中选择实际目标受众并确认 Publishing status:
|
||||
- **测试阶段**:保持 Testing,并把实际参加登录测试的 Google 账号加入 Test users。未列入的玩家会被 Google 拒绝。
|
||||
- **向玩家开放前**:检查 Audience、Publishing status 和 Google 显示的发布要求,并按实际受众切换到 In production。
|
||||
4. 在 **Data Access** 中核对 scope。`bd2server` 当前只申请最小的 `openid`,不申请 `profile` 或邮箱 scope。
|
||||
5. 在 **Clients** 中选择 **Create Client**,应用类型选择 **Web application**。不要创建 Desktop application 类型的 client:浏览器回调落在服务端 HTTPS endpoint,需要 Web application client。
|
||||
6. 在 **Authorized redirect URIs** 中添加:
|
||||
1. 登录 [Google Cloud Console](https://console.cloud.google.com/) 并选择或创建项目。
|
||||
|
||||
2. 打开左侧的 **APIs & Services** 一栏,进入 **OAuth consent screen** 页面。
|
||||
|
||||
3. 在 **Branding** 中点击 **Get started**(如果是首次配置),填写应用名称、支持邮箱等公开信息。
|
||||
|
||||
4. 在 **Audience** 中选择实际目标受众(一般选择 **External**),并确认:
|
||||
- **测试阶段**:保持 **Testing** 状态,并把实际参加登录测试的 Google 账号加入 **Test users**。未列入的玩家会被 Google 拒绝(测试用户可在 **Audience** 页面添加)。
|
||||
- **向所有玩家开放**:在 **Audience** 页面,找到 **Publishing status**,点击 **Publish app**(发布前需要根据指引完成 **Branding** 的配置,并满足 Google 对应用的相关要求)。
|
||||
|
||||
5. 在 **Data Access** 中核对 **Scopes**。我们当前只需申请最小的 `openid`,申请多了也没用。
|
||||
|
||||
6. 在 **Clients** 中选择 **Create client**,**Application type** 选择 **Web application**。不要创建其他类型的 client。
|
||||
|
||||
7. 在 **Authorized redirect URIs** 中添加:
|
||||
|
||||
```text
|
||||
https://bd2.example.com/auth/google/callback
|
||||
```
|
||||
|
||||
7. 创建后立即安全保存 Client ID 和 Client Secret。如果 Google 后台不再允许查看或下载原 secret,就按后台提供的轮换流程创建新 secret,并同步更新服务端环境变量。
|
||||
注意:这里的 `bd2.example.com` 是示例域名,实际配置时必须替换成 `bd2server` 真实使用的 HTTPS 回调地址,并与服务端配置完全一致。
|
||||
|
||||
8. 首次创建后,配置可能需要几分钟到几小时才能完全生效。创建后立即安全保存 **Client ID** 和 **Client Secret**。如果 Google 后台不再允许查看或下载原 secret,就按照后台提供的轮换流程创建新 secret,并同步更新服务端环境变量。
|
||||
|
||||
## 4. 生成并保存 master key
|
||||
|
||||
|
||||
+156
-1
@@ -21,10 +21,42 @@
|
||||
"gold_per_paid_diamond": 1000,
|
||||
"diamonds_per_paid_diamond": 1
|
||||
}
|
||||
},
|
||||
"text_moderation": {
|
||||
"rule_files": [],
|
||||
"provider": {
|
||||
"type": "off"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 实时联机入口
|
||||
|
||||
共享存档、PVP 防守快照、公会和排行榜由服务端管理。动作小游戏、联机钓鱼与随机防御另外使用实时连接,需要时在 `game.json` 添加 `realtime` 分组:
|
||||
|
||||
```json
|
||||
"realtime": {
|
||||
"enabled": true,
|
||||
"tcp_listen": "0.0.0.0:8444",
|
||||
"udp_listen": "0.0.0.0:8444",
|
||||
"public_host": "game.example.com",
|
||||
"tcp_port": 8444,
|
||||
"udp_port": 8444,
|
||||
"tls_cert_file": "/etc/bd2/tls/server.crt",
|
||||
"tls_key_file": "/etc/bd2/tls/server.key",
|
||||
"development_plain_loopback": false
|
||||
}
|
||||
```
|
||||
|
||||
省略此分组时不会监听实时端口,会对玩家体验造成影响。`public_host` 填玩家能够访问的主机名,不带协议、路径或端口。公开端口可以与监听端口不同,适用于端口映射。需要分别转发 TCP 和 UDP,普通 HTTP 反向代理不能直接转发这些原生连接。原有登录与游戏 HTTP(S) 入口继续使用认证配置中的地址。
|
||||
|
||||
TCP 使用与 `public_host` 匹配且受客户端信任的 TLS 证书。证书路径相对于 `game.json` 所在目录解析,也可以填写绝对路径。私钥只留在服务端,须允许服务进程读取。证书与私钥更新后,新握手自动载入有效的新证书;文件尚未替换完整时继续使用上一次有效证书。仅限本机开发时可以将 `development_plain_loopback` 设为 `true`,此时监听地址和公开地址都必须是回环 IP,实际生产环境不必理会。
|
||||
|
||||
玩家安装登录插件后,客户端通过已有登录会话取得短期、一次性连接票据,无需额外填写实时地址。动作同步可使用经过身份验证和防重放校验的 UDP;玩家明确配置 HTTP 代理时,实时连接通过代理的 CONNECT 隧道并使用 TCP。要让 UDP 经过代理,需要操作系统层面的 TUN 路由。
|
||||
|
||||
服务器重启不会保存战斗或房间的中间状态。已经提交的资产、成绩与领奖状态保留。客户端收到实时玩法完成通知前,服务端会先保存最终结果。尚未完成的房间需要重新进入。不要单独恢复某个数据库,备份与恢复应同时涵盖整个 `data/state`,包括账号数据库、认证数据库、共享关系、成绩和待投递事件。
|
||||
|
||||
## 联动 UR 专武
|
||||
|
||||
`gacha.include_collaboration_ur_weapons` 必须是 JSON 布尔值:
|
||||
@@ -55,7 +87,7 @@
|
||||
|
||||
所有原本走平台现金支付的普通商品,包括礼包、皮肤、通行证与付费抽卡商品,都固定消耗付费钻石。这类商品没有免费购买配置开关;`purchases.diamond_recharge` 仅设置付费钻石充值的兑换方式。原本已使用游戏内货币的商品仍走原来的游戏内购买流程。
|
||||
|
||||
普通现金商品的价格由当前版本 GameData 计算:取最小常规充值档位的现金标价与付费钻石数量作为换算基准,将商品现金标价换算为付费钻石并向上取整。当前 2.35.10 的最小档位为现金标价 `2200`、常规付费钻石 `100`,因此普通商品价格为 `ceil(现金标价 / 22)`。运行时读取 GameData 的实际档位,不把该比值固定写入代码。首次充值的加倍奖励不参与换算基准,也不增加充值兑换费用。
|
||||
普通现金商品的价格由当前版本 GameData 计算:取最小常规充值档位的现金标价与付费钻石数量作为换算基准,将商品现金标价换算为付费钻石并向上取整。当前最小档位为现金标价 `2200`、常规付费钻石 `100`,因此普通商品价格为 `ceil(现金标价 / 22)`。运行时读取 GameData 的实际档位,不把该比值固定写入代码。首次充值的加倍奖励不参与换算基准,也不增加充值兑换费用。
|
||||
|
||||
`purchases.diamond_recharge.currency` 接受下列值:
|
||||
|
||||
@@ -84,6 +116,129 @@
|
||||
|
||||
客户端从服务端 `/client/commerce` 获取商品价格目录。商品由 `group_id`、`product_id`、`sale_group` 三元组识别,Google 与 Apple 平台商品编号均作为别名返回;同一平台编号对应首购与常规变体时仍保留不同商品键。显示价格和购买校验使用同一服务端规则。
|
||||
|
||||
## 文本审核
|
||||
|
||||
输入框的内容审核由服务端决定。客户端插件关闭官方词库的拒绝与文字替换,保留长度、字符和空值校验。已有昵称和简介不会在登录时重新审核。
|
||||
|
||||
默认 `rule_files` 为空、第三方 `provider.type` 为 `"off"`,不会进行内容拦截。服主自行寻找、检查并维护词库,再将文件加入配置。所有文件在服务端启动时加载,修改后重启生效。相对路径以 `game.json` 所在目录为基准;绝对路径使用服务器实际路径。发布包不附带词库。
|
||||
|
||||
例如,加载两份本地规则:
|
||||
|
||||
```json
|
||||
"text_moderation": {
|
||||
"rule_files": ["moderation/words.txt", "moderation/names.json"],
|
||||
"provider": {
|
||||
"type": "off"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
文件须为 UTF-8,可带 BOM,单文件最多 4 MiB。`.txt` 每行一个词,忽略空行和以 `#` 开头的整行注释;其规则为子串匹配,作用于所有已接入的文本入口。下载的其他词库格式须先转换。英文短词容易命中正常名字的一部分,建议使用下面的 JSON 精确匹配或完整单词匹配。
|
||||
|
||||
`.json` 文件支持逐条指定匹配方式、作用范围及完整文本例外:
|
||||
|
||||
```json
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"text": "reservedname",
|
||||
"match": "exact",
|
||||
"scopes": ["nickname"],
|
||||
"exceptions": []
|
||||
},
|
||||
{
|
||||
"text": "sampleword",
|
||||
"match": "word",
|
||||
"scopes": ["nickname", "greeting"],
|
||||
"exceptions": ["SamplewordHero"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
以上词语仅演示格式,不是随包提供的屏蔽词库。
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
| `match: "exact"` | 整段文本相同才命中。 |
|
||||
| `match: "word"` | 两侧须为文本边界或非单词字符。Unicode 字母、数字、组合标记和下划线均视为单词字符;不提供中文分词。 |
|
||||
| `match: "substring"` | 文本中包含指定词语即命中。 |
|
||||
| `scopes` | 当前接入范围见下表;本地规则省略或空数组作用于所有已接入入口。第三方 provider 的 `scopes` 必须明确列出需要审核的范围,已有显式列表不会自动扩展。写入其他范围名本身不会实现对应玩法。 |
|
||||
| `exceptions` | 整段文本匹配才豁免当前这一条规则;仍检查其他规则及第三方审核。 |
|
||||
|
||||
| 范围 | 输入入口 |
|
||||
|---|---|
|
||||
| `nickname` | 玩家昵称 |
|
||||
| `greeting` | 个人简介 |
|
||||
| `master_title` | 主角自定义称呼 |
|
||||
| `preset_name` | 普通配队预设名称 |
|
||||
| `equipment_preset_name` | 装备预设名称 |
|
||||
| `monster_hunt_preset_name` | 魔兽追踪者预设名称 |
|
||||
| `guild_raid_preset_name` | 公会战预设名称 |
|
||||
| `colosseum_preset_name` | 斗兽场预设名称 |
|
||||
| `equipment_mark` | 装备标记中的自定义字符 |
|
||||
| `guild_name` | 公会名称 |
|
||||
| `guild_message` | 公会介绍 |
|
||||
| `guild_notice` | 公会公告 |
|
||||
| `chat` | 联机钓鱼大厅与房间自由文本 |
|
||||
|
||||
新生成配置的第三方范围列表包含以上入口。允许空名称或默认名称的玩法保留原有协议行为;图标编号和颜色值不作为文字审核。已成功提交的请求重放返回原结果,第三方审核在新请求的玩家写事务之前完成。
|
||||
|
||||
匹配时统一进行 Unicode NFKC 规范化和大小写折叠,保存、显示及发送给第三方的仍是原文。不会自动删除空格或标点,也不会自动替换数字、拼音或相似字符。规则编译为进程共享的多模式匹配结构,普通玩法请求不触发文本审核。
|
||||
|
||||
### 第三方接入
|
||||
|
||||
本地规则先执行,通过后才调用所配置范围的第三方。直接支持 Azure AI Content Safety,同时提供通用 HTTP JSON 协议,供服主接入自己的审核服务或第三方适配网关。腾讯、阿里等供应商须通过网关处理各自的鉴权和响应转换,当前没有内置它们的原生适配器。
|
||||
|
||||
通用接口配置:
|
||||
|
||||
```json
|
||||
"text_moderation": {
|
||||
"rule_files": ["moderation/names.json"],
|
||||
"provider": {
|
||||
"type": "http_json",
|
||||
"endpoint": "https://moderation.example.com/check",
|
||||
"api_key_env": "BD2_TEXT_MODERATION_KEY",
|
||||
"api_key_header": "Authorization",
|
||||
"scopes": ["greeting"],
|
||||
"timeout_ms": 1500,
|
||||
"failure_policy": "deny"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
密钥由 `api_key_env` 指定的服务端环境变量读取。`Authorization` 头会使用 `Bearer <密钥>`;其他头名原样传递密钥。不需要鉴权的自建接口可省略 `api_key_env`。审核地址使用 HTTPS,只有回环地址允许 HTTP,不跟随重定向。
|
||||
|
||||
服务端以 POST 发送原文、范围和稳定账号标识:
|
||||
|
||||
```json
|
||||
{
|
||||
"scope": "greeting",
|
||||
"account_id": "stable-account-id",
|
||||
"text": "玩家输入的原文"
|
||||
}
|
||||
```
|
||||
|
||||
接口须返回 HTTP 200 和一个 JSON 对象,允许时为 `{"decision":"allow"}`,拒绝时为 `{"decision":"reject"}`。其他状态码、字段、缺失判定、无效 JSON 或超时均按接口故障处理;响应最多 64 KiB。服务端日志不记录原文、密钥或第三方响应体。
|
||||
|
||||
Azure 配置示例:
|
||||
|
||||
```json
|
||||
"provider": {
|
||||
"type": "azure_content_safety",
|
||||
"endpoint": "https://your-resource.cognitiveservices.azure.com",
|
||||
"api_key_env": "BD2_AZURE_CONTENT_SAFETY_KEY",
|
||||
"scopes": ["greeting"],
|
||||
"timeout_ms": 1500,
|
||||
"failure_policy": "deny",
|
||||
"severity_threshold": 4
|
||||
}
|
||||
```
|
||||
|
||||
Azure 使用资源根地址,自动调用 `2024-09-01` 版 Analyze Text API,以八级严重程度检查 Hate、Sexual、SelfHarm 和 Violence。任一类别达到 `severity_threshold` 就拒绝;阈值范围为 `0..7`,默认 `4`,设为 `0` 会连严重程度为 `0` 的结果也拒绝。这些通用类别不能代替本服的广告、冒名等自定义规则。接口规范见 [Azure Analyze Text 官方文档](https://learn.microsoft.com/en-us/rest/api/contentsafety/text-operations/analyze-text?view=rest-contentsafety-2024-09-01)。
|
||||
|
||||
`timeout_ms` 默认 `1500`,允许 `10..30000`。`failure_policy` 默认 `"deny"`:接口故障时暂不接受修改,客户端提示审核暂时不可用;`"allow"` 则在接口故障时放行已通过本地规则的文本。第三方明确拒绝以及本地规则拒绝都不会被此设置放行。被拒绝或暂时无法审核的改名不扣券、不保存名字,个人简介也不写入;玩家可保持登录并重试。
|
||||
|
||||
## 校验与升级
|
||||
|
||||
`schema_version` 当前必须为 `1`。字段拼写错误、未知字段、错误类型(例如字符串 `"true"`)、`null`、格式错误或文件末尾多出的 JSON 都会使服务端拒绝启动,并在错误中给出文件路径。省略 `gacha` 或此布尔开关时使用 `false`。
|
||||
|
||||
+6
-6
@@ -90,16 +90,16 @@ server {
|
||||
server_name cdn.example.com;
|
||||
|
||||
location /ServerData/ {
|
||||
proxy_pass https://bd2-cdn.akamaized.net/ServerData/;
|
||||
proxy_set_header Host bd2-cdn.akamaized.net;
|
||||
proxy_pass https://dl.bd2.pmang.cloud/ServerData/;
|
||||
proxy_set_header Host dl.bd2.pmang.cloud;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_cache bd2;
|
||||
proxy_cache_lock on;
|
||||
}
|
||||
|
||||
location /GameData/ {
|
||||
proxy_pass https://bd2-cdn.akamaized.net/GameData/;
|
||||
proxy_set_header Host bd2-cdn.akamaized.net;
|
||||
proxy_pass https://dl.bd2.pmang.cloud/GameData/;
|
||||
proxy_set_header Host dl.bd2.pmang.cloud;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_cache bd2;
|
||||
proxy_cache_lock on;
|
||||
@@ -135,8 +135,8 @@ TLS 证书、缓存容量、访问日志和服务条款由服主负责。公网
|
||||
`<bundle_version>` 和 `<game_data_version>` 必须分别等于客户端包内 `versions.json` 的 `bundle_version` 与 `game_data_version`。例如当前发布版本对应:
|
||||
|
||||
```text
|
||||
ServerData/StandaloneWindows64/HD/20260921135230/
|
||||
GameData/20260923193640/
|
||||
ServerData/StandaloneWindows64/HD/20261007175947/
|
||||
GameData/20261008155037/
|
||||
```
|
||||
|
||||
准备完成后,在 `bd2client` 中选择“本地已下载资源”,并选中最外层的 `<本地资源根目录>`,不要直接选择 `ServerData`、`GameData` 或某个版本号目录。客户端会验证目录结构和版本,然后由 LI 插件在游戏进程内把该目录作为仅监听 loopback 的本机资源源提供给游戏。校验失败时需要玩家自行修正或重新准备资源,客户端不会跨版本拼接或自动从网络补齐缺失文件。
|
||||
|
||||
@@ -7,11 +7,11 @@ if [ "${1-}" = check-csharp ]; then
|
||||
(
|
||||
cd "$root"
|
||||
if [ "$#" -eq 0 ]; then
|
||||
set -- GameSdk GameNames LocalIdentity LoginUI CashShop CaptureEnvironment
|
||||
set -- GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment
|
||||
fi
|
||||
for project do
|
||||
case "$project" in
|
||||
GameSdk|GameNames|LocalIdentity|LoginUI|CashShop|CaptureEnvironment) ;;
|
||||
GameSdk|GameNames|LocalIdentity|LoginUI|CashShop|FChat|CaptureEnvironment) ;;
|
||||
*) printf 'bd2w: unknown C# project: %s\n' "$project" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
@@ -4,6 +4,7 @@ set "BD2W_ROOT=%~dp0"
|
||||
if /I "%~1"=="check-csharp" goto check_csharp
|
||||
set "BD2W_TOOL_DIR=%BD2W_ROOT%.build\tools"
|
||||
set "BD2W_TOOL=%BD2W_TOOL_DIR%\bd2w.exe"
|
||||
set "BD2W_RUN_TOOL=%BD2W_TOOL%"
|
||||
if not exist "%BD2W_TOOL_DIR%" (
|
||||
mkdir "%BD2W_TOOL_DIR%"
|
||||
if errorlevel 1 exit /b 1
|
||||
@@ -23,13 +24,18 @@ del /q "%BD2W_TEMP%"
|
||||
if errorlevel 1 goto failed
|
||||
goto unlock
|
||||
:replace_tool
|
||||
move /y "%BD2W_TEMP%" "%BD2W_TOOL%" >nul
|
||||
if errorlevel 1 goto failed
|
||||
move /y "%BD2W_TEMP%" "%BD2W_TOOL%" >nul 2>nul
|
||||
if errorlevel 1 set "BD2W_RUN_TOOL=%BD2W_TEMP%"
|
||||
:unlock
|
||||
rmdir "%BD2W_LOCK%"
|
||||
if errorlevel 1 exit /b 1
|
||||
"%BD2W_TOOL%" %*
|
||||
exit /b %errorlevel%
|
||||
"%BD2W_RUN_TOOL%" %*
|
||||
set "BD2W_EXIT_CODE=%errorlevel%"
|
||||
if exist "%BD2W_TEMP%" (
|
||||
del /q "%BD2W_TEMP%"
|
||||
if errorlevel 1 exit /b 1
|
||||
)
|
||||
exit /b %BD2W_EXIT_CODE%
|
||||
|
||||
:wait
|
||||
set /a BD2W_ATTEMPTS+=1 >nul
|
||||
@@ -72,7 +78,7 @@ set "BD2W_PROJECTS="
|
||||
:check_arguments
|
||||
if "%~1"=="" goto check_start
|
||||
set "BD2W_PROJECT="
|
||||
for %%P in (GameSdk GameNames LocalIdentity LoginUI CashShop CaptureEnvironment) do if "%~1"=="%%P" set "BD2W_PROJECT=%%P"
|
||||
for %%P in (GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment) do if "%~1"=="%%P" set "BD2W_PROJECT=%%P"
|
||||
if not defined BD2W_PROJECT (
|
||||
echo bd2w: Unknown C# project: "%~1" 1>&2
|
||||
exit /b 1
|
||||
@@ -81,7 +87,7 @@ set "BD2W_PROJECTS=%BD2W_PROJECTS% %BD2W_PROJECT%"
|
||||
shift
|
||||
goto check_arguments
|
||||
:check_start
|
||||
if not defined BD2W_PROJECTS set "BD2W_PROJECTS=GameSdk GameNames LocalIdentity LoginUI CashShop CaptureEnvironment"
|
||||
if not defined BD2W_PROJECTS set "BD2W_PROJECTS=GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment"
|
||||
pushd "%BD2W_ROOT%"
|
||||
if errorlevel 1 exit /b 1
|
||||
set "Configuration=Release"
|
||||
|
||||
+5
-2
@@ -23,8 +23,9 @@ func usage() {
|
||||
fmt.Println(`Usage:
|
||||
bd2w build [-GameDir directory] [-SkipTests] [-SchedulesOnly]
|
||||
bd2w runClient [client options]
|
||||
bd2w runClient2 [--instance player2] [--game-dir directory]
|
||||
bd2w runServer [server options]
|
||||
bd2w check-csharp [GameSdk GameNames LocalIdentity LoginUI CashShop CaptureEnvironment]
|
||||
bd2w check-csharp [GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment]
|
||||
bd2w sdk pack [--game-dir directory] [--package-version version] [--output-directory directory]
|
||||
bd2w sdk verify [--game-dir directory] [--package-version version] [--package-directory directory]
|
||||
bd2w sdk update-names --game-mapping file [--game-dir directory] [--version-config file]
|
||||
@@ -41,7 +42,7 @@ func run(args []string) error {
|
||||
usage()
|
||||
return nil
|
||||
}
|
||||
if args[0] != "build" && args[0] != "runClient" && args[0] != "runServer" && args[0] != "sdk" && args[0] != "version-source" {
|
||||
if args[0] != "build" && args[0] != "runClient" && args[0] != "runClient2" && args[0] != "runServer" && args[0] != "sdk" && args[0] != "version-source" {
|
||||
return fmt.Errorf("unknown task %q; use --help for available commands", args[0])
|
||||
}
|
||||
if len(args) == 2 && isHelp(args[1]) {
|
||||
@@ -58,6 +59,8 @@ func run(args []string) error {
|
||||
}
|
||||
t := task{root, native}
|
||||
switch args[0] {
|
||||
case "runClient2":
|
||||
return t.runClient2(args[1:])
|
||||
case "runClient":
|
||||
return t.command("go", append([]string{"run", "-tags", "production", "./cmd/bd2client", "--dev", "run"}, args[1:]...)...)
|
||||
case "runServer":
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
||||
clientconfig "bd2server/internal/client/config"
|
||||
clientinstance "bd2server/internal/client/instance"
|
||||
clientsetup "bd2server/internal/client/setup"
|
||||
)
|
||||
|
||||
func (t task) runClient2(args []string) error {
|
||||
fs := flag.NewFlagSet("runClient2", flag.ContinueOnError)
|
||||
name := fs.String("instance", "player2", "independent local game instance name")
|
||||
gameDir := fs.String("game-dir", "", "original game installation; defaults to go/config.json")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 0 {
|
||||
return fmt.Errorf("unexpected argument %q", fs.Arg(0))
|
||||
}
|
||||
game, managed, bep, err := t.gameDirectory(*gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
versions, err := clientconfig.LoadReleaseVersions(filepath.Join(t.root, "versions.json"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := clientsetup.Inspect(game, versions); err != nil {
|
||||
return err
|
||||
}
|
||||
settings, err := clientconfig.Load(game)
|
||||
if err != nil {
|
||||
return fmt.Errorf("save the original client's connection settings first: %w", err)
|
||||
}
|
||||
settings.ProxyURL = ""
|
||||
|
||||
instance, err := clientinstance.Prepare(*name, game, versions.GameVersion)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !instance.Created {
|
||||
settings, err = clientconfig.Load(instance.GameDirectory)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load second client's connection settings: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := clientsetup.SaveSettings(instance.GameDirectory, settings, versions); err != nil {
|
||||
return fmt.Errorf("prepare second client's resources: %w", err)
|
||||
}
|
||||
if instance.Created {
|
||||
for _, name := range []string{"LocalIdentity", "LoginUI", "CashShop", "FChat"} {
|
||||
project := filepath.Join(t.root, "plugins", name, name+".csproj")
|
||||
if err := t.command("dotnet", "build", project, "-c", "Release", "-p:GameDir="+game, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+bep, "--nologo"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
plugins := func(name string) string {
|
||||
return filepath.Join(t.root, "plugins", name, "bin", "Release", "netstandard2.1", "BD2"+name+".dll")
|
||||
}
|
||||
if _, err := clientsetup.InstallPlugins(instance.GameDirectory, settings, versions, plugins("LocalIdentity"), plugins("LoginUI"), plugins("CashShop"), plugins("FChat")); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
launcher, err := instance.WriteLauncher()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Second client ready:", launcher)
|
||||
fmt.Println("Unity log:", filepath.Join(instance.Root, "logs", "Player.log"))
|
||||
fmt.Println("BepInEx log:", filepath.Join(instance.GameDirectory, "BepInEx", "LogOutput.log"))
|
||||
if t.target.goos == "windows" {
|
||||
return exec.Command("wscript.exe", "//nologo", launcher).Run()
|
||||
}
|
||||
command := exec.Command("/bin/sh", launcher)
|
||||
if err := command.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
return command.Process.Release()
|
||||
}
|
||||
+1
-1
@@ -158,7 +158,7 @@ func (t task) build(opts buildOptions) error {
|
||||
return err
|
||||
}
|
||||
var shared []byte
|
||||
for _, plugin := range []string{"LocalIdentity", "LoginUI", "CashShop"} {
|
||||
for _, plugin := range []string{"LocalIdentity", "LoginUI", "CashShop", "FChat"} {
|
||||
project := filepath.Join(t.root, "plugins", plugin, plugin+".csproj")
|
||||
if err := t.command("dotnet", "build", project, "-c", "Release", "-p:GameDir="+game, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+bep, "--nologo"); err != nil {
|
||||
return err
|
||||
|
||||
@@ -24,6 +24,7 @@ type versionSourceConfig struct {
|
||||
CaptureEnvironment string `json:"capture_environment"`
|
||||
LoginUI string `json:"login_ui"`
|
||||
CashShop string `json:"cash_shop"`
|
||||
FChat string `json:"fchat"`
|
||||
} `json:"plugins"`
|
||||
}
|
||||
|
||||
@@ -84,7 +85,7 @@ namespace Bd2Build
|
||||
}
|
||||
|
||||
func (c versionSourceConfig) validate(plugin string) (string, error) {
|
||||
plugins := map[string]string{"local_identity": c.Plugins.LocalIdentity, "capture_environment": c.Plugins.CaptureEnvironment, "login_ui": c.Plugins.LoginUI, "cash_shop": c.Plugins.CashShop}
|
||||
plugins := map[string]string{"local_identity": c.Plugins.LocalIdentity, "capture_environment": c.Plugins.CaptureEnvironment, "login_ui": c.Plugins.LoginUI, "cash_shop": c.Plugins.CashShop, "fchat": c.Plugins.FChat}
|
||||
selected, found := plugins[plugin]
|
||||
if !found {
|
||||
return "", fmt.Errorf("unsupported plugin %q", plugin)
|
||||
@@ -94,7 +95,7 @@ func (c versionSourceConfig) validate(plugin string) (string, error) {
|
||||
if !semver.MatchString(c.GameVersion) {
|
||||
return "", errors.New("game_version must be a numeric three-part version")
|
||||
}
|
||||
for _, key := range []string{"local_identity", "capture_environment", "login_ui", "cash_shop"} {
|
||||
for _, key := range []string{"local_identity", "capture_environment", "login_ui", "cash_shop", "fchat"} {
|
||||
if !semver.MatchString(plugins[key]) {
|
||||
return "", fmt.Errorf("plugins.%s must be a numeric three-part version", key)
|
||||
}
|
||||
|
||||
@@ -89,6 +89,7 @@ func developmentRunOptions(args []string) ([]string, clientRunOptions, error) {
|
||||
localIdentityPlugin: filepath.Join(root, "plugins", "LocalIdentity", "bin", "Release", "netstandard2.1", "BD2LocalIdentity.dll"),
|
||||
loginUIPlugin: filepath.Join(root, "plugins", "LoginUI", "bin", "Release", "netstandard2.1", "BD2LoginUI.dll"),
|
||||
cashShopPlugin: filepath.Join(root, "plugins", "CashShop", "bin", "Release", "netstandard2.1", "BD2CashShop.dll"),
|
||||
fChatPlugin: filepath.Join(root, "plugins", "FChat", "bin", "Release", "netstandard2.1", "BD2FChat.dll"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -177,6 +178,7 @@ func buildDevelopmentPlugins(root, gameDir string) error {
|
||||
filepath.Join(root, "plugins", "LocalIdentity", "LocalIdentity.csproj"),
|
||||
filepath.Join(root, "plugins", "LoginUI", "LoginUI.csproj"),
|
||||
filepath.Join(root, "plugins", "CashShop", "CashShop.csproj"),
|
||||
filepath.Join(root, "plugins", "FChat", "FChat.csproj"),
|
||||
}
|
||||
for _, project := range projects {
|
||||
fmt.Fprintf(os.Stderr, "bd2client: preparing development plugin %s; first-time game source generation may take several minutes\n", filepath.Base(project))
|
||||
|
||||
@@ -15,6 +15,7 @@ type clientRunOptions struct {
|
||||
localIdentityPlugin string
|
||||
loginUIPlugin string
|
||||
cashShopPlugin string
|
||||
fChatPlugin string
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -82,6 +83,7 @@ func runClient(args []string, options clientRunOptions) error {
|
||||
LocalIdentityPlugin: options.localIdentityPlugin,
|
||||
LoginUIPlugin: options.loginUIPlugin,
|
||||
CashShopPlugin: options.cashShopPlugin,
|
||||
FChatPlugin: options.fChatPlugin,
|
||||
}); err != nil {
|
||||
logger.Error("bd2client stopped with an error", "error", err)
|
||||
return err
|
||||
|
||||
@@ -31,6 +31,7 @@ type Options struct {
|
||||
LocalIdentityPlugin string
|
||||
LoginUIPlugin string
|
||||
CashShopPlugin string
|
||||
FChatPlugin string
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
@@ -267,7 +268,7 @@ func (s *Studio) Patch(input Request) (Response, error) {
|
||||
|
||||
func (s *Studio) Install(input Request) (Response, error) {
|
||||
return s.perform("install plugins", func() (Response, error) {
|
||||
result, err := clientsetup.InstallPlugins(input.GameDirectory, input.settings(), s.options.Versions, s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin)
|
||||
result, err := clientsetup.InstallPlugins(input.GameDirectory, input.settings(), s.options.Versions, s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
@@ -275,7 +276,7 @@ func (s *Studio) Install(input Request) (Response, error) {
|
||||
return Response{}, err
|
||||
}
|
||||
message := "BD2 client plugins installed or updated"
|
||||
if !result.LocalIdentity.Changed && !result.LoginUI.Changed && !result.CashShop.Changed {
|
||||
if !result.LocalIdentity.Changed && !result.LoginUI.Changed && !result.CashShop.Changed && !result.FChat.Changed {
|
||||
message = "BD2 client plugins are already up to date; no DLL was rewritten"
|
||||
}
|
||||
return success(message, result), nil
|
||||
@@ -313,7 +314,7 @@ func (s *Studio) Launch(input Request) (Response, error) {
|
||||
if !installation.SupportedOnHost() {
|
||||
return Response{}, fmt.Errorf("cannot launch a %s game client from this operating system", installation.Kind)
|
||||
}
|
||||
for _, name := range []string{"BD2LocalIdentity.dll", "BD2LoginUI.dll", "BD2CashShop.dll"} {
|
||||
for _, name := range []string{"BD2LocalIdentity.dll", "BD2LoginUI.dll", "BD2CashShop.dll", "BD2FChat.dll"} {
|
||||
info, err := os.Stat(filepath.Join(installation.Plugins, name))
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return Response{}, fmt.Errorf("install or update the client plugins before launching; %s is missing", name)
|
||||
|
||||
@@ -34,6 +34,7 @@ type ReleaseVersions struct {
|
||||
CaptureEnvironment string `json:"capture_environment"`
|
||||
LoginUI string `json:"login_ui"`
|
||||
CashShop string `json:"cash_shop"`
|
||||
FChat string `json:"fchat"`
|
||||
} `json:"plugins"`
|
||||
}
|
||||
|
||||
@@ -65,7 +66,7 @@ func LoadReleaseVersions(path string) (ReleaseVersions, error) {
|
||||
return ReleaseVersions{}, errors.New("bundle_version and game_data_version must be 14-digit timestamps")
|
||||
}
|
||||
if versions.SeedDirectory == "" ||
|
||||
versions.Plugins.LocalIdentity == "" || versions.Plugins.LoginUI == "" || versions.Plugins.CaptureEnvironment == "" {
|
||||
versions.Plugins.LocalIdentity == "" || versions.Plugins.LoginUI == "" || versions.Plugins.CaptureEnvironment == "" || versions.Plugins.FChat == "" {
|
||||
return ReleaseVersions{}, errors.New("client release versions are incomplete")
|
||||
}
|
||||
return versions, nil
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
// Package instance prepares independent local clients for multiplayer testing.
|
||||
package instance
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
)
|
||||
|
||||
type Instance struct {
|
||||
ID string
|
||||
Root string
|
||||
GameDirectory string
|
||||
Created bool
|
||||
}
|
||||
|
||||
type manifest struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
GameVersion string `json:"game_version"`
|
||||
}
|
||||
|
||||
func Prepare(name, source, version string) (Instance, error) {
|
||||
name = strings.ToLower(strings.TrimSpace(name))
|
||||
if name == "" || len(name) > 32 || name == "default" {
|
||||
return Instance{}, errors.New("instance name must be 1-32 letters, digits, underscores or hyphens; default is reserved")
|
||||
}
|
||||
for _, ch := range name {
|
||||
valid := ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' || ch == '_' || ch == '-'
|
||||
if !valid {
|
||||
return Instance{}, errors.New("instance name may contain only letters, digits, underscores and hyphens")
|
||||
}
|
||||
}
|
||||
installation, err := clientlayout.Resolve(source)
|
||||
if err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
parent := filepath.Join(filepath.Dir(installation.Root), "BD2 Instances")
|
||||
if filepath.Base(filepath.Dir(installation.Root)) == "game" || filepath.Base(filepath.Dir(filepath.Dir(installation.Root))) == "BD2 Instances" {
|
||||
return Instance{}, errors.New("select the original installation when preparing another client instance")
|
||||
}
|
||||
result := Instance{ID: name, Root: filepath.Join(parent, name)}
|
||||
result.GameDirectory = filepath.Join(result.Root, "game")
|
||||
if installation.Kind == clientlayout.MacOS {
|
||||
result.GameDirectory = filepath.Join(result.GameDirectory, filepath.Base(installation.Root))
|
||||
}
|
||||
want := manifest{SchemaVersion: 1, ID: name, Source: installation.Root, GameVersion: version}
|
||||
data, err := os.ReadFile(filepath.Join(result.Root, "instance.json"))
|
||||
if err == nil {
|
||||
var saved manifest
|
||||
if err := json.Unmarshal(data, &saved); err != nil || saved != want {
|
||||
return Instance{}, errors.New("client instance belongs to a different installation or game version; choose a new instance name")
|
||||
}
|
||||
if _, err := clientlayout.Resolve(result.GameDirectory); err != nil {
|
||||
return Instance{}, fmt.Errorf("client instance is incomplete: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return Instance{}, err
|
||||
}
|
||||
if _, err := os.Stat(result.Root); err == nil {
|
||||
return Instance{}, errors.New("instance directory already exists without its manifest; choose another name")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return Instance{}, err
|
||||
}
|
||||
if err := os.MkdirAll(parent, 0o700); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
staged, err := os.MkdirTemp(parent, "."+name+"-preparing-")
|
||||
if err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
defer func() {
|
||||
if pathWithin(parent, staged) && strings.HasPrefix(filepath.Base(staged), "."+name+"-preparing-") {
|
||||
_ = os.RemoveAll(staged)
|
||||
}
|
||||
}()
|
||||
target := filepath.Join(staged, "game")
|
||||
if installation.Kind == clientlayout.MacOS {
|
||||
target = filepath.Join(target, filepath.Base(installation.Root))
|
||||
}
|
||||
if err := copyInstallation(installation.Root, target, installation.Data, installation.BepInEx); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
if installation.Kind == clientlayout.MacOS && filepath.Dir(installation.BepInEx) != filepath.Join(installation.Root, "Contents") {
|
||||
if err := copyBepInEx(installation.BepInEx, filepath.Join(staged, "game", "BepInEx")); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
for _, file := range []string{"run_bepinex.sh", "doorstop_config.ini", "libdoorstop.dylib"} {
|
||||
path := filepath.Join(filepath.Dir(installation.Root), file)
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
if err := copyFile(path, filepath.Join(staged, "game", file)); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, dir := range []string{"logs", "logs/crashes", "unity/persistent", "unity/cache", "unity/bundles"} {
|
||||
if err := os.MkdirAll(filepath.Join(staged, filepath.FromSlash(dir)), 0o700); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
}
|
||||
data, err = json.MarshalIndent(want, "", " ")
|
||||
if err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(staged, "instance.json"), append(data, '\n'), 0o600); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
if err := os.Rename(staged, result.Root); err != nil {
|
||||
return Instance{}, fmt.Errorf("publish client instance: %w", err)
|
||||
}
|
||||
result.Created = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func copyInstallation(source, target, data, bep string) error {
|
||||
streaming := filepath.Join(data, "StreamingAssets")
|
||||
return filepath.WalkDir(source, func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
relative, err := filepath.Rel(source, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
destination := filepath.Join(target, relative)
|
||||
if path == bep {
|
||||
if err := copyBepInEx(path, destination); err != nil {
|
||||
return err
|
||||
}
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return os.MkdirAll(destination, 0o700)
|
||||
}
|
||||
if entry.Type()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("client installation contains a symbolic link: %s", relative)
|
||||
}
|
||||
if strings.HasSuffix(strings.ToLower(relative), ".log") || strings.HasSuffix(strings.ToLower(relative), ".bak") {
|
||||
return nil
|
||||
}
|
||||
if pathWithin(streaming, path) {
|
||||
if err := os.Link(path, destination); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return copyFile(path, destination)
|
||||
})
|
||||
}
|
||||
|
||||
func copyBepInEx(source, target string) error {
|
||||
return filepath.WalkDir(source, func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
relative, err := filepath.Rel(source, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parts := strings.Split(relative, string(filepath.Separator))
|
||||
if relative != "." && parts[0] != "core" && parts[0] != "plugins" && parts[0] != "patchers" && parts[0] != "config" {
|
||||
if entry.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(parts) > 1 && parts[0] == "config" && relative != filepath.Join("config", "BepInEx.cfg") && relative != filepath.Join("config", "bd2.client.json") {
|
||||
if entry.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return os.MkdirAll(filepath.Join(target, relative), 0o700)
|
||||
}
|
||||
if entry.Type()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("BepInEx contains a symbolic link: %s", relative)
|
||||
}
|
||||
return copyFile(path, filepath.Join(target, relative))
|
||||
})
|
||||
}
|
||||
|
||||
func pathWithin(root, path string) bool {
|
||||
relative, err := filepath.Rel(root, path)
|
||||
return err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
||||
}
|
||||
|
||||
func copyFile(source, target string) (result error) {
|
||||
input, err := os.Open(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { result = errors.Join(result, input.Close()) }()
|
||||
info, err := input.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("unsupported game file: %s", source)
|
||||
}
|
||||
output, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, info.Mode().Perm())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(output, input)
|
||||
return errors.Join(err, output.Close())
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package instance
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
)
|
||||
|
||||
func (i Instance) WriteLauncher() (string, error) {
|
||||
installation, err := clientlayout.Resolve(i.GameDirectory)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
args := []string{"-screen-fullscreen", "0", "-screen-width", "1280", "-screen-height", "720", "-logFile", filepath.Join(i.Root, "logs", "Player.log"), "-crash-report-folder", filepath.Join(i.Root, "logs", "crashes")}
|
||||
if installation.Kind == clientlayout.Windows {
|
||||
quote := func(value string) string { return `"` + strings.ReplaceAll(value, `"`, `""`) + `"` }
|
||||
var command strings.Builder
|
||||
command.WriteByte('"')
|
||||
command.WriteString(installation.Executable)
|
||||
command.WriteByte('"')
|
||||
for _, arg := range args {
|
||||
command.WriteString(` "`)
|
||||
command.WriteString(arg)
|
||||
command.WriteByte('"')
|
||||
}
|
||||
var body strings.Builder
|
||||
body.WriteString("Option Explicit\r\nDim shell, environment\r\nSet shell = CreateObject(\"WScript.Shell\")\r\nSet environment = shell.Environment(\"Process\")\r\n")
|
||||
body.WriteString(`environment("BD2_CLIENT_INSTANCE_ID") = `)
|
||||
body.WriteString(quote(i.ID))
|
||||
body.WriteString("\r\n")
|
||||
body.WriteString(`environment("BD2_CLIENT_INSTANCE_ROOT") = `)
|
||||
body.WriteString(quote(i.Root))
|
||||
body.WriteString("\r\n")
|
||||
for _, key := range []string{"UNITY_PROXYSERVER", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "BD2_CLIENT_PROXY_URL"} {
|
||||
body.WriteString("environment(")
|
||||
body.WriteString(quote(key))
|
||||
body.WriteString(") = \"\"\r\n")
|
||||
}
|
||||
for _, key := range []string{"UNITY_NOPROXY", "NO_PROXY", "no_proxy"} {
|
||||
body.WriteString("environment(")
|
||||
body.WriteString(quote(key))
|
||||
body.WriteString(") = \"localhost,127.0.0.1,::1\"\r\n")
|
||||
}
|
||||
body.WriteString(`shell.CurrentDirectory = `)
|
||||
body.WriteString(quote(installation.Root))
|
||||
body.WriteString("\r\n")
|
||||
body.WriteString(`shell.Run `)
|
||||
body.WriteString(quote(command.String()))
|
||||
body.WriteString(", 1, False\r\n")
|
||||
path := filepath.Join(i.Root, "Start "+i.ID+".vbs")
|
||||
characters := utf16.Encode([]rune(body.String()))
|
||||
encoded := make([]byte, 2+2*len(characters))
|
||||
encoded[0], encoded[1] = 0xff, 0xfe
|
||||
for index, character := range characters {
|
||||
binary.LittleEndian.PutUint16(encoded[2+2*index:], character)
|
||||
}
|
||||
return path, os.WriteFile(path, encoded, 0o600)
|
||||
}
|
||||
quote := func(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" }
|
||||
var body strings.Builder
|
||||
body.WriteString("#!/bin/sh\nset -eu\n")
|
||||
body.WriteString("unset HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy\nexport UNITY_PROXYSERVER='' BD2_CLIENT_PROXY_URL=''\nexport UNITY_NOPROXY='localhost,127.0.0.1,::1' NO_PROXY='localhost,127.0.0.1,::1' no_proxy='localhost,127.0.0.1,::1'\n")
|
||||
body.WriteString("export BD2_CLIENT_INSTANCE_ID=")
|
||||
body.WriteString(quote(i.ID))
|
||||
body.WriteString("\nexport BD2_CLIENT_INSTANCE_ROOT=")
|
||||
body.WriteString(quote(i.Root))
|
||||
body.WriteByte('\n')
|
||||
body.WriteString("cd ")
|
||||
body.WriteString(quote(installation.Root))
|
||||
body.WriteString("\nexec ")
|
||||
body.WriteString(quote(installation.Executable))
|
||||
for _, arg := range args {
|
||||
body.WriteByte(' ')
|
||||
body.WriteString(quote(arg))
|
||||
}
|
||||
body.WriteString("\n")
|
||||
path := filepath.Join(i.Root, "Start "+i.ID+".command")
|
||||
if err := os.WriteFile(path, []byte(body.String()), 0o700); err != nil {
|
||||
return "", fmt.Errorf("write client launcher: %w", err)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
@@ -24,6 +24,7 @@ var (
|
||||
LocalIdentity = Spec{fileName: "BD2LocalIdentity.dll"}
|
||||
LoginUI = Spec{fileName: "BD2LoginUI.dll"}
|
||||
CashShop = Spec{fileName: "BD2CashShop.dll"}
|
||||
FChat = Spec{fileName: "BD2FChat.dll"}
|
||||
GameNames = Spec{fileName: "BD2.GameNames.dll"}
|
||||
)
|
||||
|
||||
@@ -85,7 +86,7 @@ func Install(spec Spec, gameDir, source string) (Result, error) {
|
||||
// Read both artifacts before touching the installation. The runtime table
|
||||
// library is shipped beside every plugin, including explicit development paths.
|
||||
var runtimeData []byte
|
||||
if spec == LocalIdentity || spec == LoginUI || spec == CashShop {
|
||||
if spec == LocalIdentity || spec == LoginUI || spec == CashShop || spec == FChat {
|
||||
runtimeSource := filepath.Join(filepath.Dir(source), GameNames.fileName)
|
||||
runtimeData, err = os.ReadFile(runtimeSource)
|
||||
if err != nil {
|
||||
|
||||
@@ -63,14 +63,35 @@ func installCurrentLocalCatalog(gameDir, localRoot, bundleVersion string) error
|
||||
if len(hash) == 0 || len(hash) > 1024 {
|
||||
return errors.New("local ServerData catalog hash has an invalid size")
|
||||
}
|
||||
cache, err := addressablesCacheDirectory()
|
||||
cache, err := addressablesCacheDirectory(installation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return synchronizePersistentCatalog(cache, raw, hash)
|
||||
}
|
||||
|
||||
func addressablesCacheDirectory() (string, error) {
|
||||
func addressablesCacheDirectory(installation clientlayout.Installation) (string, error) {
|
||||
gameRoot := installation.Root
|
||||
if installation.Kind == clientlayout.MacOS {
|
||||
gameRoot = filepath.Dir(gameRoot)
|
||||
}
|
||||
instanceRoot := filepath.Dir(gameRoot)
|
||||
if filepath.Base(gameRoot) == "game" {
|
||||
marker, err := os.ReadFile(filepath.Join(instanceRoot, "instance.json"))
|
||||
if err == nil {
|
||||
var owner struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(marker, &owner); err != nil || owner.SchemaVersion != 1 || owner.ID != filepath.Base(instanceRoot) {
|
||||
return "", errors.New("invalid client instance manifest for Addressables cache")
|
||||
}
|
||||
return filepath.Join(instanceRoot, "unity", "persistent", "com.unity.addressables"), nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("read client instance manifest: %w", err)
|
||||
}
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("locate user home for Addressables cache: %w", err)
|
||||
|
||||
@@ -51,6 +51,7 @@ type InstallResult struct {
|
||||
LocalIdentity plugin.Result `json:"local_identity"`
|
||||
LoginUI plugin.Result `json:"login_ui"`
|
||||
CashShop plugin.Result `json:"cash_shop"`
|
||||
FChat plugin.Result `json:"fchat"`
|
||||
}
|
||||
|
||||
func Inspect(gameDir string, versions clientconfig.ReleaseVersions) (GameStatus, error) {
|
||||
@@ -119,6 +120,7 @@ func InstallPlugins(
|
||||
localIdentitySource string,
|
||||
loginUISource string,
|
||||
cashShopSource string,
|
||||
fChatSource string,
|
||||
) (InstallResult, error) {
|
||||
status, err := Inspect(gameDir, versions)
|
||||
if err != nil {
|
||||
@@ -142,6 +144,10 @@ func InstallPlugins(
|
||||
if err != nil {
|
||||
return InstallResult{}, err
|
||||
}
|
||||
fchatSource, err := plugin.ResolvePackaged(plugin.FChat, fChatSource)
|
||||
if err != nil {
|
||||
return InstallResult{}, err
|
||||
}
|
||||
local, err := plugin.Install(plugin.LocalIdentity, gameDir, localSource)
|
||||
if err != nil {
|
||||
return InstallResult{}, err
|
||||
@@ -154,7 +160,11 @@ func InstallPlugins(
|
||||
if err != nil {
|
||||
return InstallResult{}, err
|
||||
}
|
||||
return InstallResult{LocalIdentity: local, LoginUI: login, CashShop: cash}, nil
|
||||
fchat, err := plugin.Install(plugin.FChat, gameDir, fchatSource)
|
||||
if err != nil {
|
||||
return InstallResult{}, err
|
||||
}
|
||||
return InstallResult{LocalIdentity: local, LoginUI: login, CashShop: cash, FChat: fchat}, nil
|
||||
}
|
||||
|
||||
func FetchResourcePolicy(ctx context.Context, client *http.Client, settings clientconfig.Settings, versions clientconfig.ReleaseVersions) (ResourcePolicy, error) {
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) {
|
||||
// AvatarPacket buys a character and its authored outfit before AvatarSave.
|
||||
// Current GameData: shop 1 costs 1000 type44 and grants char 1 with
|
||||
// hair 10001, outfit 40001, head accessory 20001. Motion 100001 is free.
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{State: tx}
|
||||
if _, err = g.owner.assembly.eventEconomy.Apply(ctx, "avatar-test-budget", nil, []gamedata.Reward{{Type: 44, Count: 2500}}); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
budget := g.wordCurrency()
|
||||
price := wire.AppendVarint(nil, 3, 44)
|
||||
price = wire.AppendVarint(price, 4, 1000)
|
||||
product := wire.AppendVarint(nil, 1, 1)
|
||||
product = wire.AppendBytes(product, 2, price)
|
||||
buy := g.request("/AvatarShopBuy", wire.AppendBytes(nil, 2, product))
|
||||
g.execute(buy, false)
|
||||
if got := g.wordCurrency(); got != budget-1000 {
|
||||
t.Fatalf("avatar purchase balance=%d want %d", got, budget-1000)
|
||||
}
|
||||
for _, asset := range [][2]uint64{{61, 1}, {49, 10001}, {49, 20001}, {49, 40001}} {
|
||||
if g.itemCount(asset[0], asset[1]) != 1 {
|
||||
t.Fatalf("purchased avatar asset %v is not actually owned", asset)
|
||||
}
|
||||
}
|
||||
g.execute(buy, false)
|
||||
if g.wordCurrency() != budget-1000 || g.itemCount(61, 1) != 1 {
|
||||
t.Fatal("replayed avatar purchase charged or granted again")
|
||||
}
|
||||
unowned := wire.AppendVarint(nil, 1, 1)
|
||||
unowned = wire.AppendVarint(unowned, 2, 10002)
|
||||
g.execute(g.request("/AvatarSave", wire.AppendBytes(nil, 2, unowned)), true)
|
||||
use := wire.AppendVarint(nil, 1, 1)
|
||||
use = wire.AppendVarint(use, 2, 10001)
|
||||
use = wire.AppendVarint(use, 3, 20001)
|
||||
use = wire.AppendVarint(use, 5, 40001)
|
||||
g.call("/AvatarSave", wire.AppendBytes(nil, 2, use))
|
||||
g.call("/AvatarMotionShopBuy", wire.AppendVarint(nil, 2, 100001))
|
||||
if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget-1000 {
|
||||
t.Fatal("free motion was not granted without currency consumption")
|
||||
}
|
||||
g.execute(g.request("/AvatarMotionShopBuy", wire.AppendVarint(nil, 2, 100001)), true)
|
||||
if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget-1000 {
|
||||
t.Fatal("repeated free motion changed ownership or charged currency")
|
||||
}
|
||||
wishlist := wire.AppendVarint(nil, 2, 40015)
|
||||
wishlist = wire.AppendVarint(wishlist, 2, 2)
|
||||
g.call("/AvatarShopWishListSave", wishlist)
|
||||
g.reopen()
|
||||
info := g.call("/AvatarInfo", nil)
|
||||
used, found, err := wire.Bytes(info, 1)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("avatar equipment missing after reopening: %v", err)
|
||||
}
|
||||
for field, want := range map[int]uint64{1: 1, 2: 10001, 3: 20001, 5: 40001} {
|
||||
if got, _, err := wire.Varint(used, field); err != nil || got != want {
|
||||
t.Fatalf("saved avatar slot %d=%d want %d: %v", field, got, want, err)
|
||||
}
|
||||
}
|
||||
identity, err := factory.profiles.GameIdentity(context.Background(), accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
public := g.call("/UserContentsInfo", wire.AppendVarint(nil, 2, uint64(identity.OwnerIndex)))
|
||||
profileUse, found, err := wire.Bytes(public, 34)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("profile does not project actual saved avatar: %v", err)
|
||||
}
|
||||
if got, _, _ := wire.Varint(profileUse, 5); got != 40001 {
|
||||
t.Fatalf("profile outfit=%d want purchased outfit40001", got)
|
||||
}
|
||||
login := g.call("/LoginUser", nil)
|
||||
user, _, err := wire.Bytes(login, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _, err := wire.Varint(user, 56); err != nil || got != 1 {
|
||||
t.Fatalf("login forgot initial avatar selection: %d %v", got, err)
|
||||
}
|
||||
list := g.call("/AvatarShopWishListInfo", nil)
|
||||
decodeWishlist := func(data []byte) []uint64 {
|
||||
t.Helper()
|
||||
var ids []uint64
|
||||
if err := wire.Walk(data, func(f wire.Field) error {
|
||||
if f.Number != 1 {
|
||||
return nil
|
||||
}
|
||||
if f.Type != 0 && f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
remaining := f.Value
|
||||
for len(remaining) > 0 {
|
||||
value, size := binary.Uvarint(remaining)
|
||||
if size <= 0 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
ids = append(ids, value)
|
||||
remaining = remaining[size:]
|
||||
if f.Type == 0 && len(remaining) != 0 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
ids := decodeWishlist(list)
|
||||
if len(ids) != 2 || !slices.Contains(ids, 40015) || !slices.Contains(ids, 2) {
|
||||
t.Fatalf("wishlist did not survive reopening: %v", ids)
|
||||
}
|
||||
g.call("/AvatarShopWishListSave", nil)
|
||||
g.reopen()
|
||||
list = g.call("/AvatarShopWishListInfo", nil)
|
||||
if len(decodeWishlist(list)) != 0 {
|
||||
t.Fatal("wishlist removal did not clear the persisted list")
|
||||
}
|
||||
if g.wordCurrency() != budget-1000 || g.itemCount(61, 1) != 1 || g.itemCount(50, 100001) != 1 {
|
||||
t.Fatal("reopening or profile queries changed purchased assets")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvatarDiamondPurchaseAndInvalidEquipmentBatchRemainAtomic(t *testing.T) {
|
||||
// AvatarPacket's purchase callback removes total diamonds, free first.
|
||||
// Current shop 2's premium price is 2000 diamonds. AvatarEditorUI also
|
||||
// excludes non-private parts for collab char18, including outfit40015.
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
var err error
|
||||
factory.seeds.login.UserInfo, _, err = wire.ReplaceVarint(factory.seeds.login.UserInfo, 8, 1250)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factory.seeds.login.UserInfo, _, err = wire.ReplaceVarint(factory.seeds.login.UserInfo, 9, 1000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
price := wire.AppendVarint(nil, 3, 3)
|
||||
price = wire.AppendVarint(price, 4, 2000)
|
||||
product := wire.AppendVarint(nil, 1, 2)
|
||||
product = wire.AppendBytes(product, 2, price)
|
||||
g.call("/AvatarShopBuy", wire.AppendBytes(nil, 2, product))
|
||||
g.reopen()
|
||||
readWallet := func() (uint64, uint64) {
|
||||
t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
wallet := g.owner.assembly.wallet.Snapshot(command.Context{State: tx})
|
||||
return wallet.FreeJewelry, wallet.Jewelry
|
||||
}
|
||||
if free, paid := readWallet(); free != 0 || paid != 250 {
|
||||
t.Fatalf("mixed diamond purchase persisted free=%d paid=%d want 0/250", free, paid)
|
||||
}
|
||||
if g.itemCount(61, 2) != 1 {
|
||||
t.Fatal("mixed diamond purchase did not grant the character")
|
||||
}
|
||||
use := wire.AppendVarint(nil, 1, 2)
|
||||
use = wire.AppendVarint(use, 2, 10002)
|
||||
use = wire.AppendVarint(use, 5, 40002)
|
||||
g.call("/AvatarSave", wire.AppendBytes(nil, 2, use))
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = g.owner.assembly.eventEconomy.Apply(command.Context{State: tx}, "avatar-batch-and-collab-budget", nil, []gamedata.Reward{{Type: 44, Count: 2000}, {Type: 61, ID: 18, Count: 1}, {Type: 49, ID: 40015, Count: 1}}); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
budget := g.wordCurrency()
|
||||
invalidUse := wire.AppendVarint(nil, 1, 18)
|
||||
invalidUse = wire.AppendVarint(invalidUse, 5, 40015)
|
||||
g.execute(g.request("/AvatarSave", wire.AppendBytes(nil, 2, invalidUse)), true)
|
||||
price = wire.AppendVarint(nil, 3, 44)
|
||||
price = wire.AppendVarint(price, 4, 1000)
|
||||
product = wire.AppendVarint(nil, 1, 3)
|
||||
product = wire.AppendBytes(product, 2, price)
|
||||
first := g.request("/AvatarShopBuy", wire.AppendBytes(nil, 2, product))
|
||||
last := g.request("/AvatarSave", wire.AppendBytes(nil, 2, invalidUse))
|
||||
first.Requests = append(first.Requests, last.Requests...)
|
||||
g.execute(first, true)
|
||||
g.reopen()
|
||||
if g.wordCurrency() != budget || g.itemCount(61, 3) != 0 || g.itemCount(49, 10003) != 0 {
|
||||
t.Fatal("failed equipment batch retained the preceding avatar purchase or currency debit")
|
||||
}
|
||||
info := g.call("/AvatarInfo", nil)
|
||||
current, found, err := wire.Bytes(info, 1)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("committed equipment missing: %v", err)
|
||||
}
|
||||
if char, _, _ := wire.Varint(current, 1); char != 2 {
|
||||
t.Fatalf("rejected collaboration equipment replaced committed character: %d", char)
|
||||
}
|
||||
if outfit, _, _ := wire.Varint(current, 5); outfit != 40002 {
|
||||
t.Fatalf("rejected collaboration equipment replaced committed outfit: %d", outfit)
|
||||
}
|
||||
if free, paid := readWallet(); free != 0 || paid != 250 {
|
||||
t.Fatal("failed equipment batch changed the already committed diamond split")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
chatpolicy "bd2server/internal/server/domain/chat"
|
||||
"bd2server/internal/server/domain/command"
|
||||
sharedstorage "bd2server/internal/server/storage/shared"
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNativeChatPreferencesBlocksReportsAndGuildBootstrapPersist(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
for _, account := range accounts {
|
||||
owner := openNicknamePlayer(t, factory, account)
|
||||
seedGuildQualification(t, owner)
|
||||
seedNicknameTickets(t, owner, 1)
|
||||
closeNicknamePlayer(t, owner)
|
||||
}
|
||||
var shared *sharedRuntime
|
||||
var registry *playerRegistry
|
||||
close := func() {
|
||||
if registry != nil {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry = nil
|
||||
}
|
||||
if shared != nil {
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shared = nil
|
||||
}
|
||||
}
|
||||
open := func() {
|
||||
var err error
|
||||
shared, err = openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factory.shared, factory.pvpSource = shared, shared.pvp
|
||||
registry = newPlayerRegistry(factory, time.Minute)
|
||||
}
|
||||
t.Cleanup(close)
|
||||
open()
|
||||
a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
|
||||
drainFriendPublications(t, registry, shared, accounts[0])
|
||||
drainFriendPublications(t, registry, shared, accounts[1])
|
||||
for _, client := range []*friendHTTPClient{a, b} {
|
||||
for field := 10; field <= 12; field++ {
|
||||
if appValue(client.loginBody, field) != 1 {
|
||||
t.Fatal("new account chat setting should begin enabled")
|
||||
}
|
||||
}
|
||||
}
|
||||
a.send("/ChatSettingUpdate", appScalar(3, 1), 0, 0)
|
||||
a.send("/RoomChatBlockAdd", appScalar(2, b.owner), 522, 0)
|
||||
if err := shared.store.View(context.Background(), func(tx *sharedstorage.Tx) error {
|
||||
var policy chatpolicy.Policy
|
||||
found, err := chatJSON(tx, "chat.policy", accounts[0], &policy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found || len(policy.Blocked) != 1 || policy.Blocked[0] != b.owner {
|
||||
t.Fatal("HTTP block acknowledgement preceded shared chat policy publication")
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.seq--
|
||||
a.send("/RoomChatBlockAdd", appScalar(2, b.owner), 522, 0)
|
||||
info := a.send("/RoomChatReportAndBlockInfo", nil, 521, 0)
|
||||
blocks := appRows(info, 1)
|
||||
if len(blocks) != 1 || appValue(blocks[0], 1) != b.owner || nicknameField(t, blocks[0], 2) == "" || appValue(blocks[0], 3) == 0 {
|
||||
t.Fatal("block info did not use real target and timestamp")
|
||||
}
|
||||
var reportID uint64
|
||||
for id := range factory.design.chat.ReportIDs {
|
||||
reportID = id
|
||||
break
|
||||
}
|
||||
report := append(appScalar(2, b.owner), appScalar(3, reportID)...)
|
||||
report = append(report, appMessage(4, []byte("actual reported guild message"))...)
|
||||
report = append(report, appMessage(5, []byte("-"))...)
|
||||
report = append(report, appScalar(6, uint64(time.Now().UnixMilli()))...)
|
||||
a.send("/RoomChatReport", report, 524, 0)
|
||||
a.seq--
|
||||
a.send("/RoomChatReport", report, 524, 0)
|
||||
for count := uint64(1); count < factory.design.chat.ReportLimit; count++ {
|
||||
a.send("/RoomChatReport", report, 524, 0)
|
||||
}
|
||||
a.send("/RoomChatReport", report, 524, 9003)
|
||||
info = a.send("/RoomChatReportAndBlockInfo", nil, 521, 0)
|
||||
reports := appRows(info, 2)
|
||||
if len(reports) != 1 || appValue(reports[0], 1) != factory.design.chat.ReportLimit || appValue(reports[0], 2) <= uint64(time.Now().UnixMilli()) {
|
||||
t.Fatal("report retry or limit changed daily report accounting")
|
||||
}
|
||||
if len(appRows(b.send("/RoomChatReportAndBlockInfo", nil, 521, 0), 1)) != 0 {
|
||||
t.Fatal("block affected another player's private policy")
|
||||
}
|
||||
create := guildCreateCommand(t, factory, accounts[0], "chat-guild", "ChatGuild", a.seq+1)
|
||||
created := a.send("/GuildCreate", create.Requests[0].Body[len(appScalar(1, a.seq+1)):], 296, 0)
|
||||
rows := appRows(created, 1)
|
||||
base := appRows(rows[0], 1)
|
||||
guildID := appValue(base[0], 1)
|
||||
b.send("/GuildJoin", appScalar(2, guildID), 300, 0)
|
||||
b.send("/GuildInfo", nil, 297, 0)
|
||||
beforeGuild := b.send("/GuildInfo", nil, 297, 0)
|
||||
b.send("/GuildNoticeUpdate", appMessage(2, []byte("Unauthorized notice")), 382, 9003)
|
||||
if afterGuild := b.send("/GuildInfo", nil, 297, 0); string(beforeGuild) != string(afterGuild) {
|
||||
t.Fatal("permission rejection changed guild state")
|
||||
}
|
||||
a.send("/GuildNoticeUpdate", appMessage(2, []byte("Members can chat here")), 382, 0)
|
||||
notice := b.send("/GuildNoticeInfo", nil, 381, 0)
|
||||
if nicknameField(t, notice, 1) != "Members can chat here" {
|
||||
t.Fatal("permission rejection prevented subsequent valid guild action")
|
||||
}
|
||||
b.send("/UserNicknameChange", appMessage(2, []byte("GuildMemberB")), 74, 0)
|
||||
b.send("/UserPortraitChange", appScalar(2, factory.design.profileDesign.DefaultPortraitCostumeID), 75, 0)
|
||||
drainFriendPublications(t, registry, shared, accounts[1])
|
||||
updatedMembers := appRows(a.send("/GuildInfo", nil, 297, 0), 2)
|
||||
foundUpdated := false
|
||||
for _, member := range updatedMembers {
|
||||
if appValue(member, 2) == b.owner && nicknameField(t, member, 3) == "GuildMemberB" && appValue(member, 5) == factory.design.profileDesign.DefaultPortraitCostumeID {
|
||||
foundUpdated = true
|
||||
}
|
||||
}
|
||||
if !foundUpdated {
|
||||
t.Fatal("guild member row retained stale nickname or portrait after profile edit")
|
||||
}
|
||||
close()
|
||||
open()
|
||||
a, b = friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
|
||||
if appValue(a.loginBody, 10) != 0 || appValue(a.loginBody, 11) != 1 || appValue(a.loginBody, 12) != 0 {
|
||||
t.Fatal("chat preferences did not survive store reopen")
|
||||
}
|
||||
for _, client := range []*friendHTTPClient{a, b} {
|
||||
member, base := appRows(client.loginBody, 6), appRows(client.loginBody, 7)
|
||||
if len(member) != 1 || len(base) != 1 || appValue(member[0], 1) != guildID || appValue(member[0], 2) != client.owner || appValue(base[0], 1) != guildID {
|
||||
t.Fatal("login did not bootstrap actual current guild membership")
|
||||
}
|
||||
}
|
||||
info = a.send("/RoomChatReportAndBlockInfo", nil, 521, 0)
|
||||
if len(appRows(info, 1)) != 1 || appValue(appRows(info, 2)[0], 1) != factory.design.chat.ReportLimit {
|
||||
t.Fatal("chat moderation state did not survive reopen")
|
||||
}
|
||||
a.send("/RoomChatBlockRemove", appScalar(2, b.owner), 523, 0)
|
||||
if len(appRows(a.send("/RoomChatReportAndBlockInfo", nil, 521, 0), 1)) != 0 {
|
||||
t.Fatal("unblock did not remove durable policy")
|
||||
}
|
||||
a.send("/ChatSettingUpdate", appScalar(2, 2), 0, 9003)
|
||||
b.send("/GuildLeave", nil, 298, 0)
|
||||
close()
|
||||
open()
|
||||
b = friendHTTPLogin(t, registry, accounts[1])
|
||||
if len(appRows(b.loginBody, 6)) != 0 || len(appRows(b.loginBody, 7)) != 0 {
|
||||
t.Fatal("departed guild remained in login bootstrap")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatReportQuotaResetsAtNextServerDay(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner := openNicknamePlayer(t, factory, accounts[0])
|
||||
defer closeNicknamePlayer(t, owner)
|
||||
now := time.Date(2026, 10, 11, 23, 59, 59, 0, time.UTC)
|
||||
owner.assembly.chatService.Now = func() time.Time { return now }
|
||||
owner.assembly.chatService.Target = func(command.Context, uint64) (string, error) { return "ReportedPlayer", nil }
|
||||
identity, err := factory.profiles.GameIdentity(context.Background(), accounts[1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var reportID uint64
|
||||
for id := range factory.design.chat.ReportIDs {
|
||||
reportID = id
|
||||
break
|
||||
}
|
||||
call := func(path string, fields []byte) []byte {
|
||||
t.Helper()
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{State: tx, Identity: command.Identity{AccountID: accounts[0]}, Emit: func(command.Event) error { return nil }}
|
||||
_, body, handled, err := owner.assembly.chatService.Handle(ctx, path, append(appScalar(1, 1), fields...))
|
||||
if err != nil || !handled {
|
||||
_ = tx.Rollback()
|
||||
t.Fatalf("%s %v handled%v", path, err, handled)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
report := append(appScalar(2, uint64(identity.OwnerIndex)), appScalar(3, reportID)...)
|
||||
report = append(report, appMessage(4, []byte("Reported text"))...)
|
||||
report = append(report, appMessage(5, []byte("-"))...)
|
||||
report = append(report, appScalar(6, uint64(now.UnixMilli()))...)
|
||||
call("/RoomChatReport", report)
|
||||
info := call("/RoomChatReportAndBlockInfo", nil)
|
||||
if appValue(appRows(info, 2)[0], 1) != 1 {
|
||||
t.Fatal("initial report missing")
|
||||
}
|
||||
now = now.Add(time.Second)
|
||||
info = call("/RoomChatReportAndBlockInfo", nil)
|
||||
if appValue(appRows(info, 2)[0], 1) != 0 {
|
||||
t.Fatal("daily report quota did not reset")
|
||||
}
|
||||
call("/RoomChatReport", report)
|
||||
info = call("/RoomChatReportAndBlockInfo", nil)
|
||||
if appValue(appRows(info, 2)[0], 1) != 1 {
|
||||
t.Fatal("new day report did not consume new day's quota")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
)
|
||||
|
||||
// Current 2.36.7 PackInfoResponse fields 3/4 rebuild CashShopPacket's claimed
|
||||
// lists. GameData 20261008155037 ClearPackTable group 1, pack 1 has free ticket
|
||||
// 12 and premium ticket 440000. RewardGroupTable 440001/440011 deliver 100/2000
|
||||
// free diamonds through cash mail templates 562/563 (gamedata_db.py queries).
|
||||
func TestClearPackageClaimsSurviveSessionAndDayChanges(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
account := accounts[0]
|
||||
owner, err := factory.open(account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if owner != nil {
|
||||
if err := owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
sequence := uint64(0)
|
||||
call := func(path string, fields []byte) []byte {
|
||||
t.Helper()
|
||||
sequence++
|
||||
body := append(appScalar(1, sequence), fields...)
|
||||
request := registryCommand(account, fmt.Sprintf("clear-package-%d", sequence), path, body)
|
||||
request.Identity.SessionID = fmt.Sprintf("clear-package-session-%d", sequence)
|
||||
if path == "/LoginUser" {
|
||||
request.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
|
||||
}
|
||||
reply, err := owner.Execute(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", path, err)
|
||||
}
|
||||
if len(reply.Responses) != 1 {
|
||||
t.Fatalf("%s: got %d responses", path, len(reply.Responses))
|
||||
}
|
||||
return reply.Responses[0].Body
|
||||
}
|
||||
assertClaims := func(tickets ...uint64) {
|
||||
t.Helper()
|
||||
response := call("/PackInfo", nil)
|
||||
if len(appRows(response, 1)) == 0 {
|
||||
t.Fatal("PackInfo lost world pack rows while projecting claims")
|
||||
}
|
||||
rows := appRows(response, 3)
|
||||
if len(rows) != len(tickets) {
|
||||
t.Fatalf("PackInfo projected %d story claims, want %d", len(rows), len(tickets))
|
||||
}
|
||||
var got []uint64
|
||||
for _, row := range rows {
|
||||
if appValue(row, 1) != 1 || appValue(row, 3) != 1 || appValue(row, 4) != 0 {
|
||||
t.Fatalf("PackInfo returned a different claim identity: %x", row)
|
||||
}
|
||||
got = append(got, appValue(row, 2))
|
||||
}
|
||||
slices.Sort(got)
|
||||
slices.Sort(tickets)
|
||||
if !slices.Equal(got, tickets) || len(appRows(response, 4)) != 0 {
|
||||
t.Fatalf("PackInfo mixed claim tickets or kinds: got %v, want %v", got, tickets)
|
||||
}
|
||||
}
|
||||
claim := func(ticket uint64) {
|
||||
t.Helper()
|
||||
row := append(appScalar(1, 1), appScalar(2, ticket)...)
|
||||
row = append(row, appScalar(3, 1)...)
|
||||
call("/ClearPackageReward", append(appMessage(3, row), appMessage(4, nil)...))
|
||||
}
|
||||
freeDiamonds := func() uint64 {
|
||||
t.Helper()
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
return owner.assembly.wallet.Snapshot(command.Context{State: tx}).FreeJewelry
|
||||
}
|
||||
assertCashMail := func(template, count uint64) uint64 {
|
||||
t.Helper()
|
||||
var matches [][]byte
|
||||
for _, path := range []string{"/CashMailInfo", "/MailHistoryInfo"} {
|
||||
response := call(path, appScalar(3, 100))
|
||||
for _, row := range appRows(response, 1) {
|
||||
if appValue(row, 3) == template {
|
||||
matches = append(matches, row)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(matches) != 1 {
|
||||
t.Fatalf("cash mail template %d: got %d deliveries, want one", template, len(matches))
|
||||
}
|
||||
row := matches[0]
|
||||
if !slices.Equal(appPacked(row, 8), []uint64{3}) || !slices.Equal(appPacked(row, 9), []uint64{0}) || !slices.Equal(appPacked(row, 10), []uint64{count}) {
|
||||
t.Fatalf("cash mail template %d has wrong attachments: %x", template, row)
|
||||
}
|
||||
return appValue(row, 1)
|
||||
}
|
||||
|
||||
assertClaims()
|
||||
// Seed completed story progress and ownership, retaining the real progress
|
||||
// verifier, ticket inventory, reward delivery, transaction and route chain.
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{Identity: command.Identity{AccountID: account}, State: tx}
|
||||
for _, quest := range factory.design.world.Story.Packs[1].MainQuestIDs {
|
||||
if err := owner.assembly.progressState.ClearQuest(ctx, quest, 1, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := owner.assembly.ownedItems.GrantOnce(ctx, "clear-package-premium-fixture", []gamedata.BattleReward{{Type: 19, ID: 440000, Count: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
before := freeDiamonds()
|
||||
claim(12)
|
||||
assertClaims(12)
|
||||
freeMail := assertCashMail(562, 100)
|
||||
call("/MailOpen", appScalar(2, freeMail))
|
||||
if got := freeDiamonds(); got != before+100 {
|
||||
t.Fatalf("free clear claim credited %d diamonds, want %d", got, before+100)
|
||||
}
|
||||
claim(440000)
|
||||
assertClaims(12, 440000)
|
||||
premiumMail := assertCashMail(563, 2000)
|
||||
call("/MailOpen", appScalar(2, premiumMail))
|
||||
if got := freeDiamonds(); got != before+2100 {
|
||||
t.Fatalf("premium clear claim credited %d diamonds, want %d", got, before+2100)
|
||||
}
|
||||
|
||||
if err := owner.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner = nil
|
||||
owner, err = factory.open(account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tomorrow := time.Now().AddDate(0, 0, 1)
|
||||
clock := func() time.Time { return tomorrow }
|
||||
reset := factory.design.eventAPReset.ResetSeconds - 9*3600
|
||||
owner.assembly.cashService.SetClock(clock, reset)
|
||||
owner.assembly.cashEconomy.SetClock(clock, reset)
|
||||
owner.assembly.loginPasses.SetClock(clock, reset)
|
||||
call("/LoginUser", nil)
|
||||
assertClaims(12, 440000)
|
||||
claim(12)
|
||||
claim(440000)
|
||||
assertClaims(12, 440000)
|
||||
if got := freeDiamonds(); got != before+2100 {
|
||||
t.Fatalf("claim retries credited diamonds again: got %d, want %d", got, before+2100)
|
||||
}
|
||||
if got := assertCashMail(562, 100); got != freeMail {
|
||||
t.Fatal("free clear retry created another reward mail")
|
||||
}
|
||||
if got := assertCashMail(563, 2000); got != premiumMail {
|
||||
t.Fatal("premium clear retry created another reward mail")
|
||||
}
|
||||
call("/MailOpen", appScalar(2, freeMail))
|
||||
call("/MailOpen", appScalar(2, premiumMail))
|
||||
if got := freeDiamonds(); got != before+2100 {
|
||||
t.Fatalf("mail retries credited diamonds again: got %d, want %d", got, before+2100)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"bd2server/internal/server/domain/events/calendar"
|
||||
"bd2server/internal/server/gateway/authconfig"
|
||||
"bd2server/internal/server/gateway/bootstrap"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/resources/policy"
|
||||
"context"
|
||||
@@ -41,6 +42,7 @@ type configuration struct {
|
||||
versions versionconfig.Config
|
||||
calendars *calendar.Set
|
||||
gameRules gameconfig.Config
|
||||
textModerator *textmoderation.Service
|
||||
authentication authconfig.Config
|
||||
authRuntime authconfig.Runtime
|
||||
publicResources resourcepolicy.Public
|
||||
|
||||
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/monsterhunt"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/commerce"
|
||||
"bd2server/internal/server/domain/world"
|
||||
@@ -12,6 +13,11 @@ import (
|
||||
)
|
||||
|
||||
type designCatalog struct {
|
||||
friends gamedata.FriendRules
|
||||
chat *gamedata.ChatDesign
|
||||
pvp *pvp.Rules
|
||||
guild *gamedata.GuildDesign
|
||||
nicknameTicketID uint64
|
||||
cashCatalog *commerce.Catalog
|
||||
source *gamedata.Source
|
||||
world *gamedata.WorldRules
|
||||
@@ -31,6 +37,8 @@ type designCatalog struct {
|
||||
contentTickets *gamedata.GachaContentTicketDesign
|
||||
missionDesign *gamedata.MissionDesign
|
||||
levelDesign *gamedata.AchievementLevelDesign
|
||||
profileDesign *gamedata.ProfileDesign
|
||||
avatarProfile *gamedata.AvatarProfileDesign
|
||||
equipmentSlots map[uint64]uint64
|
||||
equipmentUpgrade *gamedata.EquipmentUpgradeDesign
|
||||
equipmentCraft *gamedata.EquipmentCraftDesign
|
||||
@@ -89,6 +97,13 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) {
|
||||
calendars, gameRules := c.calendars, c.gameRules
|
||||
d := &designCatalog{source: gamedata.NewSource(gameData, gameDataVersion)}
|
||||
var err error
|
||||
if err := d.loadSharedDesign(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.nicknameTicketID, err = gamedata.LoadNicknameTicketID(gameData, gameDataVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load nickname ticket: %w", err)
|
||||
}
|
||||
gachaSchedule := calendars.GachaSeed
|
||||
var scheduleGroupIDs, stepUpGroupIDs []uint64
|
||||
for _, window := range gachaSchedule.Schedules {
|
||||
@@ -138,6 +153,14 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load user level rewards: %w", err)
|
||||
}
|
||||
d.profileDesign, err = gamedata.LoadProfileDesign(gameData, gameDataVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load default ID card layout: %w", err)
|
||||
}
|
||||
d.avatarProfile, err = gamedata.LoadAvatarProfileDesign(gameData, gameDataVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load avatar profile GameData: %w", err)
|
||||
}
|
||||
d.equipmentSlots, err = gamedata.LoadEquipmentSlots(gameData, gameDataVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load equipment slot GameData: %w", err)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/design/schedule"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
)
|
||||
|
||||
func (d *designCatalog) loadSharedDesign(c *configuration) error {
|
||||
friendRules, err := gamedata.LoadFriendRules(c.gameData, c.gameDataVersion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load friend design: %w", err)
|
||||
}
|
||||
d.friends = friendRules
|
||||
d.chat, err = gamedata.LoadChatDesign(c.gameData, c.gameDataVersion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load chat design: %w", err)
|
||||
}
|
||||
design, err := gamedata.LoadPvpDesign(c.gameData, c.gameDataVersion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load PVP design: %w", err)
|
||||
}
|
||||
policy, err := pvp.NewLocalScorePolicy(design)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var seasons []pvp.Season
|
||||
for _, content := range c.calendars.RegularService.Contents {
|
||||
var mode pvp.Mode
|
||||
switch content.ID {
|
||||
case 1:
|
||||
mode = pvp.Mirror
|
||||
case 8:
|
||||
mode = pvp.Colosseum
|
||||
default:
|
||||
continue
|
||||
}
|
||||
seen := map[uint64]bool{}
|
||||
for _, s := range []schedule.Season{content.Current, content.Next} {
|
||||
if seen[s.ID] {
|
||||
continue
|
||||
}
|
||||
seen[s.ID] = true
|
||||
regular := false
|
||||
for _, marker := range c.calendars.RegularService.Regular {
|
||||
if marker.ContentID == content.ID && s.ID >= marker.Season {
|
||||
regular = true
|
||||
}
|
||||
}
|
||||
seasons = append(seasons, pvp.Season{Mode: mode, ID: s.ID, Start: s.StartMilliseconds, End: s.EndMilliseconds, CalculateEnd: s.EndMilliseconds + c.calendars.RegularService.CalculateMilliseconds, Regular: regular})
|
||||
}
|
||||
}
|
||||
d.pvp, err = pvp.NewRules(design, seasons, policy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.guild, err = gamedata.LoadGuildDesign(c.gameData, c.gameDataVersion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load guild design: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
// Client 2.36.7 QuestPacket invokes the condition-9 completion callback before
|
||||
// the asynchronous put-down calls EndInteractionFieldObejct and sends position.
|
||||
// Read-only GameData 20261008155037: pack5 quest8 is condition9/map52;
|
||||
// action5200/group520 is type1, Disappear after quest8; action5201 has no quest.
|
||||
func TestFieldActionQuestClearAcceptsTrailingDropWithoutRestoringExpiredPosition(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[0]}
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if rule := p.design.world.Story.Packs[5].Open; rule != nil && rule.TicketID != 0 {
|
||||
if _, err := p.ownedItems.GrantOnce(ctx, "field-action-chapter-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for quest := 1; quest < 8; quest++ {
|
||||
if err := p.progressState.ClearQuest(ctx, quest, 5, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
s.protocol(t, "/PackInGameInfo", trapRequest(1, 5))
|
||||
questRequest := wire.AppendVarint(trapRequest(2, 8), 3, 5)
|
||||
s.protocol(t, "/QuestAccept", questRequest)
|
||||
s.position(t, 5, 52)
|
||||
questPosition := fieldActionPosition(52, 4.5, 0, -2.25)
|
||||
ordinaryPosition := fieldActionPosition(52, 7.25, 0, 3.5)
|
||||
drop := func(group, object uint64, position []byte) []byte {
|
||||
request := wire.AppendVarint(trapRequest(uint64(s.commands+1), 5), 3, group)
|
||||
request = wire.AppendVarint(request, 4, object)
|
||||
return wire.AppendBytes(request, 5, position)
|
||||
}
|
||||
acceptDrop := func(group, object uint64, position []byte) {
|
||||
t.Helper()
|
||||
reply, err := s.execute("/FieldObjectPositionUpdate", drop(group, object, position))
|
||||
if err != nil {
|
||||
t.Fatalf("valid put-down for object%d failed: %v", object, err)
|
||||
}
|
||||
if len(reply.Responses) != 1 || reply.Responses[0].PacketCode != 95 || len(reply.Responses[0].Body) != 0 {
|
||||
t.Fatalf("put-down must acknowledge with empty packet95: %+v", reply)
|
||||
}
|
||||
}
|
||||
positions := func() map[uint64][]byte {
|
||||
t.Helper()
|
||||
body := s.protocol(t, "/FieldObjectInfo", trapRequest(uint64(s.commands+1), 5))
|
||||
out := map[uint64][]byte{}
|
||||
for _, row := range appRows(body, 2) {
|
||||
id, found, err := wire.Varint(row, 1)
|
||||
if err != nil || !found || id == 0 {
|
||||
t.Fatalf("invalid action identity: %x, %v", row, err)
|
||||
}
|
||||
position, found, err := wire.Bytes(row, 2)
|
||||
if err != nil || !found || out[id] != nil {
|
||||
t.Fatalf("invalid or duplicate action position: %x, %v", row, err)
|
||||
}
|
||||
out[id] = position
|
||||
}
|
||||
return out
|
||||
}
|
||||
assertPositions := func(questActive bool) {
|
||||
t.Helper()
|
||||
got := positions()
|
||||
if !bytes.Equal(got[5201], ordinaryPosition) {
|
||||
t.Fatalf("ordinary movable object lost its saved drop position: %x", got[5201])
|
||||
}
|
||||
if questActive {
|
||||
if !bytes.Equal(got[5200], questPosition) {
|
||||
t.Fatalf("active quest object lost its saved drop position: %x", got[5200])
|
||||
}
|
||||
} else if _, found := got[5200]; found {
|
||||
t.Fatalf("expired quest object must not restore a position on reconnect: %x", got[5200])
|
||||
}
|
||||
}
|
||||
acceptDrop(520, 5200, questPosition)
|
||||
acceptDrop(521, 5201, ordinaryPosition)
|
||||
assertPositions(true)
|
||||
s.reopen(t)
|
||||
assertPositions(true)
|
||||
update := wire.AppendVarint(trapRequest(uint64(s.commands+1), 8), 3, 5)
|
||||
s.protocol(t, "/QuestUpdate", wire.AppendVarint(update, 4, 81))
|
||||
clear := s.protocol(t, "/QuestClear", wire.AppendVarint(trapRequest(uint64(s.commands+1), 8), 3, 5))
|
||||
if appValue(clear, 3) != 8 {
|
||||
t.Fatalf("quest clear did not complete the interacted quest: %x", clear)
|
||||
}
|
||||
assertPositions(false)
|
||||
acceptDrop(520, 5200, fieldActionPosition(52, 10.5, 0, 9.25))
|
||||
assertPositions(false)
|
||||
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
|
||||
stored, err := p.progressState.FieldActionPositions(ctx, 5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := stored[5200]; got.QuestCleared || !bytes.Equal(got.Position, questPosition) {
|
||||
t.Fatal("trailing drop overwrote the retired quest position")
|
||||
}
|
||||
})
|
||||
s.reopen(t)
|
||||
assertPositions(false)
|
||||
|
||||
for _, invalid := range []struct {
|
||||
name string
|
||||
group, object uint64
|
||||
position []byte
|
||||
}{
|
||||
{"wrong-group-after-clear", 521, 5200, questPosition},
|
||||
{"unknown-object-after-clear", 520, math.MaxInt32, questPosition},
|
||||
{"wrong-current-map-after-clear", 520, 5200, fieldActionPosition(51, 1, 0, 1)},
|
||||
{"nonfinite-after-clear", 520, 5200, fieldActionPosition(52, float32(math.Inf(1)), 0, 1)},
|
||||
} {
|
||||
t.Run(invalid.name, func(t *testing.T) {
|
||||
if _, err := s.execute("/FieldObjectPositionUpdate", drop(invalid.group, invalid.object, invalid.position)); err == nil {
|
||||
t.Fatal("quest completion bypassed the authored object or position validation")
|
||||
}
|
||||
assertPositions(false)
|
||||
})
|
||||
}
|
||||
s.position(t, 5, 51)
|
||||
if _, err := s.execute("/FieldObjectPositionUpdate", drop(701, 5501, fieldActionPosition(51, 1, 0, 1))); err == nil {
|
||||
t.Fatal("object5501 must remain unavailable until its Appear quest45 is complete")
|
||||
}
|
||||
s.position(t, 5, 52)
|
||||
s.reopen(t)
|
||||
assertPositions(false)
|
||||
}
|
||||
|
||||
func fieldActionPosition(mapID uint64, x, y, z float32) []byte {
|
||||
position := wire.AppendVarint(nil, 1, mapID)
|
||||
for i, value := range []float32{x, y, z} {
|
||||
position = binary.AppendUvarint(position, uint64((i+2)<<3|5))
|
||||
position = binary.LittleEndian.AppendUint32(position, math.Float32bits(value))
|
||||
}
|
||||
return position
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
type friendSupporterDetailHandler struct {
|
||||
owner func(command.Context) (uint64, error)
|
||||
load func(command.Context, uint64) (map[uint64][]byte, error)
|
||||
}
|
||||
|
||||
func (h friendSupporterDetailHandler) Handle(ctx command.Context, path string, request []byte) (int, []byte, bool, error) {
|
||||
if path != "/SupporterDetail" {
|
||||
return 0, nil, false, nil
|
||||
}
|
||||
var fields [4]uint64
|
||||
var seen [4]bool
|
||||
err := wire.Walk(request, func(f wire.Field) error {
|
||||
if f.Number < 1 || f.Number > 3 {
|
||||
return nil
|
||||
}
|
||||
if f.Type != 0 || seen[f.Number] {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
fields[f.Number], _ = binary.Uvarint(f.Value)
|
||||
seen[f.Number] = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 434, nil, true, err
|
||||
}
|
||||
if fields[1] == 0 || fields[1] > math.MaxInt32 || fields[2] == 0 || fields[2] > math.MaxInt64 || fields[3] > 1 {
|
||||
return 434, nil, true, wire.ErrMalformed
|
||||
}
|
||||
owner, err := h.owner(ctx)
|
||||
if err != nil {
|
||||
return 434, nil, true, err
|
||||
}
|
||||
if fields[2] == owner {
|
||||
return 0, nil, false, nil
|
||||
}
|
||||
details, err := h.load(ctx, fields[2])
|
||||
if errors.Is(err, social.ErrNotFound) || errors.Is(err, profile.ErrNotFound) {
|
||||
return 434, nil, true, &command.GameError{PacketCode: 434, ErrorType: 9003, Message: "This player is unavailable"}
|
||||
}
|
||||
if err != nil {
|
||||
return 434, nil, true, err
|
||||
}
|
||||
response, found := details[fields[3]]
|
||||
if !found {
|
||||
return 434, nil, true, &command.GameError{PacketCode: 434, ErrorType: 9003, Message: "This player's supporter slot is empty"}
|
||||
}
|
||||
return 434, append([]byte(nil), response...), true, nil
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/identity"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/gateway/transport"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type friendHTTPClient struct {
|
||||
t *testing.T
|
||||
handler http.Handler
|
||||
cookie string
|
||||
key []byte
|
||||
seq uint64
|
||||
owner uint64
|
||||
loginBody []byte
|
||||
}
|
||||
|
||||
func (c *friendHTTPClient) send(path string, fields []byte, code, errorType int) []byte {
|
||||
c.t.Helper()
|
||||
c.seq++
|
||||
request := httptest.NewRequest(http.MethodPut, "/game"+path, strings.NewReader(string(nicknameEncrypt(c.t, append(appScalar(1, c.seq), fields...), c.key))))
|
||||
request.Header.Set("Cookie", c.cookie)
|
||||
response := httptest.NewRecorder()
|
||||
c.handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
c.t.Fatalf("%s HTTP%d: %s", path, response.Code, response.Body.String())
|
||||
}
|
||||
var envelope struct {
|
||||
PacketCode, ErrorType int
|
||||
Data string
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &envelope); err != nil {
|
||||
c.t.Fatal(err)
|
||||
}
|
||||
if envelope.PacketCode != code || envelope.ErrorType != errorType {
|
||||
c.t.Fatalf("%s code/error=%d/%d want%d/%d: %s", path, envelope.PacketCode, envelope.ErrorType, code, errorType, response.Body.String())
|
||||
}
|
||||
return nicknameDecrypt(c.t, envelope.Data, c.key)
|
||||
}
|
||||
|
||||
func friendHTTPLogin(t *testing.T, registry *playerRegistry, account string) *friendHTTPClient {
|
||||
t.Helper()
|
||||
game, err := session.NewServer(registry, nicknameAuthenticator{account})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixed := []byte("abcdefghijkrstuv024680wxyzlmnopq")
|
||||
login, err := game.DispatchRaw(context.Background(), "/LoginUser", nicknameEncrypt(t, appScalar(1, 1), fixed), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var envelope struct{ Data string }
|
||||
if err := json.Unmarshal(login.Body, &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loginBody := nicknameDecrypt(t, envelope.Data, fixed)
|
||||
users := appRows(loginBody, 1)
|
||||
if len(users) != 1 {
|
||||
t.Fatal("missing LoginUser")
|
||||
}
|
||||
return &friendHTTPClient{t: t, handler: transport.HTTP{Raw: game}.Handler(), cookie: "s=" + login.Cookie, key: []byte(nicknameField(t, users[0], 3)), seq: 1, owner: appValue(users[0], 1), loginBody: loginBody}
|
||||
}
|
||||
|
||||
func drainFriendPublications(t *testing.T, registry *playerRegistry, shared *sharedRuntime, account string) {
|
||||
t.Helper()
|
||||
body, err := executePlayerSystem(context.Background(), registry, account, player.ReadOutbox, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var events []outbox.Pending
|
||||
if err := json.Unmarshal(body, &events); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, event := range events {
|
||||
if err := shared.Consume(context.Background(), event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ack, _ := json.Marshal(struct {
|
||||
Key string `json:"key"`
|
||||
Digest string `json:"digest"`
|
||||
}{event.Key, event.Digest})
|
||||
if _, err := executePlayerSystem(context.Background(), registry, account, player.AcknowledgeOutbox, ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeFriendRequestsAreBilateralDurableAndRetrySafe(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
type supporter struct{ character, costume, id uint64 }
|
||||
var supporters [2]supporter
|
||||
for i, account := range accounts {
|
||||
owner := openNicknamePlayer(t, factory, account)
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
costumeID := []uint64{101, 201}[i]
|
||||
if _, err := owner.assembly.collection.GrantCostumes(command.Context{State: tx}, "friend-supporter-fixture", []uint64{costumeID}, factory.design.rewardCostumes); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
characters := owner.assembly.worldService.CharacterService().All(command.Context{State: tx})
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, character := range characters {
|
||||
if roster.IsStoryCharacter(character) || roster.IsCharmCharacter(character) {
|
||||
continue
|
||||
}
|
||||
for _, costume := range owner.assembly.collection.Costumes() {
|
||||
if costume.ID != costumeID {
|
||||
continue
|
||||
}
|
||||
design, ok := factory.design.rewardCostumes.Character(costume.ID)
|
||||
if ok && (character.ID == design.ID || slices.Contains(design.GrowthCharacterIDs, character.ID)) {
|
||||
supporters[i] = supporter{character.InvenIndex, costume.InvenIndex, costume.ID}
|
||||
}
|
||||
}
|
||||
}
|
||||
if supporters[i].character == 0 {
|
||||
t.Fatal("no permanent owned supporter in fixture")
|
||||
}
|
||||
seedNicknameTickets(t, owner, 1)
|
||||
closeNicknamePlayer(t, owner)
|
||||
}
|
||||
var shared *sharedRuntime
|
||||
var registry *playerRegistry
|
||||
open := func() {
|
||||
var err error
|
||||
shared, err = openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factory.shared, factory.pvpSource = shared, shared.pvp
|
||||
registry = newPlayerRegistry(factory, time.Minute)
|
||||
}
|
||||
close := func() {
|
||||
if registry != nil {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry = nil
|
||||
}
|
||||
if shared != nil {
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shared = nil
|
||||
}
|
||||
}
|
||||
t.Cleanup(close)
|
||||
open()
|
||||
a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
|
||||
for i, client := range []*friendHTTPClient{a, b} {
|
||||
client.send("/UserNicknameChange", appMessage(2, []byte([]string{"FriendAlpha", "FriendBeta"}[i])), 74, 0)
|
||||
client.send("/UserPortraitChange", appScalar(2, supporters[i].id), 75, 0)
|
||||
registration := wire.AppendVarint(nil, 2, 1)
|
||||
registration = wire.AppendVarint(registration, 3, supporters[i].character)
|
||||
registration = wire.AppendVarint(registration, 4, supporters[i].costume)
|
||||
client.send("/SupporterRegister", wire.AppendVarint(registration, 5, 123), 435, 0)
|
||||
}
|
||||
drainFriendPublications(t, registry, shared, accounts[0])
|
||||
drainFriendPublications(t, registry, shared, accounts[1])
|
||||
assertRows := func(c *friendHTTPClient, path string, code int, field int, expected ...uint64) {
|
||||
t.Helper()
|
||||
rows := appRows(c.send(path, nil, code, 0), field)
|
||||
if len(rows) != len(expected) {
|
||||
t.Fatalf("%s rowcount%d want%d", path, len(rows), len(expected))
|
||||
}
|
||||
for i, row := range rows {
|
||||
if appValue(row, 1) != expected[i] || nicknameField(t, row, 4) == "" {
|
||||
t.Fatalf("%s invalid actualplayer row%x", path, row)
|
||||
}
|
||||
}
|
||||
}
|
||||
search := appRows(a.send("/FriendSearch", appScalar(2, b.owner), 212, 0), 1)
|
||||
if len(search) != 1 || appValue(search[0], 1) != b.owner {
|
||||
t.Fatal("numeric owner search did not find second player")
|
||||
}
|
||||
if nicknameField(t, search[0], 4) != "FriendBeta" || appValue(search[0], 2) != supporters[1].id {
|
||||
t.Fatal("search did not project target nickname and portrait")
|
||||
}
|
||||
assertRows(a, "/FriendRecommend", 211, 1, b.owner)
|
||||
a.send("/FriendSend", appScalar(2, b.owner), 205, 0)
|
||||
a.seq--
|
||||
a.send("/FriendSend", appScalar(2, b.owner), 205, 0)
|
||||
assertRows(a, "/FriendSendList", 209, 1, b.owner)
|
||||
assertRows(b, "/FriendReceiveList", 210, 1, a.owner)
|
||||
full := a.send("/FriendInfoList", appScalar(2, 1), 204, 0)
|
||||
if len(appRows(full, 3)) != 1 {
|
||||
t.Fatal("login allInfo omitted outgoing request")
|
||||
}
|
||||
accepted := appRows(b.send("/FriendAccept", appScalar(2, a.owner), 206, 0), 1)
|
||||
if len(accepted) != 1 || appValue(accepted[0], 1) != a.owner {
|
||||
t.Fatal("accept omitted native singularfriend response")
|
||||
}
|
||||
b.seq--
|
||||
b.send("/FriendAccept", appScalar(2, a.owner), 206, 0)
|
||||
b.send("/FriendAccept", appScalar(2, a.owner), 206, 1)
|
||||
a.send("/FriendSend", appScalar(2, b.owner), 205, 5)
|
||||
assertRows(a, "/FriendInfoList", 204, 1, b.owner)
|
||||
assertRows(b, "/FriendInfoList", 204, 1, a.owner)
|
||||
assertRows(a, "/FriendSendList", 209, 1)
|
||||
assertRows(b, "/FriendReceiveList", 210, 1)
|
||||
close()
|
||||
open()
|
||||
a, b = friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
|
||||
drainFriendPublications(t, registry, shared, accounts[0])
|
||||
drainFriendPublications(t, registry, shared, accounts[1])
|
||||
assertRows(a, "/FriendInfoList", 204, 1, b.owner)
|
||||
assertRows(b, "/FriendInfoList", 204, 1, a.owner)
|
||||
a.send("/FriendRemove", appScalar(2, b.owner), 208, 0)
|
||||
assertRows(a, "/FriendInfoList", 204, 1)
|
||||
assertRows(b, "/FriendInfoList", 204, 1)
|
||||
a.send("/FriendSend", appScalar(2, b.owner), 205, 0)
|
||||
a.send("/FriendSendRemove", appScalar(2, b.owner), 213, 0)
|
||||
assertRows(a, "/FriendSendList", 209, 1)
|
||||
assertRows(b, "/FriendReceiveList", 210, 1)
|
||||
a.send("/FriendSend", appScalar(2, b.owner), 205, 0)
|
||||
b.send("/FriendRefuse", appScalar(2, a.owner), 207, 0)
|
||||
assertRows(a, "/FriendSendList", 209, 1)
|
||||
assertRows(b, "/FriendReceiveList", 210, 1)
|
||||
a.send("/FriendSearch", appScalar(2, 9223372036854775807), 212, 1)
|
||||
assertRows(a, "/FriendRecommend", 211, 1, b.owner)
|
||||
profile := a.send("/UserContentsInfo", appScalar(2, b.owner), 215, 0)
|
||||
if appValue(profile, 1) != b.owner {
|
||||
t.Fatal("friend profile click returned caller profile")
|
||||
}
|
||||
if nicknameField(t, profile, 2) != "FriendBeta" || appValue(profile, 4) != supporters[1].id {
|
||||
t.Fatal("profile click did not show target nickname and portrait")
|
||||
}
|
||||
for _, target := range []*friendHTTPClient{a, b} {
|
||||
detail := a.send("/SupporterDetail", append(appScalar(2, target.owner), appScalar(3, 1)...), 434, 0)
|
||||
slot := appRows(detail, 1)
|
||||
expected := supporters[0]
|
||||
if target == b {
|
||||
expected = supporters[1]
|
||||
}
|
||||
if len(slot) != 1 || appValue(slot[0], 1) != target.owner || appValue(slot[0], 3) != expected.id {
|
||||
t.Fatal("supporter detail did not show chosen target's actual registered character")
|
||||
}
|
||||
battle, err := base64.StdEncoding.DecodeString(nicknameField(t, slot[0], 6))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
characters := appRows(battle, 1)
|
||||
if len(characters) != 1 || appValue(characters[0], 1) != expected.character || appValue(characters[0], 5) != expected.id || appValue(characters[0], 7) != expected.costume {
|
||||
t.Fatal("supporter battle character does not belong to selected target")
|
||||
}
|
||||
ownedCostume := false
|
||||
for _, costume := range appRows(battle, 2) {
|
||||
if appValue(costume, 1) == expected.costume && appValue(costume, 2) == expected.id {
|
||||
ownedCostume = true
|
||||
}
|
||||
}
|
||||
if !ownedCostume {
|
||||
t.Fatal("supporter battle bundle omitted selected target's registered owned costume")
|
||||
}
|
||||
}
|
||||
a.send("/SupporterDetail", appScalar(2, b.owner), 434, 9003)
|
||||
// Bypass actor receipt caches for a shared-domain accept, then reopen the
|
||||
// actual SQLite store before retrying the identical operation identity.
|
||||
durableSend := command.Identity{AccountID: accounts[0], SessionID: "durable-friend", RequestID: "send"}
|
||||
durableAccept := command.Identity{AccountID: accounts[1], SessionID: "durable-friend", RequestID: "accept"}
|
||||
if _, _, err := shared.friends.Execute(context.Background(), durableSend, a.owner, "/FriendSend", append(appScalar(1, 1), appScalar(2, b.owner)...)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
acceptWire := append(appScalar(1, 1), appScalar(2, a.owner)...)
|
||||
_, acceptedBeforeRestart, err := shared.friends.Execute(context.Background(), durableAccept, b.owner, "/FriendAccept", acceptWire)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
close()
|
||||
open()
|
||||
code, acceptedAfterRestart, err := shared.friends.Execute(context.Background(), durableAccept, b.owner, "/FriendAccept", acceptWire)
|
||||
if err != nil || code != 206 || !slices.Equal(acceptedBeforeRestart, acceptedAfterRestart) {
|
||||
t.Fatalf("durable accept retry code=%d error=%v changed=%v", code, err, !slices.Equal(acceptedBeforeRestart, acceptedAfterRestart))
|
||||
}
|
||||
a, b = friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
|
||||
drainFriendPublications(t, registry, shared, accounts[0])
|
||||
drainFriendPublications(t, registry, shared, accounts[1])
|
||||
assertRows(a, "/FriendInfoList", 204, 1, b.owner)
|
||||
assertRows(b, "/FriendInfoList", 204, 1, a.owner)
|
||||
b.send("/FriendAccept", appScalar(2, a.owner), 206, 1)
|
||||
a.send("/FriendRemove", appScalar(2, b.owner), 208, 0)
|
||||
assertRows(a, "/FriendInfoList", 204, 1)
|
||||
assertRows(b, "/FriendReceiveList", 210, 1)
|
||||
}
|
||||
|
||||
func TestNativeFriendSendRejectsFullOutgoingListWithoutChangingEitherPlayer(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.shared, factory.pvpSource = shared, shared.pvp
|
||||
repository, ok := factory.profiles.(identity.Repository)
|
||||
if !ok {
|
||||
t.Fatal("integration identity store cannot register accounts")
|
||||
}
|
||||
registration, err := identity.New(identity.Config{Providers: map[string]string{"discord": "integration-client"}, DeviceTTL: time.Minute, AccessTTL: time.Hour, RefreshTTL: 24 * time.Hour}, repository)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// CommunityDefineTable field6 supplies the outgoing limit; each target is
|
||||
// a registered account projected from its own persisted starter state.
|
||||
var targets []uint64
|
||||
for i := uint64(0); i < factory.design.friends.Sent; i++ {
|
||||
device, err := registration.CreateDevice("discord", "127.0.0.1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
auth, err := registration.Start("discord", device.ID, device.StartTicket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := registration.CompleteDevice(auth.ID, "discord", identity.ProviderIdentity{Issuer: "https://discord.com", Subject: fmt.Sprintf("%d", 30000000+i)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := registration.Poll(device.ID, device.Secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
account, err := registration.ValidateAccess(result.Tokens.AccessToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner := openNicknamePlayer(t, factory, account)
|
||||
if err := owner.readLocal(context.Background(), command.Identity{AccountID: account}, func(c command.Context) error {
|
||||
profile, err := owner.assembly.publicFriendProfile(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
targets = append(targets, profile.OwnerIndex)
|
||||
return shared.friends.Publish(context.Background(), profile)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
closeNicknamePlayer(t, owner)
|
||||
}
|
||||
registry := newPlayerRegistry(factory, time.Minute)
|
||||
t.Cleanup(func() {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
|
||||
drainFriendPublications(t, registry, shared, accounts[0])
|
||||
drainFriendPublications(t, registry, shared, accounts[1])
|
||||
for _, target := range targets {
|
||||
a.send("/FriendSend", appScalar(2, target), 205, 0)
|
||||
}
|
||||
before := a.send("/FriendSendList", nil, 209, 0)
|
||||
if len(appRows(before, 1)) != len(targets) {
|
||||
t.Fatal("outgoing requests did not reach the current GameData limit")
|
||||
}
|
||||
// Current native Send error3 maps to the user's full outgoing list (120503).
|
||||
a.send("/FriendSend", appScalar(2, b.owner), 205, 3)
|
||||
if after := a.send("/FriendSendList", nil, 209, 0); !slices.Equal(before, after) {
|
||||
t.Fatal("capacity error altered existing outgoing requests")
|
||||
}
|
||||
if rows := appRows(b.send("/FriendReceiveList", nil, 210, 0), 1); len(rows) != 0 {
|
||||
t.Fatal("capacity error created a counterpart incoming request")
|
||||
}
|
||||
a.send("/FriendSendRemove", appScalar(2, targets[0]), 213, 0)
|
||||
a.send("/FriendSend", appScalar(2, b.owner), 205, 0)
|
||||
rows := appRows(b.send("/FriendReceiveList", nil, 210, 0), 1)
|
||||
if len(rows) != 1 || appValue(rows[0], 1) != a.owner {
|
||||
t.Fatal("freeing one outgoing slot did not permit a bilateral request")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
)
|
||||
|
||||
func raidCurrency(t *testing.T, g *guildGameplay) uint64 {
|
||||
t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := tx.Rollback(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
values, err := g.owner.assembly.eventEconomy.AdditionalCurrencies(command.Context{State: tx, Identity: command.Identity{AccountID: g.account}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return values[44]
|
||||
}
|
||||
|
||||
func TestNewPlayerGuildBootstrapDoesNotRequireGuildUnlock(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.shared, factory.pvpSource = shared, shared.pvp
|
||||
g := &guildGameplay{t: t, factory: factory, account: accounts[0]}
|
||||
g.open()
|
||||
t.Cleanup(g.close)
|
||||
g.pvpCall("/LoginUser", nil)
|
||||
if err = g.owner.guildQualification(context.Background(), command.Identity{AccountID: g.account}, "/GuildRaidDeckSave"); !errors.Is(err, social.ErrIneligible) {
|
||||
t.Fatalf("new player must start with guild content locked: %v", err)
|
||||
}
|
||||
before := g.balance()
|
||||
// IntroUI.SetData sends both social requests even before guild content is unlocked.
|
||||
bootstrap := registryCommand(g.account, "new-player-guild-bootstrap", "/GuildInitInfo", appScalar(1, 2))
|
||||
bootstrap.Requests = append(bootstrap.Requests,
|
||||
player.Request{Path: "/GuildRaidSeasonReward", Body: appScalar(1, 3)},
|
||||
player.Request{Path: "/ItemInfo", Body: appScalar(1, 4)})
|
||||
reply, err := g.execute(bootstrap)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(reply.Responses) != 3 || reply.Responses[0].PacketCode != 332 || reply.Responses[1].PacketCode != 310 {
|
||||
t.Fatalf("incomplete startup batch: %+v", reply.Responses)
|
||||
}
|
||||
reward := reply.Responses[1].Body
|
||||
if appValue(reward, 2) != 0 || len(appRows(reward, 1)) != 0 {
|
||||
t.Fatalf("new player received a phantom guild raid reward: %x", reward)
|
||||
}
|
||||
if after := g.balance(); before != after {
|
||||
t.Fatalf("empty startup claim changed wallet: before=%+v after=%+v", before, after)
|
||||
}
|
||||
entitlements, err := shared.guild.Entitlements(context.Background(), g.account)
|
||||
if err != nil || len(entitlements) != 0 {
|
||||
t.Fatalf("startup created raid entitlements: %v, %v", entitlements, err)
|
||||
}
|
||||
g.member(0)
|
||||
_, err = g.execute(registryCommand(g.account, "still-locked-raid-deck", "/GuildRaidDeckSave", appScalar(1, 5)))
|
||||
if !errors.Is(err, social.ErrIneligible) {
|
||||
t.Fatalf("locked guild mutation accepted after bootstrap: %v", err)
|
||||
}
|
||||
g.seq = 5
|
||||
if items := g.pvpCall("/ItemInfo", nil); len(items) == 0 {
|
||||
t.Fatal("normal player request failed after guild bootstrap")
|
||||
}
|
||||
}
|
||||
|
||||
type raidFixture struct {
|
||||
factory *PlayerFactory
|
||||
shared *sharedRuntime
|
||||
a, b *guildGameplay
|
||||
guild, season uint64
|
||||
seasonEnd time.Time
|
||||
clock *atomic.Int64
|
||||
}
|
||||
|
||||
func (f *raidFixture) open(g *guildGameplay) {
|
||||
g.open()
|
||||
f.bindClock(g)
|
||||
}
|
||||
|
||||
func (f *raidFixture) bindClock(g *guildGameplay) {
|
||||
config := g.owner.socialServiceConfig()
|
||||
config.Now = func() time.Time { return time.Unix(0, f.clock.Load()) }
|
||||
service, err := social.NewService(config)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
g.owner.sharedSocial = service
|
||||
g.owner.assembly.battleService.AttachEventBattle(service)
|
||||
}
|
||||
|
||||
func newRaidFixture(t *testing.T) *raidFixture {
|
||||
t.Helper()
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
clock := new(atomic.Int64)
|
||||
clock.Store(time.Now().UnixNano())
|
||||
var season uint64
|
||||
var seasonEnd time.Time
|
||||
for i, content := range factory.options.calendars.RegularService.Contents {
|
||||
if content.ID != 6 {
|
||||
continue
|
||||
}
|
||||
season = content.Current.ID
|
||||
now := time.Unix(0, clock.Load())
|
||||
content.Current.StartMilliseconds = uint64(now.Add(-time.Hour).UnixMilli())
|
||||
seasonEnd = now.Add(time.Hour)
|
||||
content.Current.EndMilliseconds = uint64(seasonEnd.UnixMilli())
|
||||
factory.options.calendars.RegularService.Contents[i] = content
|
||||
break
|
||||
}
|
||||
if season == 0 {
|
||||
t.Fatal("selected calendar has no guild raid season")
|
||||
}
|
||||
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.shared, factory.pvpSource = shared, shared.pvp
|
||||
a := &guildGameplay{t: t, factory: factory, account: accounts[0]}
|
||||
b := &guildGameplay{t: t, factory: factory, account: accounts[1]}
|
||||
f := &raidFixture{factory: factory, shared: shared, a: a, b: b, season: season, seasonEnd: seasonEnd, clock: clock}
|
||||
f.open(a)
|
||||
f.open(b)
|
||||
t.Cleanup(a.close)
|
||||
t.Cleanup(b.close)
|
||||
seedGuildQualification(t, a.owner)
|
||||
seedGuildQualification(t, b.owner)
|
||||
f.bindClock(a)
|
||||
f.bindClock(b)
|
||||
create := guildCreateCommand(t, factory, a.account, "raid-guild-create", "RaidGuild", 1)
|
||||
reply, err := a.execute(create)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
guild := guildIDFromCreate(t, reply)
|
||||
f.guild = guild
|
||||
b.pvpCall("/GuildJoin", appScalar(2, guild))
|
||||
return f
|
||||
}
|
||||
|
||||
func TestNativeGuildRaidPresetsPersistPurchaseAndMetadata(t *testing.T) {
|
||||
f := newRaidFixture(t)
|
||||
factory, a := f.factory, f.a
|
||||
presets := factory.design.presetDesign
|
||||
if presets.BaseCount >= presets.Maximum {
|
||||
t.Fatal("current guild preset design has no purchasable slot")
|
||||
}
|
||||
login := appRows(a.pvpCall("/LoginUser", nil), 1)
|
||||
if len(login) != 1 || appValue(login[0], 53) != presets.BaseCount {
|
||||
t.Fatal("guild preset count before purchase does not match GameData")
|
||||
}
|
||||
tx, err := a.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := command.Context{Identity: command.Identity{AccountID: a.account}, State: tx}
|
||||
if _, err = a.owner.assembly.eventEconomy.Apply(c, "raid-preset-budget", nil, []gamedata.Reward{{Type: presets.PriceType, ID: presets.PriceID, Count: presets.Price}}); err != nil {
|
||||
if rollback := tx.Rollback(); rollback != nil {
|
||||
t.Error(rollback)
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walletBefore := a.balance()
|
||||
a.seq++
|
||||
purchase := registryCommand(a.account, "raid-slot-purchase", "/GuildRaidPresetSlotAdd", append(appScalar(1, a.seq), appScalar(2, 1)...))
|
||||
if _, err = a.execute(purchase); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walletAfter := walletBefore
|
||||
switch presets.PriceType {
|
||||
case 2:
|
||||
walletAfter.Jewelry -= presets.Price
|
||||
case 3:
|
||||
walletAfter.FreeJewelry -= presets.Price
|
||||
case 4:
|
||||
walletAfter.Gold -= presets.Price
|
||||
case 12:
|
||||
walletAfter.Catalyst -= presets.Price
|
||||
default:
|
||||
t.Fatal("unsupported authored preset currency")
|
||||
}
|
||||
if actual := a.balance(); actual != walletAfter {
|
||||
t.Fatalf("guild preset purchase charged %+v, want %+v", actual, walletAfter)
|
||||
}
|
||||
login = appRows(a.pvpCall("/LoginUser", nil), 1)
|
||||
if len(login) != 1 || appValue(login[0], 53) != presets.BaseCount+1 {
|
||||
t.Fatal("purchased guild preset slot was not projected into login")
|
||||
}
|
||||
a.close()
|
||||
f.open(a)
|
||||
login = appRows(a.pvpCall("/LoginUser", nil), 1)
|
||||
if len(login) != 1 || appValue(login[0], 53) != presets.BaseCount+1 {
|
||||
t.Fatal("guild preset count did not survive player reload")
|
||||
}
|
||||
if _, err = a.execute(purchase); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.balance() != walletAfter {
|
||||
t.Fatal("durable guild preset slot replay charged twice")
|
||||
}
|
||||
changedSlot := presets.BaseCount
|
||||
fields := appMessage(2, []byte("Raid Setup"))
|
||||
fields = append(fields, appScalar(3, 0)...)
|
||||
fields = append(fields, appScalar(4, 1)...)
|
||||
fields = append(fields, appScalar(5, changedSlot)...)
|
||||
a.pvpCall("/GuildRaidPresetInfoChange", fields)
|
||||
rows := appRows(a.pvpCall("/GuildRaidPresetInfo", nil), 1)
|
||||
found := false
|
||||
for _, row := range rows {
|
||||
if appValue(row, 4) == changedSlot {
|
||||
names := appRows(row, 1)
|
||||
found = len(names) == 1 && string(names[0]) == "Raid Setup" && appValue(row, 3) == 1
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("native guild preset metadata update did not persist")
|
||||
}
|
||||
a.pvpCall("/GuildRaidPresetDelete", appScalar(2, changedSlot))
|
||||
for _, row := range appRows(a.pvpCall("/GuildRaidPresetInfo", nil), 1) {
|
||||
if appValue(row, 4) == changedSlot {
|
||||
t.Fatal("native deleted guild preset remains visible")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeGuildRaidSettlesBothMembersAndClaimsOnce(t *testing.T) {
|
||||
f := newRaidFixture(t)
|
||||
factory, shared, a, b, guild, season := f.factory, f.shared, f.a, f.b, f.guild, f.season
|
||||
bosses := factory.design.guild.Raid.Bosses[season]
|
||||
if len(bosses) == 0 {
|
||||
t.Fatal("calendar raid season has no current GameData bosses")
|
||||
}
|
||||
level := uint64(1)
|
||||
boss, exists := bosses[level]
|
||||
if !exists {
|
||||
t.Fatal("current raid season lacks first boss")
|
||||
}
|
||||
before := map[string]uint64{a.account: raidCurrency(t, a), b.account: raidCurrency(t, b)}
|
||||
scores := map[string]uint64{}
|
||||
for i, g := range []*guildGameplay{a, b} {
|
||||
_, character := g.ownedPVPDeck()
|
||||
deck := appScalar(1, character)
|
||||
g.pvpCall("/GuildRaidDeckSave", appMessage(2, deck))
|
||||
entered := g.pvpCall("/GuildRaidBossBattleEnter", appScalar(2, level))
|
||||
if appValue(entered, 4) != 1 {
|
||||
t.Fatal("raid enter omitted native engine mode")
|
||||
}
|
||||
g.pvpCall("/BattleStart", appScalar(2, boss.DeckID))
|
||||
g.seq++
|
||||
end := registryCommand(g.account, fmt.Sprintf("raid-end-%d", i), "/BattleEnd", append(appScalar(1, g.seq), appScalar(2, 1)...))
|
||||
settled, err := g.execute(end)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(settled.Responses) != 1 || settled.Responses[0].PacketCode != 15 {
|
||||
t.Fatalf("raid did not use native battle settlement: %+v", settled)
|
||||
}
|
||||
details := appRows(settled.Responses[0].Body, 25)
|
||||
if len(details) != 1 {
|
||||
t.Fatal("raid result lacks authored score breakdown")
|
||||
}
|
||||
turn := uint64(math.Max(0, factory.design.guild.Raid.TurnAddScore-factory.design.guild.Raid.TurnScoreValue))
|
||||
if appValue(details[0], 1) != boss.AddScore || appValue(details[0], 2) != turn || appValue(details[0], 3) != 0 {
|
||||
t.Fatalf("raid score breakdown does not follow one completed round: %x", details[0])
|
||||
}
|
||||
scores[g.account] = boss.AddScore + turn
|
||||
afterBoss := raidCurrency(t, g)
|
||||
var expectedBossCurrency uint64
|
||||
for _, reward := range boss.Rewards {
|
||||
if reward.Type == 39 {
|
||||
expectedBossCurrency += reward.Count
|
||||
}
|
||||
}
|
||||
if afterBoss-before[g.account] != expectedBossCurrency {
|
||||
t.Fatalf("boss reward currency gain=%d want %d", afterBoss-before[g.account], expectedBossCurrency)
|
||||
}
|
||||
g.drainPVP()
|
||||
retry, err := g.execute(end)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(retry.Responses[0].Body, settled.Responses[0].Body) || raidCurrency(t, g) != afterBoss {
|
||||
t.Fatal("raid battle replay duplicated boss reward or changed score")
|
||||
}
|
||||
}
|
||||
members, err := shared.guild.MemberStandings(context.Background(), guild, season)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]uint64{}
|
||||
for _, member := range members {
|
||||
got[member.AccountID] = member.Score
|
||||
}
|
||||
if !maps.Equal(got, scores) {
|
||||
t.Fatalf("shared raid bests missing participants: %v want %v", got, scores)
|
||||
}
|
||||
standing, err := shared.guild.Season(context.Background(), guild, season)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total := scores[a.account] + scores[b.account]
|
||||
if standing.TotalScore != total || standing.Pending != 0 {
|
||||
t.Fatalf("guild score must sum distinct personal bests: %+v", standing)
|
||||
}
|
||||
ranked := a.pvpCall("/GuildRaidSeasonRanking", appScalar(2, season))
|
||||
own := appRows(ranked, 2)
|
||||
if len(own) != 1 || appValue(own[0], 3) != guild || appValue(own[0], 2) != total {
|
||||
t.Fatal("native guild season ranking omitted own settled guild total")
|
||||
}
|
||||
|
||||
beforeRepeat := raidCurrency(t, a)
|
||||
a.pvpCall("/GuildRaidBossBattleEnter", appScalar(2, level))
|
||||
a.pvpCall("/BattleStart", appScalar(2, boss.DeckID))
|
||||
a.pvpCall("/BattleEnd", appScalar(2, 1))
|
||||
a.drainPVP()
|
||||
standing, err = shared.guild.Season(context.Background(), guild, season)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if standing.TotalScore != total || raidCurrency(t, a) != beforeRepeat {
|
||||
t.Fatal("equal raid score was summed twice or boss reward repeated")
|
||||
}
|
||||
f.clock.Store(f.seasonEnd.Add(time.Millisecond).UnixNano())
|
||||
if err = shared.guild.FinalizeSeason(context.Background(), season, time.Unix(0, f.clock.Load()).UnixMilli()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.pvpCall("/GuildLeave", nil)
|
||||
departed, err := shared.guild.Account(context.Background(), b.account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if departed.GuildID != 0 {
|
||||
t.Fatal("native guild leave did not remove departed member")
|
||||
}
|
||||
for _, g := range []*guildGameplay{a, b} {
|
||||
beforeClaim := raidCurrency(t, g)
|
||||
itemsBefore := appItemTotals(g.pvpCall("/ItemInfo", nil))
|
||||
g.seq++
|
||||
claim := registryCommand(g.account, "raid-score-claim", "/GuildRaidSeasonReward", appScalar(1, g.seq))
|
||||
claimed, err := g.execute(claim)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(claimed.Responses) != 1 || claimed.Responses[0].PacketCode != 310 {
|
||||
t.Fatal("raid claim has wrong native response")
|
||||
}
|
||||
if len(claimed.Responses[0].Body) == 0 {
|
||||
t.Fatal("earned score reward omitted native grant bundle")
|
||||
}
|
||||
afterClaim := raidCurrency(t, g)
|
||||
itemsAfter := appItemTotals(g.pvpCall("/ItemInfo", nil))
|
||||
if afterClaim == beforeClaim && maps.Equal(itemsBefore, itemsAfter) {
|
||||
t.Fatal("earned guild score reward did not change any owned assets")
|
||||
}
|
||||
retry, err := g.execute(claim)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(claimed.Responses[0].Body, retry.Responses[0].Body) || raidCurrency(t, g) != afterClaim || !maps.Equal(itemsAfter, appItemTotals(g.pvpCall("/ItemInfo", nil))) {
|
||||
t.Fatal("guild score reward replay credited twice")
|
||||
}
|
||||
g.close()
|
||||
f.open(g)
|
||||
durable, err := g.execute(claim)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(durable.Responses[0].Body, claimed.Responses[0].Body) || raidCurrency(t, g) != afterClaim {
|
||||
t.Fatal("raid reward durable retry changed grant")
|
||||
}
|
||||
g.drainPVP()
|
||||
ent, err := shared.guild.Entitlements(context.Background(), g.account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ent) != 0 {
|
||||
t.Fatalf("confirmed reward remains claimable: %+v", ent)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
)
|
||||
|
||||
type missionGameplay struct {
|
||||
t *testing.T
|
||||
factory *PlayerFactory
|
||||
account string
|
||||
owner *playerInstance
|
||||
now time.Time
|
||||
seq uint64
|
||||
}
|
||||
|
||||
func newMissionGameplay(t *testing.T) *missionGameplay {
|
||||
t.Helper()
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
days := (8 - int(now.Weekday())) % 7
|
||||
g := &missionGameplay{t: t, factory: factory, account: accounts[0], owner: owner, now: time.Date(now.Year(), now.Month(), now.Day()+days, 12, 0, 0, 0, time.UTC)}
|
||||
owner.assembly.missionService.SetClock(func() time.Time { return g.now })
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
return g
|
||||
}
|
||||
|
||||
func (g *missionGameplay) execute(path string, fields []byte) ([]byte, error) {
|
||||
g.seq++
|
||||
request := registryCommand(g.account, fmt.Sprintf("mission-%d", g.seq), path, append(appScalar(1, g.seq), fields...))
|
||||
if path == "/LoginUser" {
|
||||
request.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
|
||||
}
|
||||
reply, err := g.owner.Execute(context.Background(), request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(reply.Responses) != 1 {
|
||||
return nil, fmt.Errorf("%s returned %d responses", path, len(reply.Responses))
|
||||
}
|
||||
return reply.Responses[0].Body, nil
|
||||
}
|
||||
|
||||
func (g *missionGameplay) call(path string, fields []byte) []byte {
|
||||
g.t.Helper()
|
||||
response, err := g.execute(path, fields)
|
||||
if err != nil {
|
||||
g.t.Fatalf("%s: %v", path, err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func (g *missionGameplay) reopen() {
|
||||
g.t.Helper()
|
||||
if err := g.owner.Close(); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
g.owner = nil
|
||||
var err error
|
||||
g.owner, err = g.factory.open(g.account)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
g.owner.assembly.missionService.SetClock(func() time.Time { return g.now })
|
||||
}
|
||||
|
||||
func (g *missionGameplay) wallet() assets.Currency {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
return g.owner.assembly.wallet.Snapshot(command.Context{State: tx})
|
||||
}
|
||||
|
||||
func (g *missionGameplay) itemCount(typ, id uint64) uint64 {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
var count uint64
|
||||
for _, item := range g.owner.assembly.ownedItems.All(command.Context{State: tx}) {
|
||||
if item.Type == typ && item.ID == id {
|
||||
count += item.Count
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func (g *missionGameplay) assertMission(groupType, group, id, value uint64, claimed bool) {
|
||||
g.t.Helper()
|
||||
var row []byte
|
||||
for _, candidate := range appRows(g.call("/MissionInfo", nil), 1) {
|
||||
if appValue(candidate, 1) == group && appValue(candidate, 2) == id && appValue(candidate, 3) == groupType {
|
||||
row = candidate
|
||||
}
|
||||
}
|
||||
if appValue(row, 4) != value || (appValue(row, 5) == 1) != claimed {
|
||||
g.t.Fatalf("mission %d/%d/%d: value=%d claimed=%v, want value=%d claimed=%v", groupType, group, id, appValue(row, 4), appValue(row, 5) == 1, value, claimed)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *missionGameplay) claim(all bool, groupType, group, id uint64) []byte {
|
||||
fields := append(appScalar(3, groupType), appScalar(4, group)...)
|
||||
fields = append(fields, appScalar(5, id)...)
|
||||
if all {
|
||||
fields = append(fields, appScalar(2, 1)...)
|
||||
}
|
||||
return g.call("/MissionClear", fields)
|
||||
}
|
||||
|
||||
func missionRewardCount(t *testing.T, response []byte, typ, id uint64) uint64 {
|
||||
t.Helper()
|
||||
bundles := appRows(response, 1)
|
||||
if len(bundles) != 1 {
|
||||
t.Fatalf("MissionClear must return one reward envelope, got %d", len(bundles))
|
||||
}
|
||||
var total uint64
|
||||
for _, row := range appRows(bundles[0], 1) {
|
||||
if appValue(row, 3) == typ && appValue(row, 2) == id {
|
||||
total += appValue(row, 4)
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// Current client MissionUI bulk requests select group_type 0 (daily) or 1
|
||||
// (weekly), with group/id omitted. GameData 20261008155037 and LocalText
|
||||
// 5500001/5501001 specify one login per day: daily 1/101 gives 4000 gold;
|
||||
// weekly 2/201 requires five days and gives 50000. Daily 1/110 gives box
|
||||
// 504145 x 1; weekly 2/210 counts five completed group-1 missions, giving x 4.
|
||||
func TestMissionLoginClaimsKeepDailyAndWeeklyPeriodsSeparate(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
start := g.now
|
||||
before := g.wallet()
|
||||
boxes := g.itemCount(9, 504145)
|
||||
for day := range 5 {
|
||||
g.now = start.AddDate(0, 0, day)
|
||||
g.call("/LoginUser", nil)
|
||||
g.call("/LoginUser", nil)
|
||||
g.assertMission(0, 1, 101, 1, false)
|
||||
g.assertMission(1, 2, 201, uint64(day+1), false)
|
||||
g.assertMission(1, 2, 210, min(uint64(2*(day+1)), uint64(5)), false)
|
||||
var response []byte
|
||||
if day == 0 {
|
||||
response = g.claim(false, 0, 1, 101)
|
||||
g.claim(false, 0, 1, 110)
|
||||
} else {
|
||||
response = g.claim(true, 0, 0, 0)
|
||||
}
|
||||
if missionRewardCount(t, response, 4, 0) != 4000 || g.wallet().Gold != before.Gold+uint64(day+1)*4000 || g.itemCount(9, 504145) != boxes+uint64(day+1) {
|
||||
t.Fatalf("daily day %d did not grant exactly one daily gold/box reward", day+1)
|
||||
}
|
||||
g.assertMission(1, 2, 201, uint64(day+1), false)
|
||||
g.assertMission(1, 2, 210, min(uint64(2*(day+1)), uint64(5)), false)
|
||||
}
|
||||
g.reopen()
|
||||
g.call("/LoginUser", nil)
|
||||
g.assertMission(1, 2, 201, 5, false)
|
||||
g.now = start.AddDate(0, 0, 5)
|
||||
g.call("/LoginUser", nil)
|
||||
weekly := g.claim(true, 1, 0, 0)
|
||||
if missionRewardCount(t, weekly, 4, 0) != 50000 || g.wallet().Gold != before.Gold+70000 || g.itemCount(9, 504145) != boxes+9 {
|
||||
t.Fatal("weekly bulk did not grant only its 50000 gold and four boxes")
|
||||
}
|
||||
g.assertMission(0, 1, 101, 1, false)
|
||||
g.assertMission(1, 2, 201, 5, true)
|
||||
g.assertMission(1, 2, 210, 5, true)
|
||||
g.claim(true, 0, 0, 0)
|
||||
g.call("/MissionSectionReward", append(appScalar(2, 0), appScalar(3, 1)...))
|
||||
if g.wallet().Gold != before.Gold+74000 || g.wallet().Catalyst != before.Catalyst+70 || g.itemCount(9, 504145) != boxes+10 {
|
||||
t.Fatal("daily rewards or first section were consumed by the weekly claim")
|
||||
}
|
||||
retry := g.claim(false, 1, 2, 201)
|
||||
if missionRewardCount(t, retry, 4, 0) != 0 || g.wallet().Gold != before.Gold+74000 {
|
||||
t.Fatal("a new request for an already received weekly reward echoed or paid gold")
|
||||
}
|
||||
g.reopen()
|
||||
if g.wallet().Gold != before.Gold+74000 || g.itemCount(9, 504145) != boxes+10 {
|
||||
t.Fatal("reopening SQLite lost granted mission rewards")
|
||||
}
|
||||
for offset := range 5 {
|
||||
day := offset + 7
|
||||
g.now = start.AddDate(0, 0, day)
|
||||
g.call("/LoginUser", nil)
|
||||
g.assertMission(1, 2, 201, uint64(day-6), false)
|
||||
g.claim(true, 0, 0, 0)
|
||||
if day == 7 {
|
||||
g.call("/MissionSectionReward", append(appScalar(2, 0), appScalar(3, 1)...))
|
||||
}
|
||||
}
|
||||
g.claim(false, 1, 2, 201)
|
||||
g.claim(true, 1, 2, 0)
|
||||
if g.wallet().Gold != before.Gold+144000 || g.wallet().Catalyst != before.Catalyst+140 || g.itemCount(9, 504145) != boxes+19 {
|
||||
t.Fatal("new daily/weekly periods did not pay the newly earned currency and items")
|
||||
}
|
||||
g.assertMission(1, 2, 201, 5, true)
|
||||
g.assertMission(1, 2, 210, 5, true)
|
||||
}
|
||||
|
||||
func (g *missionGameplay) completeFixtures(keys []gamedata.MissionKey) {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx}
|
||||
for _, key := range keys {
|
||||
if err := g.owner.assembly.missionService.CompleteMission(ctx, key); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Section rewards count claimed tasks in their selected tab. Independent
|
||||
// current GameData rows: daily 101/102/103 give catalyst70, box504153 x1,
|
||||
// diamonds60 at 1/3/5 claims; weekly 201 gives box504144 x4 at three claims.
|
||||
func TestMissionSectionsStayInSelectedPeriodAndPayAgainNextWeek(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
before := g.wallet()
|
||||
dailyBoxes, weeklyBoxes := g.itemCount(9, 504153), g.itemCount(9, 504144)
|
||||
keys := []gamedata.MissionKey{{GroupType: 0, GroupID: 1, ID: 101}, {GroupType: 0, GroupID: 1, ID: 109}, {GroupType: 0, GroupID: 1, ID: 111}, {GroupType: 0, GroupID: 1, ID: 113}, {GroupType: 1, GroupID: 2, ID: 201}, {GroupType: 1, GroupID: 2, ID: 218}, {GroupType: 1, GroupID: 2, ID: 219}}
|
||||
for offset := range 2 {
|
||||
period := offset + 1
|
||||
g.call("/LoginUser", nil)
|
||||
g.completeFixtures(keys)
|
||||
g.claim(true, 0, 0, 0)
|
||||
g.claim(true, 1, 0, 0)
|
||||
response := g.call("/MissionSectionReward", appScalar(3, 1))
|
||||
var catalyst uint64
|
||||
for _, row := range appRows(response, 1) {
|
||||
if appValue(row, 3) == 12 {
|
||||
catalyst += appValue(row, 4)
|
||||
}
|
||||
}
|
||||
if catalyst != 70 || g.wallet().Catalyst != before.Catalyst+uint64(period)*70 || g.wallet().FreeJewelry != before.FreeJewelry+uint64(period)*60 || g.itemCount(9, 504153) != dailyBoxes+uint64(period) || g.itemCount(9, 504144) != weeklyBoxes+uint64(period-1)*4 {
|
||||
t.Fatal("daily section bulk mixed weekly rewards or failed to grant its current rewards")
|
||||
}
|
||||
g.call("/MissionSectionReward", append(appScalar(2, 1), appScalar(4, 201)...))
|
||||
if g.itemCount(9, 504144) != weeklyBoxes+uint64(period)*4 {
|
||||
t.Fatal("weekly section did not remain independently claimable")
|
||||
}
|
||||
g.reopen()
|
||||
g.call("/MissionSectionReward", append(appScalar(2, 1), appScalar(3, 1)...))
|
||||
g.call("/MissionSectionReward", appScalar(3, 1))
|
||||
if g.wallet().Catalyst != before.Catalyst+uint64(period)*70 || g.wallet().FreeJewelry != before.FreeJewelry+uint64(period)*60 || g.itemCount(9, 504153) != dailyBoxes+uint64(period) || g.itemCount(9, 504144) != weeklyBoxes+uint64(period)*4 {
|
||||
t.Fatal("section retries after reopening SQLite duplicated rewards")
|
||||
}
|
||||
g.now = g.now.AddDate(0, 0, 7)
|
||||
}
|
||||
}
|
||||
|
||||
// ChangeMissionTable 1/104 ended 2025-12-08; its former one-collection
|
||||
// condition and 200-gold reward must not receive current gameplay events.
|
||||
func TestMissionExpiredRowCannotReceiveCurrentGameplayEvents(t *testing.T) {
|
||||
g := newMissionGameplay(t)
|
||||
g.call("/LoginUser", nil)
|
||||
before := g.wallet()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx}
|
||||
if err := g.owner.assembly.missionService.RecordEvent(ctx, 3, 0, 1, g.owner.assembly.worldService.MissionsUnlocked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, row := range appRows(g.call("/MissionInfo", nil), 1) {
|
||||
if appValue(row, 1) == 1 && appValue(row, 2) == 104 {
|
||||
t.Fatal("current collection event completed a mission already hidden by the client")
|
||||
}
|
||||
}
|
||||
fields := append(appScalar(3, 1), appScalar(4, 1)...)
|
||||
fields = append(fields, appScalar(5, 104)...)
|
||||
if _, err := g.execute("/MissionClear", fields); err == nil || g.wallet() != before {
|
||||
t.Fatal("expired collection mission paid a reward")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/monsterhunt"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
func TestMonsterHuntClearedDifficultyRankingAndRewardlessReplay(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
presets, err := gamedata.LoadMonsterHuntPresetDesign(factory.options.gameData, factory.options.gameDataVersion)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
design, err := factory.design.source.MonsterHunt(75)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hp3, err := design.HP(3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hp5, err := design.HP(5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
factory.design.monsterHunt, err = monsterhunt.NewRules([]monsterhunt.Season{{ID: 81, Hunt: 75, Start: uint64(now.Add(-time.Hour).UnixMilli()), End: uint64(now.Add(24 * time.Hour).UnixMilli())}}, factory.seeds.defaults, presets, factory.design.source.MonsterHunt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &monsterHuntScenario{factory: factory, account: accounts[0]}
|
||||
s.open(t)
|
||||
t.Cleanup(func() {
|
||||
if s.owner != nil {
|
||||
if err := s.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
s.battle(t, "initial-failure", 5, false, 9000, hp5)
|
||||
s.assertRank(t, 0, 0)
|
||||
if got := s.progress(t).StartHP; got != hp5/2 {
|
||||
t.Fatalf("failed challenge saved %d HP, want %d", got, hp5/2)
|
||||
}
|
||||
s.reopen(t)
|
||||
s.assertRank(t, 0, 0)
|
||||
if got := s.progress(t).StartHP; got != hp5/2 {
|
||||
t.Fatalf("reopening lost partial challenge HP: got %d, want %d", got, hp5/2)
|
||||
}
|
||||
s.battle(t, "resume-five", 5, false, 8000, hp5/2)
|
||||
s.assertRank(t, 0, 0)
|
||||
|
||||
beforeClear := s.assets(t)
|
||||
first := s.battle(t, "clear-three", 3, true, 1200, hp3)
|
||||
if bundle, found, err := wire.Bytes(first, 7); err != nil || !found || len(bundle) == 0 {
|
||||
t.Fatal("first clear did not return its clear rewards")
|
||||
}
|
||||
s.assertClearRewards(t, beforeClear, 1, 3)
|
||||
s.assertRank(t, 3, 1200)
|
||||
s.battle(t, "higher-failure", 5, false, 900000, hp5)
|
||||
s.assertRank(t, 3, 1200)
|
||||
s.reopen(t)
|
||||
s.assertRank(t, 3, 1200)
|
||||
progress := s.progress(t)
|
||||
assets := s.assets(t)
|
||||
s.assertNoReplayRewards(t, s.battle(t, "improve-three", 3, true, 2000, hp3))
|
||||
s.assertRank(t, 3, 2000)
|
||||
s.assertProgress(t, progress)
|
||||
s.assertAssets(t, assets)
|
||||
s.assertNoReplayRewards(t, s.battle(t, "failed-three", 3, false, 500000, hp3))
|
||||
s.assertRank(t, 3, 2000)
|
||||
s.assertProgress(t, progress)
|
||||
s.assertAssets(t, assets)
|
||||
|
||||
maximum := s.battle(t, "clear-five", 5, true, 1000, hp5/2)
|
||||
if bundle, found, err := wire.Bytes(maximum, 7); err != nil || !found || len(bundle) == 0 {
|
||||
t.Fatal("new maximum clear did not return its clear rewards")
|
||||
}
|
||||
s.assertRank(t, 5, 1000)
|
||||
s.assertClearRewards(t, assets, 4, 5)
|
||||
progress = s.progress(t)
|
||||
if progress.Level != 5 || progress.Level > design.MaxLevel {
|
||||
t.Fatalf("maximum clear hid the client's challenge entry: %+v", progress)
|
||||
}
|
||||
assets = s.assets(t)
|
||||
s.reopen(t)
|
||||
s.assertRank(t, 5, 1000)
|
||||
s.assertNoReplayRewards(t, s.battle(t, "failed-five-replay", 5, false, 500000, hp5))
|
||||
s.assertRank(t, 5, 1000)
|
||||
s.assertProgress(t, progress)
|
||||
s.assertAssets(t, assets)
|
||||
replay := s.battle(t, "improve-five", 5, true, 2000, hp5)
|
||||
s.assertNoReplayRewards(t, replay)
|
||||
s.assertRank(t, 5, 2000)
|
||||
s.assertProgress(t, progress)
|
||||
s.assertAssets(t, assets)
|
||||
s.reopen(t)
|
||||
s.assertRank(t, 5, 2000)
|
||||
retried := s.complete(t, "improve-five", 0, 2000)
|
||||
if !bytes.Equal(retried, replay) {
|
||||
t.Fatal("persisted battle retry changed its response")
|
||||
}
|
||||
s.assertAssets(t, assets)
|
||||
s.assertNoReplayRewards(t, s.battle(t, "worse-five", 5, true, 500, hp5))
|
||||
s.assertRank(t, 5, 2000)
|
||||
s.assertProgress(t, progress)
|
||||
s.assertAssets(t, assets)
|
||||
}
|
||||
|
||||
type monsterHuntScenario struct {
|
||||
factory *PlayerFactory
|
||||
owner *playerInstance
|
||||
account string
|
||||
}
|
||||
|
||||
type monsterHuntProgress struct{ Level, StartHP, HighestHP uint64 }
|
||||
|
||||
type monsterHuntAssets struct {
|
||||
Wallet assets.Currency
|
||||
Items map[[2]uint64]uint64
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) open(t *testing.T) {
|
||||
t.Helper()
|
||||
var err error
|
||||
s.owner, err = s.factory.open(s.account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) reopen(t *testing.T) {
|
||||
t.Helper()
|
||||
if err := s.owner.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.owner = nil
|
||||
s.open(t)
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) command(t *testing.T, action func(command.Context) ([]byte, error)) []byte {
|
||||
t.Helper()
|
||||
tx, err := s.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
response, err := action(command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "hunt-client"}, State: tx})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) battle(t *testing.T, receipt string, level uint64, won bool, damage, expectedHP uint64) []byte {
|
||||
t.Helper()
|
||||
design, err := s.factory.design.source.MonsterHunt(75)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := wire.AppendVarint(nil, 4, design.DeckID)
|
||||
request = wire.AppendVarint(request, 5, 8)
|
||||
request = wire.AppendVarint(request, 6, 75)
|
||||
request = wire.AppendVarint(request, 10, level)
|
||||
entry := s.command(t, func(ctx command.Context) ([]byte, error) {
|
||||
return s.owner.assembly.monsterHuntService.EnterBattle(ctx, request, receipt)
|
||||
})
|
||||
user, found, err := wire.Bytes(entry, 5)
|
||||
if err != nil || !found {
|
||||
t.Fatal("battle entry is missing the monster hunt user")
|
||||
}
|
||||
enteredLevel, _, err := wire.Varint(user, 3)
|
||||
if err != nil || enteredLevel != level {
|
||||
t.Fatalf("battle entry selected difficulty %d, want %d", enteredLevel, level)
|
||||
}
|
||||
hp, _, err := wire.Varint(user, 4)
|
||||
if err != nil || hp != expectedHP || hp <= 1 {
|
||||
t.Fatalf("battle entry returned %d HP, want %d", hp, expectedHP)
|
||||
}
|
||||
maxHP, _, err := wire.Varint(user, 6)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectedMax, err := design.HP(level)
|
||||
if err != nil || maxHP != expectedMax {
|
||||
t.Fatalf("selected difficulty maximum HP %d, want design HP %d: %v", maxHP, expectedMax, err)
|
||||
}
|
||||
var remaining uint64
|
||||
if !won {
|
||||
remaining = hp / 2
|
||||
}
|
||||
return s.complete(t, receipt, remaining, damage)
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) complete(t *testing.T, receipt string, remaining, damage uint64) []byte {
|
||||
t.Helper()
|
||||
request := wire.AppendVarint(nil, 7, remaining)
|
||||
attack := wire.AppendVarint(nil, 1, 1)
|
||||
attack = wire.AppendVarint(attack, 2, damage)
|
||||
request = wire.AppendBytes(request, 10, wire.AppendBytes(nil, 1, attack))
|
||||
return s.command(t, func(ctx command.Context) ([]byte, error) {
|
||||
return s.owner.assembly.monsterHuntService.CompleteBattle(ctx, request, receipt)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) assertRank(t *testing.T, difficulty, damage uint64) {
|
||||
t.Helper()
|
||||
response := s.command(t, func(ctx command.Context) ([]byte, error) {
|
||||
request := wire.AppendVarint(nil, 1, 1)
|
||||
request = wire.AppendVarint(request, 2, 81)
|
||||
_, response, handled, err := s.owner.assembly.monsterHuntService.Handle(ctx, "/MonsterHuntRankInfo", request)
|
||||
if !handled {
|
||||
return nil, fmt.Errorf("ranking request was not handled")
|
||||
}
|
||||
return response, err
|
||||
})
|
||||
rank, found, err := wire.Bytes(response, 2)
|
||||
if err != nil || !found {
|
||||
t.Fatal("missing personal ranking")
|
||||
}
|
||||
var score uint64
|
||||
if err := wire.Walk(rank, func(field wire.Field) error {
|
||||
if field.Number == 8 && field.Type == 1 {
|
||||
score = uint64(math.Float64frombits(binary.LittleEndian.Uint64(field.Value)))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if score/100000000000000 != difficulty || score%100000000000000 != damage {
|
||||
t.Fatalf("client ranking difficulty=%d damage=%d, want difficulty=%d damage=%d", score/100000000000000, score%100000000000000, difficulty, damage)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) progress(t *testing.T) monsterHuntProgress {
|
||||
t.Helper()
|
||||
response := s.command(t, func(ctx command.Context) ([]byte, error) {
|
||||
_, response, handled, err := s.owner.assembly.monsterHuntService.Handle(ctx, "/MonsterHuntUserInfo", wire.AppendVarint(nil, 1, 1))
|
||||
if !handled {
|
||||
return nil, fmt.Errorf("hunt user request was not handled")
|
||||
}
|
||||
return response, err
|
||||
})
|
||||
user, found, err := wire.Bytes(response, 1)
|
||||
if err != nil || !found {
|
||||
t.Fatal("missing hunt user info")
|
||||
}
|
||||
var progress monsterHuntProgress
|
||||
for field, value := range map[int]*uint64{3: &progress.Level, 4: &progress.StartHP, 6: &progress.HighestHP} {
|
||||
*value, _, err = wire.Varint(user, field)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return progress
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) assertProgress(t *testing.T, expected monsterHuntProgress) {
|
||||
t.Helper()
|
||||
if got := s.progress(t); got != expected {
|
||||
t.Fatalf("replay changed main hunt progress: got %+v, want %+v", got, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) assets(t *testing.T) monsterHuntAssets {
|
||||
t.Helper()
|
||||
result := monsterHuntAssets{Items: map[[2]uint64]uint64{}}
|
||||
s.command(t, func(ctx command.Context) ([]byte, error) {
|
||||
result.Wallet = s.owner.assembly.wallet.Snapshot(ctx)
|
||||
for _, item := range s.owner.assembly.ownedItems.All(ctx) {
|
||||
result.Items[[2]uint64{item.Type, item.ID}] += item.Count
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) assertAssets(t *testing.T, expected monsterHuntAssets) {
|
||||
t.Helper()
|
||||
if got := s.assets(t); !reflect.DeepEqual(got, expected) {
|
||||
t.Fatalf("owned rewards differ: got %+v, want %+v", got, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) assertClearRewards(t *testing.T, before monsterHuntAssets, first, last uint64) {
|
||||
t.Helper()
|
||||
design, err := s.factory.design.source.MonsterHunt(75)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := monsterHuntAssets{Wallet: before.Wallet, Items: maps.Clone(before.Items)}
|
||||
for level := first; level <= last; level++ {
|
||||
for _, reward := range design.Rewards[level].Clear {
|
||||
switch reward.Type {
|
||||
case 4:
|
||||
expected.Wallet.Gold += reward.Count
|
||||
case 8:
|
||||
expected.Items[[2]uint64{reward.Type, reward.ID}] += reward.Count
|
||||
default:
|
||||
t.Fatalf("current hunt clear reward type %d needs an owned-asset assertion", reward.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.assertAssets(t, expected)
|
||||
}
|
||||
|
||||
func (s *monsterHuntScenario) assertNoReplayRewards(t *testing.T, response []byte) {
|
||||
t.Helper()
|
||||
for _, field := range []int{7, 8} {
|
||||
if _, found, err := wire.Bytes(response, field); err != nil || found {
|
||||
t.Fatalf("replay returned reward bundle field %d", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
)
|
||||
|
||||
func TestNicknamePersistsAndProjectsWithoutChangingIdentity(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner := openNicknamePlayer(t, factory, accounts[0])
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, owner) })
|
||||
seedNicknameTickets(t, owner, 6)
|
||||
identity, err := factory.profiles.GameIdentity(context.Background(), accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeTickets, beforeWallet := nicknameAssets(t, owner)
|
||||
seq := uint64(0)
|
||||
call := func(path string, fields []byte) []byte {
|
||||
t.Helper()
|
||||
seq++
|
||||
c := registryCommand(accounts[0], fmt.Sprintf("nickname-%d", seq), path, append(appScalar(1, seq), fields...))
|
||||
c.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
|
||||
reply, err := owner.Execute(context.Background(), c)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", path, err)
|
||||
}
|
||||
if len(reply.Responses) != 1 {
|
||||
t.Fatalf("%s returned %d responses", path, len(reply.Responses))
|
||||
}
|
||||
return reply.Responses[0].Body
|
||||
}
|
||||
assertName := func(name string) {
|
||||
t.Helper()
|
||||
profile := call("/UserContentsInfo", appScalar(2, uint64(identity.OwnerIndex)))
|
||||
if appValue(profile, 1) != uint64(identity.OwnerIndex) || nicknameField(t, profile, 2) != name {
|
||||
t.Fatalf("profile identity/name is stale: %x", profile)
|
||||
}
|
||||
room := appRows(profile, 14)
|
||||
if len(room) != 1 || appValue(room[0], 1) != uint64(identity.OwnerIndex) || nicknameField(t, room[0], 2) != name {
|
||||
t.Fatalf("profile room identity/name is stale: %x", room)
|
||||
}
|
||||
login := appRows(call("/LoginUser", nil), 1)
|
||||
if len(login) != 1 || appValue(login[0], 1) != uint64(identity.OwnerIndex) || nicknameField(t, login[0], 2) != name {
|
||||
t.Fatalf("login identity/name is stale: %x", login)
|
||||
}
|
||||
}
|
||||
seq++
|
||||
rename := registryCommand(accounts[0], fmt.Sprintf("nickname-%d", seq), "/UserNicknameChange", append(appScalar(1, seq), appMessage(2, []byte("CodexName7"))...))
|
||||
reply, err := owner.Execute(context.Background(), rename)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(reply.Responses) != 1 || reply.Responses[0].PacketCode != 74 || len(reply.Responses[0].Body) != 0 {
|
||||
t.Fatalf("invalid nickname success response: %+v", reply)
|
||||
}
|
||||
if _, err = owner.Execute(context.Background(), rename); err != nil {
|
||||
t.Fatal("exact rename replay", err)
|
||||
}
|
||||
assertName("CodexName7")
|
||||
if tickets, wallet := nicknameAssets(t, owner); tickets != beforeTickets-1 || wallet != beforeWallet {
|
||||
t.Fatalf("rename/replay assets: tickets %d want %d; wallet %+v want %+v", tickets, beforeTickets-1, wallet, beforeWallet)
|
||||
}
|
||||
if err = owner.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner = openNicknamePlayer(t, factory, accounts[0])
|
||||
assertName("CodexName7")
|
||||
if _, err = owner.Execute(context.Background(), rename); err != nil {
|
||||
t.Fatal("durable rename replay", err)
|
||||
}
|
||||
if tickets, _ := nicknameAssets(t, owner); tickets != beforeTickets-1 {
|
||||
t.Fatalf("durable replay spent again: %d", tickets)
|
||||
}
|
||||
for _, name := range []string{"123456789012345678901234", "青山明月春风白云", "Flechazo"} {
|
||||
call("/UserNicknameChange", appMessage(2, []byte(name)))
|
||||
assertName(name)
|
||||
}
|
||||
if tickets, wallet := nicknameAssets(t, owner); tickets != beforeTickets-4 || wallet != beforeWallet {
|
||||
t.Fatalf("boundary renames charged wrong assets: %d %+v", tickets, wallet)
|
||||
}
|
||||
second := openNicknamePlayer(t, factory, accounts[1])
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, second) })
|
||||
seedNicknameTickets(t, second, 1)
|
||||
other, err := factory.profiles.GameIdentity(context.Background(), accounts[1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if other.AccountID == identity.AccountID || other.OwnerIndex == identity.OwnerIndex {
|
||||
t.Fatal("two account fixtures share identity")
|
||||
}
|
||||
if _, err = second.Execute(context.Background(), registryCommand(accounts[1], "duplicate-display-name", "/UserNicknameChange", append(appScalar(1, 1), appMessage(2, []byte("Flechazo"))...))); err != nil {
|
||||
t.Fatal("explicit duplicate display-name policy", err)
|
||||
}
|
||||
if second.assembly.nicknameService.CurrentNickname() != "Flechazo" {
|
||||
t.Fatal("second account nickname not committed")
|
||||
}
|
||||
afterIdentity, err := factory.profiles.GameIdentity(context.Background(), accounts[0])
|
||||
if err != nil || afterIdentity != identity {
|
||||
t.Fatalf("rename changed authentication identity: %+v %v", afterIdentity, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNicknameRejectionsAndBatchFailurePreserveCommittedAssets(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner := openNicknamePlayer(t, factory, accounts[0])
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, owner) })
|
||||
seedNicknameTickets(t, owner, 2)
|
||||
initial := owner.assembly.nicknameService.CurrentNickname()
|
||||
tickets, wallet := nicknameAssets(t, owner)
|
||||
seq := uint64(10)
|
||||
cases := []struct {
|
||||
name string
|
||||
fields []byte
|
||||
}{
|
||||
{"short", appMessage(2, []byte("abc"))},
|
||||
{"over24", appMessage(2, []byte("1234567890123456789012345"))},
|
||||
{"oneHan", appMessage(2, []byte("山"))},
|
||||
{"nineHan", appMessage(2, []byte("青山明月春风白云海"))},
|
||||
{"space", appMessage(2, []byte("Name 7"))},
|
||||
{"underscore", appMessage(2, []byte("Name_7"))},
|
||||
{"emoji", appMessage(2, []byte("Name😀"))},
|
||||
{"invalidUTF8", appMessage(2, []byte{0xff, 0xfe, 0xfd, 0xfc})},
|
||||
{"missingName", nil},
|
||||
{"wrongNameWireType", appScalar(2, 1)},
|
||||
{"duplicateName", append(appMessage(2, []byte("CodexName7")), appMessage(2, []byte("CodexName8"))...)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
seq++
|
||||
_, err := owner.Execute(context.Background(), registryCommand(accounts[0], fmt.Sprintf("reject-%d", seq), "/UserNicknameChange", append(appScalar(1, seq), tc.fields...)))
|
||||
if err == nil {
|
||||
t.Fatal("invalid nickname accepted")
|
||||
}
|
||||
if owner.assembly.nicknameService.CurrentNickname() != initial {
|
||||
t.Fatal("rejection changed name")
|
||||
}
|
||||
if got, balance := nicknameAssets(t, owner); got != tickets || balance != wallet {
|
||||
t.Fatalf("rejection changed assets: %d %+v", got, balance)
|
||||
}
|
||||
})
|
||||
}
|
||||
batch := registryCommand(accounts[0], "nickname-rollback", "/UserNicknameChange", append(appScalar(1, 80), appMessage(2, []byte("CodexName8"))...))
|
||||
batch.Requests = append(batch.Requests, player.Request{Path: "/UserNicknameChange", Body: append(appScalar(1, 81), appMessage(2, []byte("bad space"))...)})
|
||||
batch.Digest = sha256.Sum256(append(batch.Requests[0].Body, batch.Requests[1].Body...))
|
||||
if _, err := owner.Execute(context.Background(), batch); err == nil {
|
||||
t.Fatal("invalid second batch action accepted")
|
||||
}
|
||||
if owner.assembly.nicknameService.CurrentNickname() != initial {
|
||||
t.Fatal("batch rollback kept uncommitted nickname")
|
||||
}
|
||||
if got, balance := nicknameAssets(t, owner); got != tickets || balance != wallet {
|
||||
t.Fatalf("batch rollback lost assets: %d %+v", got, balance)
|
||||
}
|
||||
if err := owner.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner = openNicknamePlayer(t, factory, accounts[0])
|
||||
if owner.assembly.nicknameService.CurrentNickname() != initial {
|
||||
t.Fatal("reopen resurrected rolled-back nickname")
|
||||
}
|
||||
if got, balance := nicknameAssets(t, owner); got != tickets || balance != wallet {
|
||||
t.Fatalf("reopen resurrected rolled-back assets: %d %+v", got, balance)
|
||||
}
|
||||
empty := openNicknamePlayer(t, factory, accounts[1])
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, empty) })
|
||||
emptyTickets, emptyWallet := nicknameAssets(t, empty)
|
||||
if emptyTickets != 1 {
|
||||
t.Fatalf("starter fixture has %d tickets, want the independently seeded one", emptyTickets)
|
||||
}
|
||||
if _, err := empty.Execute(context.Background(), registryCommand(accounts[1], "starter-ticket", "/UserNicknameChange", append(appScalar(1, 1), appMessage(2, []byte("CodexName8"))...))); err != nil {
|
||||
t.Fatal("existing starter ticket is unusable", err)
|
||||
}
|
||||
emptyName := "CodexName8"
|
||||
if err := empty.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
empty = openNicknamePlayer(t, factory, accounts[1])
|
||||
if _, err := empty.Execute(context.Background(), registryCommand(accounts[1], "no-ticket", "/UserNicknameChange", append(appScalar(1, 2), appMessage(2, []byte("CodexName7"))...))); err == nil {
|
||||
t.Fatal("rename without ticket accepted")
|
||||
}
|
||||
if got, balance := nicknameAssets(t, empty); got != 0 || balance != emptyWallet || empty.assembly.nicknameService.CurrentNickname() != emptyName {
|
||||
t.Fatal("no-ticket rejection changed state")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNicknameNativeAlreadyUsedErrorUsesActiveSessionEnvelope(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner := openNicknamePlayer(t, factory, accounts[0])
|
||||
seedNicknameTickets(t, owner, 2)
|
||||
if err := owner.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := newPlayerRegistry(factory, time.Minute)
|
||||
t.Cleanup(func() {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
server, err := session.NewServer(registry, nicknameAuthenticator{accounts[0]})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixed := []byte("abcdefghijkrstuv024680wxyzlmnopq")
|
||||
login, err := server.DispatchRaw(context.Background(), "/LoginUser", nicknameEncrypt(t, appScalar(1, 1), fixed), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var envelope struct {
|
||||
PacketCode int
|
||||
ErrorType int
|
||||
Data string
|
||||
}
|
||||
if err = json.Unmarshal(login.Body, &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := appRows(nicknameDecrypt(t, envelope.Data, fixed), 1)
|
||||
if len(user) != 1 {
|
||||
t.Fatal("invalid login user envelope")
|
||||
}
|
||||
key := []byte(nicknameField(t, user[0], 3))
|
||||
if len(key) != 32 {
|
||||
t.Fatal("login did not supply session key")
|
||||
}
|
||||
cookie := "s=" + login.Cookie
|
||||
request := append(appScalar(1, 2), appMessage(2, []byte("CodexName7"))...)
|
||||
if _, err = server.DispatchRaw(context.Background(), "/UserNicknameChange", nicknameEncrypt(t, request, key), cookie); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request = append(appScalar(1, 3), appMessage(2, []byte("CodexName7"))...)
|
||||
for range 2 {
|
||||
reply, err := server.DispatchRaw(context.Background(), "/UserNicknameChange", nicknameEncrypt(t, request, key), cookie)
|
||||
if err != nil {
|
||||
t.Fatal("native nickname rejection invalidated session", err)
|
||||
}
|
||||
if err = json.Unmarshal(reply.Body, &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if envelope.PacketCode != 74 || envelope.ErrorType != 1 || len(nicknameDecrypt(t, envelope.Data, key)) != 0 {
|
||||
t.Fatalf("wrong native error envelope: %s", reply.Body)
|
||||
}
|
||||
}
|
||||
if _, err = server.DispatchRaw(context.Background(), "/UserNicknameChange", nicknameEncrypt(t, append(appScalar(1, 4), appMessage(2, []byte("bad space"))...), key), cookie); err == nil {
|
||||
t.Fatal("unclassified request failure became a success envelope")
|
||||
}
|
||||
if _, err = server.DispatchRaw(context.Background(), "/ItemInfo", nicknameEncrypt(t, appScalar(1, 5), key), cookie); err != nil {
|
||||
t.Fatal("read-only rejection invalidated active session", err)
|
||||
}
|
||||
if err = registry.Close(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened := openNicknamePlayer(t, factory, accounts[0])
|
||||
defer closeNicknamePlayer(t, reopened)
|
||||
if tickets, _ := nicknameAssets(t, reopened); tickets != 2 || reopened.assembly.nicknameService.CurrentNickname() != "CodexName7" {
|
||||
t.Fatal("native errors consumed tickets or changed committed nickname")
|
||||
}
|
||||
}
|
||||
|
||||
func openNicknamePlayer(t *testing.T, f *PlayerFactory, account string) *playerInstance {
|
||||
t.Helper()
|
||||
owner, err := f.open(account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return owner
|
||||
}
|
||||
func closeNicknamePlayer(t *testing.T, owner *playerInstance) {
|
||||
t.Helper()
|
||||
if err := owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
func seedNicknameTickets(t *testing.T, owner *playerInstance, count uint64) {
|
||||
t.Helper()
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx, Identity: command.Identity{AccountID: owner.accountID}}
|
||||
if _, err = owner.assembly.ownedItems.GrantOnce(ctx, "nickname-ticket-fixture", []gamedata.BattleReward{{Type: 14, ID: 1, Count: count}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func nicknameAssets(t *testing.T, owner *playerInstance) (uint64, assets.Currency) {
|
||||
t.Helper()
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx}
|
||||
var count uint64
|
||||
for _, item := range owner.assembly.ownedItems.All(ctx) {
|
||||
if item.Type == 14 && item.ID == 1 {
|
||||
count += item.Count
|
||||
}
|
||||
}
|
||||
return count, owner.assembly.wallet.Snapshot(ctx)
|
||||
}
|
||||
func nicknameField(t *testing.T, body []byte, field int) string {
|
||||
t.Helper()
|
||||
rows := appRows(body, field)
|
||||
if len(rows) != 1 {
|
||||
t.Fatalf("field %d has %d values", field, len(rows))
|
||||
}
|
||||
return string(rows[0])
|
||||
}
|
||||
|
||||
type nicknameAuthenticator struct{ account string }
|
||||
|
||||
func (a nicknameAuthenticator) AuthenticateLogin([]byte) (string, error) {
|
||||
if a.account == "" {
|
||||
return "", errors.New("missing fixture account")
|
||||
}
|
||||
return a.account, nil
|
||||
}
|
||||
|
||||
// The client transport oracle independently implements AES-CBC/base64 and
|
||||
// obtains the active key from LoginUser, rather than using server cryptox.
|
||||
func nicknameEncrypt(t *testing.T, plain, key []byte) []byte {
|
||||
t.Helper()
|
||||
plain = []byte(base64.StdEncoding.EncodeToString(plain))
|
||||
pad := aes.BlockSize - len(plain)%aes.BlockSize
|
||||
plain = append(plain, bytes.Repeat([]byte{byte(pad)}, pad)...)
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := make([]byte, len(plain))
|
||||
cipher.NewCBCEncrypter(block, make([]byte, aes.BlockSize)).CryptBlocks(out, plain)
|
||||
return []byte(base64.StdEncoding.EncodeToString(out))
|
||||
}
|
||||
func nicknameDecrypt(t *testing.T, encoded string, key []byte) []byte {
|
||||
t.Helper()
|
||||
raw, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil || len(raw) == 0 || len(raw)%aes.BlockSize != 0 {
|
||||
t.Fatalf("invalid encrypted response: %v", err)
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain := make([]byte, len(raw))
|
||||
cipher.NewCBCDecrypter(block, make([]byte, aes.BlockSize)).CryptBlocks(plain, raw)
|
||||
pad := int(plain[len(plain)-1])
|
||||
if pad < 1 || pad > aes.BlockSize || !bytes.Equal(plain[len(plain)-pad:], bytes.Repeat([]byte{byte(pad)}, pad)) {
|
||||
t.Fatal("invalid response padding")
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(string(plain[:len(plain)-pad]))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
@@ -39,6 +39,11 @@ func (p *playerAssembly) assets(ctx command.Context) error {
|
||||
if err := p.ownedItems.AttachItemStacks(p.design.itemStacks); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.initializeAccount {
|
||||
if err := p.ownedItems.InitializeItems(ctx, p.starter.OwnedItems); err != nil {
|
||||
return fmt.Errorf("initialize owned item seed: %w", err)
|
||||
}
|
||||
}
|
||||
p.recipeService, err = assets.NewRecipeService(p.design.recipeDesign, p.starter.CookingRecipes, p.ownedItems)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load learned recipes: %w", err)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) avatar(ctx command.Context) error {
|
||||
var err error
|
||||
p.avatarService, err = profile.OpenAvatar(ctx, p.gameplayStore, p.design.avatarProfile, p, p.eventEconomy)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open avatar profile: %w", err)
|
||||
}
|
||||
return p.login.AttachAvatarSelection(p.avatarService)
|
||||
}
|
||||
func (p *playerAssembly) AvatarItems(ctx command.Context) []assets.Item { return p.ownedItems.All(ctx) }
|
||||
func (p *playerAssembly) AvatarCurrency(ctx command.Context) assets.Currency {
|
||||
return p.wallet.Snapshot(ctx)
|
||||
}
|
||||
func (p *playerAssembly) AvatarUnlocked(ctx command.Context, product gamedata.AvatarProduct) (bool, error) {
|
||||
if product.UnlockValue == 0 {
|
||||
return true, nil
|
||||
}
|
||||
switch product.UnlockType {
|
||||
case 1:
|
||||
return p.worldService.MissionsUnlocked(ctx, product.UnlockValue, 0), nil
|
||||
case 2:
|
||||
exp, err := p.missionService.AchievementExperience()
|
||||
return err == nil && p.design.levelDesign.Level(exp) >= product.UnlockValue, err
|
||||
case 6:
|
||||
value, err := p.achievementCounters.AchievementValue(ctx, product.UnlockValue)
|
||||
return err == nil && value >= product.UnlockSub, err
|
||||
default:
|
||||
return false, fmt.Errorf("avatar: unsupported design unlock condition %d", product.UnlockType)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/chat"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"context"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) chat() error {
|
||||
p.chatService = &chat.Service{Design: p.design.chat, Owner: p.ProfileOwner, Target: func(ctx command.Context, owner uint64) (string, error) {
|
||||
profile, err := p.PublicProfile(ctx, owner)
|
||||
return profile.UserID, err
|
||||
}}
|
||||
return p.login.AttachCommunity(func(ctx command.Context) ([]byte, error) {
|
||||
auto, global, visible, err := p.chatService.ChatSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []byte
|
||||
for i, flag := range []bool{auto, global, visible} {
|
||||
if flag {
|
||||
out = wire.AppendVarint(out, i+10, 1)
|
||||
}
|
||||
}
|
||||
if p.shared != nil && p.shared.guild != nil {
|
||||
member, base, err := p.shared.guild.LoginInfo(context.Background(), ctx.AccountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(member) > 0 {
|
||||
out = wire.AppendBytes(out, 6, member)
|
||||
out = wire.AppendBytes(out, 7, base)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
})
|
||||
}
|
||||
@@ -48,7 +48,10 @@ func (p *playerAssembly) commerce(ctx command.Context) error {
|
||||
return fmt.Errorf("load cash bonus claims: %w", err)
|
||||
}
|
||||
p.cashService.AttachLegacyCounts(p.gachaService)
|
||||
cashSpecialProducts := []gamedata.CashProductKey{{GroupID: p.design.infiniteGacha.ProductGroupID, ProductID: p.design.infiniteGacha.ProductID, SaleGroup: p.design.infiniteGacha.SaleGroup}}
|
||||
var cashSpecialProducts []gamedata.CashProductKey
|
||||
if infinite := p.design.infiniteGacha; infinite != nil {
|
||||
cashSpecialProducts = append(cashSpecialProducts, gamedata.CashProductKey{GroupID: infinite.ProductGroupID, ProductID: infinite.ProductID, SaleGroup: infinite.SaleGroup})
|
||||
}
|
||||
for _, group := range p.design.regularGacha.Groups() {
|
||||
if group.CashProductGroupID != 0 && group.CashProductID != 0 {
|
||||
cashSpecialProducts = append(cashSpecialProducts, gamedata.CashProductKey{GroupID: group.CashProductGroupID, ProductID: group.CashProductID, SaleGroup: group.CashSalesGroup})
|
||||
@@ -58,7 +61,10 @@ func (p *playerAssembly) commerce(ctx command.Context) error {
|
||||
return fmt.Errorf("attach special cash products: %w", err)
|
||||
}
|
||||
p.cashService.AttachDelegate(func(ctx command.Context, key gamedata.CashProductKey, request []byte) ([]byte, bool, error) {
|
||||
known := key.GroupID == p.design.infiniteGacha.ProductGroupID && key.ProductID == p.design.infiniteGacha.ProductID && key.SaleGroup == p.design.infiniteGacha.SaleGroup
|
||||
known := false
|
||||
if infinite := p.design.infiniteGacha; infinite != nil {
|
||||
known = key.GroupID == infinite.ProductGroupID && key.ProductID == infinite.ProductID && key.SaleGroup == infinite.SaleGroup
|
||||
}
|
||||
for _, group := range p.design.regularGacha.Groups() {
|
||||
if key.GroupID == group.CashProductGroupID && key.ProductID == group.CashProductID && key.SaleGroup == group.CashSalesGroup {
|
||||
known = true
|
||||
|
||||
@@ -10,9 +10,11 @@ import (
|
||||
"bd2server/internal/server/domain/events/games"
|
||||
"bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/domain/events/tasks"
|
||||
"bd2server/internal/server/domain/fishing"
|
||||
"bd2server/internal/server/domain/progression/achievements"
|
||||
"bd2server/internal/server/domain/progression/missions"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
loginprotocol "bd2server/internal/server/protocol/login"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
@@ -39,6 +41,26 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
return fmt.Errorf("load event play state: %w", err)
|
||||
}
|
||||
p.eventPlayService.AttachBattleChallenges(p.design.eventBattleChallenges)
|
||||
if p.roomResults != nil {
|
||||
p.eventPlayService.AttachRooms(p.roomResults)
|
||||
}
|
||||
var rooms eventplay.RoomRuntime
|
||||
if p.roomResults != nil {
|
||||
rooms = p.roomResults
|
||||
}
|
||||
p.fishingService, err = fishing.Open(ctx, p.design.eventPlay, p.eventEconomy, rooms)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load fishing state: %w", err)
|
||||
}
|
||||
if err := p.login.AttachFishing(func() loginprotocol.FishingState {
|
||||
state := p.fishingService.Profile()
|
||||
return loginprotocol.FishingState{AP: state.MultiAP, FishSlots: state.FishSlots, RodSlots: state.RodSlots, ItemSlots: state.ItemSlots}
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.shared != nil {
|
||||
p.fishingService.AttachPublicProfiles(p.shared.directory.fishing)
|
||||
}
|
||||
p.eventPlayService.AttachHubCalendars(p.seeds.defaults)
|
||||
if err := p.eventPlayService.AttachFieldBindingsFile(filepath.Join(filepath.Dir(p.options.worldSeed), "event_field_bindings.json")); err != nil {
|
||||
return fmt.Errorf("attach hidden field bindings: %w", err)
|
||||
@@ -71,7 +93,15 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(rows, huntingRows...), nil
|
||||
rows = append(rows, huntingRows...)
|
||||
if p.pvpService != nil {
|
||||
pvpRows, err := p.pvpService.ChargeInfo(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows = append(rows, pvpRows...)
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
p.eventActionsService.AttachProgress(func(ctx command.Context, condition, sub, count uint64) error {
|
||||
if err := p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked); err != nil {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
accountstate "bd2server/internal/server/storage/account"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
@@ -23,6 +24,72 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
|
||||
if request.Identity.AccountID != p.accountID || p.assembly == nil {
|
||||
return reply, player.Failure{Cause: player.ErrUnavailable, RecoveryRequired: true}
|
||||
}
|
||||
if request.System != nil && request.System.Kind == player.ReconcileSocial {
|
||||
return p.reconcileSocial(ctx, request)
|
||||
}
|
||||
friendStarted := time.Now()
|
||||
friendResponses, err := p.prepareFriends(ctx, request)
|
||||
reply.Timing.Execute += time.Since(friendStarted)
|
||||
if err != nil {
|
||||
return reply, err
|
||||
}
|
||||
if len(request.Requests) == 1 && len(friendResponses) == 1 {
|
||||
reply.Responses = []player.Response{friendResponses[0]}
|
||||
return reply, nil
|
||||
}
|
||||
if request.System == nil && hasPlayerText(request.Requests) {
|
||||
var receipt commandReceipt
|
||||
var found bool
|
||||
err := p.readLocal(ctx, request.Identity, func(c command.Context) error {
|
||||
raw, exists, err := c.State.LoadEntry("missions", "command_receipts", request.Identity.SessionID+"/"+request.Identity.RequestID)
|
||||
if err != nil || !exists {
|
||||
return err
|
||||
}
|
||||
found = true
|
||||
return json.Unmarshal(raw, &receipt)
|
||||
})
|
||||
if err != nil {
|
||||
return reply, err
|
||||
}
|
||||
if found {
|
||||
if receipt.Digest != hex.EncodeToString(request.Digest[:]) {
|
||||
return reply, player.ErrIdentityConflict
|
||||
}
|
||||
reply.Responses = receipt.Responses
|
||||
return reply, nil
|
||||
}
|
||||
}
|
||||
approvals, err := p.prepareText(ctx, request)
|
||||
if err != nil {
|
||||
return reply, err
|
||||
}
|
||||
if approvals != nil {
|
||||
ctx = context.WithValue(ctx, textApprovalKey{}, approvals)
|
||||
cancellation := request.Cancellation
|
||||
if cancellation == nil {
|
||||
cancellation = ctx
|
||||
}
|
||||
request.Cancellation = context.WithValue(cancellation, textApprovalKey{}, approvals)
|
||||
}
|
||||
restoreRooms, err := p.prepareRoomResults(ctx, request.Requests)
|
||||
if err != nil {
|
||||
return reply, err
|
||||
}
|
||||
defer restoreRooms()
|
||||
socialService, socialPlans, err := p.prepareSocial(ctx, request)
|
||||
if err != nil {
|
||||
return reply, err
|
||||
}
|
||||
defer func() {
|
||||
if result != nil || socialService == nil {
|
||||
return
|
||||
}
|
||||
for _, plan := range socialPlans {
|
||||
if err := socialService.Confirm(ctx, plan); err != nil {
|
||||
result = errors.Join(result, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
started := time.Now()
|
||||
tx, err := p.repository.BeginCommand(ctx)
|
||||
reply.Timing.Begin = time.Since(started)
|
||||
@@ -43,9 +110,22 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
|
||||
}()
|
||||
|
||||
identity := command.Context{Identity: request.Identity, Cancellation: request.Cancellation, State: tx}
|
||||
published := false
|
||||
var chatPolicyPayload []byte
|
||||
identity.Emit = func(event command.Event) error {
|
||||
if err := outbox.Publish(tx, p.accountID, event); err != nil {
|
||||
return err
|
||||
}
|
||||
published = true
|
||||
if event.Topic == "chat.policy" {
|
||||
chatPolicyPayload = append([]byte(nil), event.Payload...)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
isLogin := len(request.Requests) == 1 && request.Requests[0].Path == "/LoginUser"
|
||||
isSystem := request.System != nil
|
||||
receiptKey := request.Identity.SessionID + "/" + request.Identity.RequestID
|
||||
if !isLogin {
|
||||
if !isLogin && !isSystem {
|
||||
raw, found, err := tx.LoadEntry("missions", "command_receipts", receiptKey)
|
||||
if err != nil {
|
||||
return reply, err
|
||||
@@ -74,7 +154,33 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
|
||||
}
|
||||
assembly := p.assembly
|
||||
transientBefore := assembly.transientVersion()
|
||||
for _, item := range request.Requests {
|
||||
failCommand := func(cause error) error {
|
||||
changed := tx.Dirty() || assembly.transientVersion() != transientBefore
|
||||
started := time.Now()
|
||||
rollbackErr := tx.Rollback()
|
||||
reply.Timing.Rollback += time.Since(started)
|
||||
finished = true
|
||||
if rollbackErr != nil {
|
||||
p.assembly = nil
|
||||
return player.Failure{Cause: errors.Join(cause, rollbackErr), RecoveryRequired: true}
|
||||
}
|
||||
if !changed {
|
||||
return cause
|
||||
}
|
||||
p.assembly = nil
|
||||
if recoveryErr := p.Recover(context.WithoutCancel(ctx)); recoveryErr != nil {
|
||||
return player.Failure{Cause: errors.Join(cause, recoveryErr), RecoveryRequired: true}
|
||||
}
|
||||
return player.Failure{Cause: cause, RecoveryRequired: true, AlreadyRecovered: true}
|
||||
}
|
||||
if isSystem {
|
||||
body, err := p.executeSystem(identity, tx, request.System)
|
||||
if err != nil {
|
||||
return reply, failCommand(err)
|
||||
}
|
||||
reply.Responses = []player.Response{{Body: body}}
|
||||
}
|
||||
for index, item := range request.Requests {
|
||||
var response player.Response
|
||||
if isLogin {
|
||||
started := time.Now()
|
||||
@@ -94,7 +200,13 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
|
||||
reply.Timing.Observer += time.Since(started)
|
||||
if err == nil {
|
||||
started = time.Now()
|
||||
response.PacketCode, response.Body, err = assembly.dispatch(identity, item.Path, item.Body)
|
||||
if friendResponse, found := friendResponses[index]; found {
|
||||
response = friendResponse
|
||||
} else if plan := socialPlans[index]; plan != nil {
|
||||
response.PacketCode, response.Body, err = socialService.Apply(identity, plan)
|
||||
} else {
|
||||
response.PacketCode, response.Body, err = assembly.dispatch(identity, item.Path, item.Body)
|
||||
}
|
||||
reply.Timing.Execute += time.Since(started)
|
||||
}
|
||||
if err == nil {
|
||||
@@ -112,28 +224,27 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
changed := tx.Dirty() || assembly.transientVersion() != transientBefore
|
||||
started := time.Now()
|
||||
rollbackErr := tx.Rollback()
|
||||
reply.Timing.Rollback += time.Since(started)
|
||||
finished = true
|
||||
if rollbackErr != nil {
|
||||
p.assembly = nil
|
||||
return reply, player.Failure{Cause: errors.Join(err, rollbackErr), RecoveryRequired: true}
|
||||
}
|
||||
if !changed {
|
||||
return reply, err
|
||||
}
|
||||
p.assembly = nil
|
||||
if recoveryErr := p.Recover(context.WithoutCancel(ctx)); recoveryErr != nil {
|
||||
return reply, player.Failure{Cause: errors.Join(err, recoveryErr), RecoveryRequired: true}
|
||||
}
|
||||
return reply, player.Failure{Cause: err, RecoveryRequired: true, AlreadyRecovered: true}
|
||||
return reply, failCommand(err)
|
||||
}
|
||||
|
||||
reply.Responses = append(reply.Responses, response)
|
||||
}
|
||||
if tx.Dirty() && !isLogin {
|
||||
if !isSystem && (tx.Dirty() || isLogin) {
|
||||
if isLogin || friendProfileChanged(request.Requests) {
|
||||
if err := assembly.publishFriendProfile(identity, isLogin); err != nil {
|
||||
return reply, failCommand(err)
|
||||
}
|
||||
}
|
||||
if isLogin {
|
||||
if err := assembly.chatService.PublishPolicy(identity); err != nil {
|
||||
return reply, err
|
||||
}
|
||||
}
|
||||
if err := assembly.publishDirectory(identity); err != nil {
|
||||
return reply, failCommand(err)
|
||||
}
|
||||
}
|
||||
if tx.Dirty() && !isLogin && !isSystem {
|
||||
raw, err := json.Marshal(commandReceipt{Digest: hex.EncodeToString(request.Digest[:]), Responses: reply.Responses})
|
||||
if err != nil {
|
||||
return reply, err
|
||||
@@ -150,6 +261,14 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
|
||||
p.assembly = nil
|
||||
return reply, player.Failure{Cause: err, RecoveryRequired: true}
|
||||
}
|
||||
if published && p.factory.wakeOutbox != nil {
|
||||
p.factory.wakeOutbox(p.accountID)
|
||||
}
|
||||
if len(chatPolicyPayload) > 0 && p.factory.shared != nil {
|
||||
if err := p.factory.shared.consumeChatPolicy(ctx, p.accountID, chatPolicyPayload); err != nil {
|
||||
slog.Warn("chat policy publication deferred", "account_id", p.accountID, "error", err)
|
||||
}
|
||||
}
|
||||
return reply, nil
|
||||
}
|
||||
|
||||
@@ -197,12 +316,17 @@ func (p *playerInstance) Recover(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
p.assembly = assembly
|
||||
p.sharedSocial = nil
|
||||
if err := p.recoverSharedBattle(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
slog.Warn("player state recovered from committed snapshot", "account_id", p.accountID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *playerInstance) Close() error {
|
||||
p.assembly = nil
|
||||
p.sharedSocial = nil
|
||||
return p.repository.Close()
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"bd2server/internal/server/domain/battle"
|
||||
"bd2server/internal/server/domain/battle/hunting"
|
||||
"bd2server/internal/server/domain/battle/monsterhunt"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/chat"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/commerce"
|
||||
"bd2server/internal/server/domain/commerce/gacha"
|
||||
@@ -15,13 +17,16 @@ import (
|
||||
"bd2server/internal/server/domain/events/games"
|
||||
"bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/domain/events/tasks"
|
||||
"bd2server/internal/server/domain/fishing"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/mail"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
"bd2server/internal/server/domain/progression/achievements"
|
||||
"bd2server/internal/server/domain/progression/missions"
|
||||
"bd2server/internal/server/domain/progression/pictorial"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/domain/roster/deck"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/domain/world"
|
||||
"bd2server/internal/server/domain/world/progress"
|
||||
"bd2server/internal/server/domain/world/todayquest"
|
||||
@@ -40,18 +45,24 @@ import (
|
||||
)
|
||||
|
||||
type PlayerFactory struct {
|
||||
options *configuration
|
||||
design *designCatalog
|
||||
seeds *seedCatalog
|
||||
profiles interface {
|
||||
roomResults *roomResults
|
||||
shared *sharedRuntime
|
||||
pvpSource pvp.Source
|
||||
wakeOutbox func(string)
|
||||
options *configuration
|
||||
design *designCatalog
|
||||
seeds *seedCatalog
|
||||
profiles interface {
|
||||
GameIdentity(context.Context, string) (identitystore.GameProfile, error)
|
||||
}
|
||||
}
|
||||
|
||||
type playerAssembly struct {
|
||||
worldSeed world.Seed
|
||||
mailbox *mail.Starter
|
||||
deckSeed deck.Seed
|
||||
fishingService *fishing.Service
|
||||
pvpService *pvp.Service
|
||||
worldSeed world.Seed
|
||||
mailbox *mail.Starter
|
||||
deckSeed deck.Seed
|
||||
*PlayerFactory
|
||||
progressState *progress.Store
|
||||
deckStateStore *deck.Store
|
||||
@@ -60,6 +71,9 @@ type playerAssembly struct {
|
||||
wallet *assets.Wallet
|
||||
inventorySlots *assets.InventorySlots
|
||||
mailService *mail.Service
|
||||
nicknameService *profile.NicknameService
|
||||
profileService *profile.Service
|
||||
chatService *chat.Service
|
||||
missionService *missions.Service
|
||||
ownedEquipment *assets.EquipmentInventory
|
||||
worldService *world.Service
|
||||
@@ -102,6 +116,7 @@ type playerAssembly struct {
|
||||
achievementCounters *achievements.AchievementService
|
||||
achievementObserver *achievements.GameplayAchievementObserver
|
||||
handlers []session.Handler
|
||||
avatarService *profile.AvatarService
|
||||
observers []session.ResponseObserver
|
||||
stateRepository *accountstate.Repository
|
||||
scope stateio.RootStore
|
||||
@@ -112,10 +127,11 @@ type playerAssembly struct {
|
||||
}
|
||||
|
||||
type playerInstance struct {
|
||||
accountID string
|
||||
factory *PlayerFactory
|
||||
repository *accountstate.Repository
|
||||
assembly *playerAssembly
|
||||
sharedSocial *social.Service
|
||||
accountID string
|
||||
factory *PlayerFactory
|
||||
repository *accountstate.Repository
|
||||
assembly *playerAssembly
|
||||
}
|
||||
|
||||
func (f *PlayerFactory) open(accountID string) (instance *playerInstance, openErr error) {
|
||||
@@ -140,7 +156,11 @@ func (f *PlayerFactory) open(accountID string) (instance *playerInstance, openEr
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &playerInstance{accountID: accountID, factory: f, repository: repository, assembly: assembly}, nil
|
||||
instance = &playerInstance{accountID: accountID, factory: f, repository: repository, assembly: assembly}
|
||||
if err := instance.recoverSharedBattle(context.Background()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
func (f *PlayerFactory) assemble(ctx context.Context, accountID string, repository *accountstate.Repository) (_ *playerAssembly, openErr error) {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) publicFriendProfile(ctx command.Context) (social.FriendProfile, error) {
|
||||
owner, err := p.ProfileOwner(ctx)
|
||||
if err != nil {
|
||||
return social.FriendProfile{}, err
|
||||
}
|
||||
snapshot, err := p.PublicProfile(ctx, owner)
|
||||
if err != nil {
|
||||
return social.FriendProfile{}, err
|
||||
}
|
||||
profile := social.FriendProfile{AccountID: ctx.AccountID, OwnerIndex: owner, Version: uint64(time.Now().UnixNano()), LastLoginMS: time.Now().UnixMilli(), Snapshot: snapshot}
|
||||
if raw, found, err := ctx.State.LoadEntry("directory", "friend_publication", "last_login"); err != nil {
|
||||
return profile, err
|
||||
} else if found {
|
||||
if err := json.Unmarshal(raw, &profile.LastLoginMS); err != nil {
|
||||
return profile, err
|
||||
}
|
||||
}
|
||||
profile.SupporterDetails, err = p.profileService.PublicSupporterDetails(ctx)
|
||||
if err != nil {
|
||||
return profile, err
|
||||
}
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
func (p *playerAssembly) publishFriendProfile(ctx command.Context, login bool) error {
|
||||
if p.shared == nil || p.shared.friends == nil {
|
||||
return nil
|
||||
}
|
||||
profile, err := p.publicFriendProfile(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if login {
|
||||
profile.LastLoginMS = time.Now().UnixMilli()
|
||||
raw, err := json.Marshal(profile.LastLoginMS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.State.PutEntry("directory", "friend_publication", "last_login", raw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(profile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Publish(command.Event{ID: fmt.Sprintf("friend-profile:%d", profile.Version), Topic: "friend.directory", Payload: raw})
|
||||
}
|
||||
|
||||
func (p *playerInstance) prepareFriends(ctx context.Context, request player.Command) (map[int]player.Response, error) {
|
||||
var responses map[int]player.Response
|
||||
if p.factory.shared == nil || p.factory.shared.friends == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var own social.FriendProfile
|
||||
for index, item := range request.Requests {
|
||||
if !social.OwnsFriend(item.Path) {
|
||||
continue
|
||||
}
|
||||
if social.FriendMutates(item.Path) && len(request.Requests) != 1 {
|
||||
return nil, &command.GameError{PacketCode: 204, ErrorType: 9003, Message: "Friend changes require a standalone request"}
|
||||
}
|
||||
if own.OwnerIndex == 0 {
|
||||
err := p.readLocal(ctx, request.Identity, func(c command.Context) error {
|
||||
var err error
|
||||
own.OwnerIndex, err = p.assembly.ProfileOwner(c)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := p.factory.shared.friends.Profile(ctx, own.OwnerIndex); errors.Is(err, social.ErrNotFound) {
|
||||
if err := p.readLocal(ctx, request.Identity, func(c command.Context) error { var err error; own, err = p.assembly.publicFriendProfile(c); return err }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := p.factory.shared.friends.Publish(ctx, own); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
code, body, err := p.factory.shared.friends.Execute(ctx, request.Identity, own.OwnerIndex, item.Path, item.Body)
|
||||
if errors.Is(err, social.ErrConflict) {
|
||||
return nil, player.ErrIdentityConflict
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if responses == nil {
|
||||
responses = map[int]player.Response{}
|
||||
}
|
||||
responses[index] = player.Response{PacketCode: code, Body: body}
|
||||
}
|
||||
return responses, nil
|
||||
}
|
||||
|
||||
func friendProfileChanged(requests []player.Request) bool {
|
||||
for _, r := range requests {
|
||||
for _, prefix := range []string{"/Equip", "/CharGrowth", "/CharAwake", "/CharImprint", "/CharImmortal", "/Costume", "/Gacha", "/MercenaryScout", "/CharSpecialScout", "/PrestigeSkin"} {
|
||||
if strings.HasPrefix(r.Path, prefix) && !strings.HasSuffix(r.Path, "Info") && !strings.HasSuffix(r.Path, "InfoList") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
switch r.Path {
|
||||
case "/UserPortraitChange", "/UserTitleChange", "/UserNicknameChange", "/SupporterRegister", "/SupporterRemove", "/UpdateUserContentsInfoOption", "/UserGreetingChange", "/IdCardSave", "/IdCardRecovery", "/AvatarUse", "/AvatarSave", "/GuildCreate", "/GuildJoin", "/GuildLeave", "/GuildMemberBan", "/GuildInfoEdit", "/GuildNameChange", "/CharLevelUp", "/CostumeLevelUp", "/CharAwake", "/EquipUse", "/EquipUpgrade", "/CostumePotentialUpgrade", "/PrestigeSkinUse":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"bd2server/internal/server/domain/events/calendar"
|
||||
"bd2server/internal/server/domain/identity"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
identitystore "bd2server/internal/server/storage/identity"
|
||||
@@ -49,6 +50,15 @@ func newIntegrationFactory(t *testing.T) (*PlayerFactory, []string) {
|
||||
seed := versions.Resolve(versions.SeedDirectory)
|
||||
root := t.TempDir()
|
||||
config := &configuration{versions: versions, calendars: calendars, gameRules: gameconfig.Default(), gameData: resources, gameDataVersion: versions.GameDataVersion, stateDirectory: filepath.Join(root, "state"), devToolsConfig: filepath.Join(root, "development.json"), accountSeed: filepath.Join(seed, "login_user.json"), playerSeed: filepath.Join(seed, "starter_player.json"), readonlySeed: filepath.Join(seed, "readonly.json"), mailSeed: filepath.Join(seed, "mail.json"), deckSeed: filepath.Join(seed, "decks.json"), worldSeed: filepath.Join(seed, "world.json")}
|
||||
config.textModerator, err = textmoderation.New(config.gameRules.TextModeration, root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := config.textModerator.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if err = lockServerState(config.stateDirectory, config.gameRules.Story.StartPackID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) nickname(ctx command.Context) error {
|
||||
initial, found, err := wire.Bytes(p.login.UserInfo, 2)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load initial nickname: %w", err)
|
||||
}
|
||||
if !found || len(initial) == 0 {
|
||||
return fmt.Errorf("initial nickname is missing")
|
||||
}
|
||||
p.nicknameService, err = profile.OpenNickname(ctx, p.gameplayStore, p.ownedItems, p.checkProfileText, p.design.nicknameTicketID, string(initial))
|
||||
if err != nil {
|
||||
return fmt.Errorf("load nickname: %w", err)
|
||||
}
|
||||
return p.login.AttachNickname(p.nicknameService)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
)
|
||||
|
||||
func executeOutboxCommand(tx outbox.PageStore, request *player.SystemRequest) ([]byte, error) {
|
||||
switch request.Kind {
|
||||
case player.ReadOutbox:
|
||||
if len(request.Body) != 0 {
|
||||
return nil, errors.New("outbox read takes no payload")
|
||||
}
|
||||
pending, err := outbox.Read(tx, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(pending)
|
||||
case player.AcknowledgeOutbox:
|
||||
if err := stateio.RequireExactJSONObject(request.Body, "key", "digest"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var receipt struct {
|
||||
Key string `json:"key"`
|
||||
Digest string `json:"digest"`
|
||||
}
|
||||
if err := json.Unmarshal(request.Body, &receipt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, outbox.Acknowledge(tx, receipt.Key, receipt.Digest)
|
||||
default:
|
||||
return nil, errors.New("unknown outbox command")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) profile(ctx command.Context) error {
|
||||
initialTitle, _, err := wire.Varint(p.login.UserInfo, 66)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.profileService, err = profile.Open(ctx, p.gameplayStore, p, p.design.profileDesign, p.eventEconomy, p.checkProfileText, initialTitle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.login.AttachProfileTitle(p.profileService)
|
||||
}
|
||||
|
||||
func (p *playerAssembly) PublicProfile(ctx command.Context, target uint64) (profile.Snapshot, error) {
|
||||
owner, _, err := wire.Varint(p.login.UserInfo, 1)
|
||||
if err != nil {
|
||||
return profile.Snapshot{}, err
|
||||
}
|
||||
if owner != target {
|
||||
if p.shared != nil && p.shared.friends != nil {
|
||||
published, err := p.shared.friends.Profile(context.Background(), target)
|
||||
if err == nil {
|
||||
return published.Snapshot, nil
|
||||
}
|
||||
if !errors.Is(err, social.ErrNotFound) {
|
||||
return profile.Snapshot{}, err
|
||||
}
|
||||
}
|
||||
return profile.Snapshot{}, profile.ErrNotFound
|
||||
}
|
||||
settings, err := p.profileService.Settings(ctx)
|
||||
if err != nil {
|
||||
return profile.Snapshot{}, err
|
||||
}
|
||||
exp, err := p.missionService.AchievementExperience()
|
||||
if err != nil {
|
||||
return profile.Snapshot{}, err
|
||||
}
|
||||
portrait := p.deckStateStore.PortraitCostume()
|
||||
var portraitDesign uint64
|
||||
if costume, ok := p.collection.CostumeByID(portrait); ok {
|
||||
portraitDesign = costume.DesignID
|
||||
}
|
||||
rank, percent, err := p.monsterHuntService.ProfileRank()
|
||||
if err != nil {
|
||||
return profile.Snapshot{}, err
|
||||
}
|
||||
supporters, err := p.profileService.SupporterBases(ctx, settings)
|
||||
if err != nil {
|
||||
return profile.Snapshot{}, err
|
||||
}
|
||||
avatar, err := p.avatarService.CurrentUse(ctx)
|
||||
if err != nil {
|
||||
return profile.Snapshot{}, err
|
||||
}
|
||||
return profile.Snapshot{
|
||||
OwnerIndex: owner, UserID: p.nicknameService.CurrentNickname(), TitleID: settings.TitleID,
|
||||
PortraitCostumeID: portrait, PortraitDesignID: portraitDesign,
|
||||
AchievementLevel: p.design.levelDesign.Level(exp), TotalBattlePower: p.deckStateStore.HighestTotalBattlePower(),
|
||||
MonsterHuntRank: rank, MonsterHuntTopPercent: percent, Card: settings.Card,
|
||||
Greeting: settings.Greeting, IsAllPrivate: settings.IsAllPrivate, Options: settings.Options, SortIDs: settings.SortIDs, Supporters: supporters, AvatarUse: &avatar,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *playerAssembly) OwnedItems(ctx command.Context) []assets.Item { return p.ownedItems.All(ctx) }
|
||||
func (p *playerAssembly) OwnedCostume(id uint64) (profile.CostumeBase, bool) {
|
||||
costume, ok := p.collection.CostumeByID(id)
|
||||
return profile.CostumeBase{ID: costume.ID, Level: costume.Level, DesignID: costume.DesignID}, ok
|
||||
}
|
||||
func (p *playerAssembly) SelectPortrait(ctx command.Context, id uint64) error {
|
||||
return p.deckStateStore.SelectPortrait(ctx, id, p.design.profileDesign.DefaultPortraitCostumeID)
|
||||
}
|
||||
func (p *playerAssembly) ProfileOwner(command.Context) (uint64, error) {
|
||||
owner, _, err := wire.Varint(p.login.UserInfo, 1)
|
||||
return owner, err
|
||||
}
|
||||
func (p *playerAssembly) CardUnlocked(ctx command.Context, item gamedata.ProfileCardItem) (bool, error) {
|
||||
switch item.Unlock {
|
||||
case 0:
|
||||
return true, nil
|
||||
case 1:
|
||||
for _, pack := range item.Magic {
|
||||
if !p.worldService.CashPackagePackCleared(pack, 0) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
case 2, 3:
|
||||
return false, nil
|
||||
case 4:
|
||||
for _, own := range p.ownedItems.All(ctx) {
|
||||
if own.Type == 47 && own.ID == item.ID && own.Count > 0 {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
default:
|
||||
return false, fmt.Errorf("profile: unsupported card unlock rule %d", item.Unlock)
|
||||
}
|
||||
}
|
||||
func (p *playerAssembly) SupporterDetails(ctx command.Context, charIndex, costumeIndex uint64) (profile.SupporterDetails, error) {
|
||||
character, ok := p.worldService.CharacterService().Find(ctx, charIndex)
|
||||
if !ok || roster.IsStoryCharacter(character) || roster.IsCharmCharacter(character) {
|
||||
return profile.SupporterDetails{}, fmt.Errorf("profile: supporter character is not permanent-owned")
|
||||
}
|
||||
costume, ok := p.collection.CostumeByIndex(costumeIndex)
|
||||
if !ok {
|
||||
return profile.SupporterDetails{}, fmt.Errorf("profile: supporter costume is not owned")
|
||||
}
|
||||
d, ok := p.design.rewardCostumes.Character(costume.ID)
|
||||
if !ok || character.ID != d.ID && !slices.Contains(d.GrowthCharacterIDs, character.ID) {
|
||||
return profile.SupporterDetails{}, fmt.Errorf("profile: supporter costume belongs to a different character")
|
||||
}
|
||||
unique, ok := p.design.charAwakeDesign.CharacterUniqueID(character.ID)
|
||||
if !ok {
|
||||
return profile.SupporterDetails{}, fmt.Errorf("profile: supporter character has no static identity")
|
||||
}
|
||||
details := profile.SupporterDetails{Character: character, UniqueID: unique}
|
||||
details.Awake, _ = p.collection.CharAwakeState(unique)
|
||||
for _, owned := range p.collection.Costumes() {
|
||||
design, ok := p.design.rewardCostumes.Character(owned.ID)
|
||||
if ok {
|
||||
uid, known := p.design.charAwakeDesign.CharacterUniqueID(design.ID)
|
||||
if known && uid == unique {
|
||||
details.Costumes = append(details.Costumes, owned)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, equipment := range p.ownedEquipment.All(ctx) {
|
||||
if equipment.UseChar == charIndex {
|
||||
details.Equipment = append(details.Equipment, equipment)
|
||||
}
|
||||
}
|
||||
return details, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) multiplayerPVP(ctx command.Context) error {
|
||||
if p.pvpSource == nil {
|
||||
return nil
|
||||
}
|
||||
owner, err := p.ProfileOwner(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
profile, err := p.PublicProfile(ctx, owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
exp, err := p.missionService.AchievementExperience()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
public := pvp.Profile{OwnerID: ctx.AccountID, OwnerIndex: owner, Name: profile.UserID, XP: exp, PortraitCostume: profile.PortraitCostumeID, PortraitDesign: profile.PortraitDesignID, Title: profile.TitleID}
|
||||
builder := &pvp.OwnedSnapshotBuilder{Design: p.design.pvp.Design, Characters: p.worldService.CharacterService(), Collection: p.collection, Equipment: p.ownedEquipment, OwnerIndex: owner,
|
||||
Buffs: func(ctx command.Context) ([]gamedata.PictorialBuffStat, error) {
|
||||
_, buffs, err := p.pictorialService.Snapshot(ctx)
|
||||
return buffs, err
|
||||
}}
|
||||
p.pvpService, err = pvp.Open(ctx, p.design.pvp, public, p.pvpSource, builder,
|
||||
func(ctx command.Context, id string, cost []gamedata.BattleReward) error {
|
||||
_, err := p.eventEconomy.Apply(ctx, id, pvpRewards(cost), nil)
|
||||
return err
|
||||
}, func(ctx command.Context, id string, reward []gamedata.BattleReward) ([]byte, error) {
|
||||
return p.eventEconomy.Apply(ctx, id, nil, pvpRewards(reward))
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = p.pvpService.AttachPlayerViews(func(ctx command.Context, typ uint64) (uint64, error) {
|
||||
field, ok := events.AdditionalCurrencyFields[typ]
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("pvp: unsupported ticket currency")
|
||||
}
|
||||
values, err := p.eventEconomy.AdditionalCurrencies(ctx)
|
||||
return values[field], err
|
||||
}, func(ctx command.Context) (pvp.Profile, error) {
|
||||
current, err := p.PublicProfile(ctx, owner)
|
||||
if err != nil {
|
||||
return pvp.Profile{}, err
|
||||
}
|
||||
xp, err := p.missionService.AchievementExperience()
|
||||
if err != nil {
|
||||
return pvp.Profile{}, err
|
||||
}
|
||||
return pvp.Profile{OwnerID: ctx.AccountID, OwnerIndex: owner, Name: current.UserID, XP: xp, PortraitCostume: current.PortraitCostumeID, PortraitDesign: current.PortraitDesignID, Title: current.TitleID}, nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = p.login.AttachColosseumSlots(p.pvpService); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.login.AttachAdditionalCurrencies(pvpLoginCurrencies{p})
|
||||
}
|
||||
|
||||
type pvpLoginCurrencies struct{ player *playerAssembly }
|
||||
|
||||
func (p pvpLoginCurrencies) AdditionalCurrencies(ctx command.Context) (map[int]uint64, error) {
|
||||
if err := p.player.pvpService.RefreshTickets(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.player.eventEconomy.AdditionalCurrencies(ctx)
|
||||
}
|
||||
|
||||
func pvpRewards(in []gamedata.BattleReward) []gamedata.Reward {
|
||||
out := make([]gamedata.Reward, len(in))
|
||||
for i, reward := range in {
|
||||
out[i] = gamedata.Reward(reward)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"context"
|
||||
)
|
||||
|
||||
func (p *playerInstance) prepareRoomResults(ctx context.Context, requests []player.Request) (func(), error) {
|
||||
base := p.factory.roomResults
|
||||
if base == nil {
|
||||
return func() {}, nil
|
||||
}
|
||||
needed := false
|
||||
for _, request := range requests {
|
||||
switch request.Path {
|
||||
case "/MiniGameActionStart", "/MiniGameActionEnd", "/MiniGameDefenseStart", "/MiniGameDefenseEnd", "/FishingVoyageStart", "/FishingVoyageEnd":
|
||||
needed = true
|
||||
}
|
||||
}
|
||||
if !needed {
|
||||
return func() {}, nil
|
||||
}
|
||||
assembly := p.assembly
|
||||
runs := assembly.eventPlayService.NativeRuns()
|
||||
runs = append(runs, assembly.fishingService.NativeRuns()...)
|
||||
prepared, err := base.PrepareResults(ctx, p.accountID, runs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
assembly.eventPlayService.AttachRooms(prepared)
|
||||
assembly.fishingService.AttachRooms(prepared)
|
||||
return func() { assembly.eventPlayService.AttachRooms(base); assembly.fishingService.AttachRooms(base) }, nil
|
||||
}
|
||||
@@ -6,29 +6,58 @@ import (
|
||||
"bd2server/internal/server/domain/commerce"
|
||||
"bd2server/internal/server/domain/commerce/gacha"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/protocol/defaults"
|
||||
scheduleadapter "bd2server/internal/server/protocol/schedule"
|
||||
"bd2server/internal/server/protocol/staticdata"
|
||||
"bd2server/internal/server/storage/account"
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (p *playerAssembly) session(ctx command.Context) error {
|
||||
if err := p.nickname(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.avatar(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.profile(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.chat(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.multiplayerPVP(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
p.handlers = []session.Handler{
|
||||
p.chatService,
|
||||
p.nicknameService,
|
||||
p.avatarService,
|
||||
friendSupporterDetailHandler{owner: p.ProfileOwner, load: func(ctx command.Context, target uint64) (map[uint64][]byte, error) {
|
||||
if p.shared == nil || p.shared.friends == nil {
|
||||
return nil, profile.ErrNotFound
|
||||
}
|
||||
published, err := p.shared.friends.Profile(context.Background(), target)
|
||||
return published.SupporterDetails, err
|
||||
}},
|
||||
p.profileService,
|
||||
commerce.PackInfoHandler{World: p.worldService, Claims: p.clearPackages},
|
||||
p.worldService,
|
||||
p.progressState,
|
||||
p.cashService,
|
||||
p.cashBonuses,
|
||||
p.clearPackages,
|
||||
commerce.PackInfoHandler{World: p.worldService, Claims: p.clearPackages},
|
||||
commerce.AttendanceHandler{Events: p.eventTasksService, Economy: p.cashEconomy, LoginPasses: p.loginPasses, Store: p.gameplayStore},
|
||||
p.eventRegistry,
|
||||
p.eventGamesService,
|
||||
p.eventExchangeService,
|
||||
p.boxService,
|
||||
p.eventPlayService,
|
||||
p.fishingService,
|
||||
p.eventActionsService,
|
||||
p.npcShopService,
|
||||
p.innService,
|
||||
@@ -65,6 +94,9 @@ func (p *playerAssembly) session(ctx command.Context) error {
|
||||
readonly.Service{Seed: p.seeds.defaults},
|
||||
feature.Service{},
|
||||
}
|
||||
if p.pvpService != nil {
|
||||
p.handlers = append([]session.Handler{p.pvpService}, p.handlers...)
|
||||
}
|
||||
p.observers = []session.ResponseObserver{p.achievementObserver, p.eventTasksService, p.mailService}
|
||||
featured := gacha.ActivePickupCostumes(p.design.regularGacha, p.options.calendars.GachaSeed, uint64(time.Now().UTC().UnixMilli()))
|
||||
limitedIDs := p.design.limitedCostumes.Excluding(featured)
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/design/schedule"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
)
|
||||
|
||||
func (p *playerInstance) recoverSharedBattle(ctx context.Context) (result error) {
|
||||
if p.factory.shared == nil {
|
||||
return nil
|
||||
}
|
||||
service, err := p.socialService()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := p.repository.BeginCommand(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
finished := false
|
||||
defer func() {
|
||||
if !finished {
|
||||
result = errors.Join(result, tx.Rollback())
|
||||
}
|
||||
}()
|
||||
c := command.Context{Identity: command.Identity{AccountID: p.accountID, SessionID: "recovery", RequestID: "shared-battle"}, State: tx, Cancellation: ctx}
|
||||
published := false
|
||||
c.Emit = func(event command.Event) error {
|
||||
if err := outbox.Publish(tx, p.accountID, event); err != nil {
|
||||
return err
|
||||
}
|
||||
published = true
|
||||
return nil
|
||||
}
|
||||
if err := service.AbandonBattle(c); err != nil {
|
||||
return err
|
||||
}
|
||||
err = tx.Commit()
|
||||
finished = true
|
||||
if err == nil && published && p.factory.wakeOutbox != nil {
|
||||
p.factory.wakeOutbox(p.accountID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *playerInstance) reconcileSocial(ctx context.Context, request player.Command) (player.Reply, error) {
|
||||
var reservation social.Reservation
|
||||
if err := json.Unmarshal(request.System.Body, &reservation); err != nil {
|
||||
return player.Reply{}, err
|
||||
}
|
||||
if p.factory.shared == nil || reservation.ActorAccount != p.accountID || reservation.ID == "" {
|
||||
return player.Reply{}, social.ErrPermission
|
||||
}
|
||||
var proof *social.CommitProof
|
||||
err := p.readLocal(ctx, request.Identity, func(c command.Context) error {
|
||||
raw, found, err := c.State.LoadEntry("social", "receipts", reservation.ID)
|
||||
if err != nil || !found {
|
||||
return err
|
||||
}
|
||||
value, err := social.CommittedProof(raw)
|
||||
if err == nil {
|
||||
proof = &value
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return player.Reply{}, err
|
||||
}
|
||||
_, err = p.factory.shared.guild.RecoverReservation(ctx, reservation.ID, proof)
|
||||
return player.Reply{Responses: []player.Response{{}}}, err
|
||||
}
|
||||
|
||||
func (p *playerInstance) readLocal(ctx context.Context, identity command.Identity, read func(command.Context) error) (result error) {
|
||||
tx, err := p.repository.BeginCommand(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if err := tx.Rollback(); err != nil {
|
||||
p.assembly = nil
|
||||
p.sharedSocial = nil
|
||||
result = player.Failure{Cause: errors.Join(result, err), RecoveryRequired: true}
|
||||
}
|
||||
}()
|
||||
result = read(command.Context{Identity: identity, Cancellation: ctx, State: tx})
|
||||
if tx.Dirty() {
|
||||
p.assembly = nil
|
||||
p.sharedSocial = nil
|
||||
return player.Failure{Cause: errors.Join(result, errors.New("shared preparation mutated player state")), RecoveryRequired: true}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (p *playerInstance) guildQualification(ctx context.Context, identity command.Identity, path string) error {
|
||||
if !social.Mutates(path) || path == "/GuildInfo" {
|
||||
return nil
|
||||
}
|
||||
return p.readLocal(ctx, identity, func(c command.Context) error {
|
||||
rule := p.factory.design.guild.Open
|
||||
exp, err := p.assembly.missionService.AchievementExperience()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p.factory.design.levelDesign.Level(exp) < rule.SquadLevel {
|
||||
return social.ErrIneligible
|
||||
}
|
||||
if rule.TicketID == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, item := range p.assembly.ownedItems.All(c) {
|
||||
if item.Type == 19 && item.ID == rule.TicketID && item.Count > 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return social.ErrIneligible
|
||||
})
|
||||
}
|
||||
|
||||
func (p *playerInstance) socialService() (*social.Service, error) {
|
||||
if p.sharedSocial != nil {
|
||||
return p.sharedSocial, nil
|
||||
}
|
||||
a := p.assembly
|
||||
service, err := social.NewService(p.socialServiceConfig())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.sharedSocial = service
|
||||
a.battleService.AttachEventBattle(service)
|
||||
if err := a.login.AttachGuildRaidSlots(func(ctx command.Context) (uint64, error) {
|
||||
state, err := social.LoadRaidState(ctx.State)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if state.PresetSlots == 0 {
|
||||
return a.design.presetDesign.BaseCount, nil
|
||||
}
|
||||
return state.PresetSlots, nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return service, nil
|
||||
}
|
||||
|
||||
func (p *playerInstance) socialServiceConfig() social.ServiceConfig {
|
||||
a := p.assembly
|
||||
member := func(ctx context.Context, identity command.Identity) (social.PublicMember, error) {
|
||||
var out social.PublicMember
|
||||
err := p.readLocal(ctx, identity, func(c command.Context) error {
|
||||
owner, err := a.ProfileOwner(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
profile, err := a.PublicProfile(c, owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = social.PublicMember{AccountID: identity.AccountID, OwnerIndex: owner, Name: profile.UserID, TitleID: profile.TitleID, PortraitID: profile.PortraitCostumeID, PortraitDesignID: profile.PortraitDesignID, LastLoginMS: time.Now().UnixMilli()}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
var seasons []social.Season
|
||||
for _, content := range p.factory.options.calendars.RegularService.Contents {
|
||||
if content.ID != 6 {
|
||||
continue
|
||||
}
|
||||
seen := map[uint64]bool{}
|
||||
for _, s := range []schedule.Season{content.Current, content.Next} {
|
||||
if seen[s.ID] {
|
||||
continue
|
||||
}
|
||||
seen[s.ID] = true
|
||||
seasons = append(seasons, social.Season{ID: s.ID, BossGroupID: s.ID, RulesVersion: a.options.gameDataVersion, StartsMS: int64(s.StartMilliseconds), EndsMS: int64(s.EndMilliseconds)})
|
||||
}
|
||||
}
|
||||
return social.ServiceConfig{Owner: p.factory.shared.guild, Profile: member,
|
||||
BattleBuffs: a.battleService.PictorialBuffs,
|
||||
RaidSeasons: seasons,
|
||||
RaidState: func(ctx context.Context, identity command.Identity) (social.RaidState, error) {
|
||||
var state social.RaidState
|
||||
err := p.readLocal(ctx, identity, func(c command.Context) error { var err error; state, err = social.LoadRaidState(c.State); return err })
|
||||
return state, err
|
||||
},
|
||||
Characters: a.worldService.CharacterService(), Collection: a.collection, Equipment: a.ownedEquipment, Presets: a.design.presetDesign,
|
||||
BeginBattle: a.battleService.BeginExternal, BattleRounds: a.battleService.RoundCount,
|
||||
RewardBundle: func(c command.Context, id string, rewards []gamedata.Reward) ([]byte, error) {
|
||||
return a.eventEconomy.Apply(c, id, nil, rewards)
|
||||
},
|
||||
Qualify: func(ctx context.Context, identity command.Identity, path string) error {
|
||||
return p.guildQualification(ctx, identity, path)
|
||||
},
|
||||
Supporter: func(ctx context.Context, identity command.Identity, char, costume uint64) (social.SupporterSlot, error) {
|
||||
profile, err := member(ctx, identity)
|
||||
if err != nil {
|
||||
return social.SupporterSlot{}, err
|
||||
}
|
||||
var out social.SupporterSlot
|
||||
err = p.readLocal(ctx, identity, func(c command.Context) error {
|
||||
details, err := a.SupporterDetails(c, char, costume)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out, err = social.SupporterSnapshot(profile, details, char, costume, a.options.gameDataVersion)
|
||||
return err
|
||||
})
|
||||
return out, err
|
||||
},
|
||||
CheckText: func(ctx context.Context, identity command.Identity, scope, text string) error {
|
||||
return a.checkProfileText(command.Context{Identity: identity, Cancellation: ctx}, scope, text)
|
||||
},
|
||||
Spend: func(c command.Context, id string, costs []gamedata.Reward) error {
|
||||
_, err := a.eventEconomy.Apply(c, "guild-cost:"+id, costs, nil)
|
||||
return err
|
||||
},
|
||||
Grant: func(c command.Context, id string, rewards []gamedata.Reward) error {
|
||||
_, err := a.eventEconomy.Apply(c, "guild-reward:"+id, nil, rewards)
|
||||
return err
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *playerInstance) prepareSocial(ctx context.Context, request player.Command) (*social.Service, []*social.Plan, error) {
|
||||
plans := make([]*social.Plan, len(request.Requests))
|
||||
if p.factory.shared == nil {
|
||||
return nil, plans, nil
|
||||
}
|
||||
var service *social.Service
|
||||
for i, item := range request.Requests {
|
||||
if !social.Owns(item.Path) {
|
||||
continue
|
||||
}
|
||||
if service == nil {
|
||||
var err error
|
||||
service, err = p.socialService()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
plan, _, err := service.Prepare(ctx, request.Identity, item.Path, item.Body)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("%s prepare: %w", item.Path, err)
|
||||
}
|
||||
plans[i] = plan
|
||||
}
|
||||
return service, plans, nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/domain/world"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/storage/account"
|
||||
)
|
||||
|
||||
var systemSequence atomic.Uint64
|
||||
|
||||
func executePlayerSystem(ctx context.Context, registry *playerRegistry, account string, kind player.SystemKind, body []byte) ([]byte, error) {
|
||||
runtime, release, err := registry.Acquire(ctx, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
digest := sha256.Sum256(append([]byte{byte(kind)}, body...))
|
||||
future, err := runtime.Submit(ctx, player.Command{Identity: command.Identity{AccountID: account, SessionID: "shared-system", RequestID: fmt.Sprint(systemSequence.Add(1))}, Digest: digest, System: &player.SystemRequest{Kind: kind, Body: body}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reply, err := future.Wait(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(reply.Responses) != 1 {
|
||||
return nil, errors.New("invalid player system response")
|
||||
}
|
||||
return reply.Responses[0].Body, nil
|
||||
}
|
||||
|
||||
func (instance *playerInstance) executeSystem(ctx command.Context, tx *accountstate.CommandStore, request *player.SystemRequest) ([]byte, error) {
|
||||
p := instance.assembly
|
||||
if request.Kind == player.StoryCheckpoint {
|
||||
var input world.StoryCheckpointRequest
|
||||
if err := json.Unmarshal(request.Body, &input); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reply, err := p.worldService.StoryCheckpoint(ctx, input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(reply)
|
||||
}
|
||||
if request.Kind == player.CloseExpiredRaid {
|
||||
if instance.sharedSocial == nil {
|
||||
return nil, errors.New("guild runtime is unavailable")
|
||||
}
|
||||
return nil, instance.sharedSocial.CloseExpiredRaid(ctx)
|
||||
}
|
||||
if request.Kind == player.ReadRoomProfile {
|
||||
return p.roomProfile(ctx)
|
||||
}
|
||||
if request.Kind == player.ClosePVPSeason {
|
||||
var closure ranking.Closure
|
||||
if err := json.Unmarshal(request.Body, &closure); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if closure.Owner != ctx.AccountID || p.pvpService == nil {
|
||||
return nil, errors.New("invalid PVP closure owner")
|
||||
}
|
||||
return nil, p.pvpService.CloseSeason(ctx, closure.Mode, closure.Season)
|
||||
}
|
||||
return executeOutboxCommand(tx, request)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
)
|
||||
|
||||
type textApprovalKey struct{}
|
||||
|
||||
type textCandidate struct{ scope, text string }
|
||||
|
||||
type textApprovals struct {
|
||||
identity command.Identity
|
||||
values map[textCandidate]bool
|
||||
}
|
||||
|
||||
type textField struct {
|
||||
scope string
|
||||
code int
|
||||
path []int
|
||||
}
|
||||
|
||||
var playerTextFields = map[string][]textField{
|
||||
"/UserNicknameChange": {{"nickname", 74, []int{2}}},
|
||||
"/UserGreetingChange": {{"greeting", 219, []int{2}}},
|
||||
"/MasterTitleInfoUpdate": {{"master_title", 592, []int{2}}},
|
||||
"/PresetSave": {{"preset_name", 179, []int{2, 1}}},
|
||||
"/PresetInfoChange": {{"preset_name", 278, []int{2}}},
|
||||
"/EquipPresetSave": {{"equipment_preset_name", 254, []int{4}}},
|
||||
"/EquipPresetNameChange": {{"equipment_preset_name", 259, []int{4}}},
|
||||
"/EquipMarkSet": {{"equipment_mark", 396, []int{3}}},
|
||||
"/MonsterHuntPresetSave": {{"monster_hunt_preset_name", 406, []int{2, 1}}},
|
||||
"/MonsterHuntPresetInfoChange": {{"monster_hunt_preset_name", 0, []int{2}}},
|
||||
"/GuildRaidPresetSave": {{"guild_raid_preset_name", 404, []int{2, 1}}},
|
||||
"/GuildRaidPresetInfoChange": {{"guild_raid_preset_name", 0, []int{2}}},
|
||||
"/ColosseumPresetSave": {{"colosseum_preset_name", 494, []int{2, 1}}},
|
||||
"/ColosseumPresetInfoChange": {{"colosseum_preset_name", 497, []int{2}}},
|
||||
"/GuildCreate": {{"guild_name", 296, []int{2}}, {"guild_message", 296, []int{5}}},
|
||||
"/GuildInfoEdit": {{"guild_message", 305, []int{4}}},
|
||||
"/GuildNameChange": {{"guild_name", 570, []int{2}}},
|
||||
"/GuildNoticeUpdate": {{"guild_notice", 382, []int{2}}},
|
||||
}
|
||||
|
||||
func hasPlayerText(requests []player.Request) bool {
|
||||
for _, request := range requests {
|
||||
if len(playerTextFields[request.Path]) != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *playerInstance) prepareText(ctx context.Context, request player.Command) (*textApprovals, error) {
|
||||
if !hasPlayerText(request.Requests) {
|
||||
return nil, nil
|
||||
}
|
||||
if request.Cancellation != nil {
|
||||
ctx = request.Cancellation
|
||||
}
|
||||
approvals := textApprovals{identity: request.Identity, values: map[textCandidate]bool{}}
|
||||
for _, item := range request.Requests {
|
||||
for _, field := range playerTextFields[item.Path] {
|
||||
text := item.Body
|
||||
for _, number := range field.path {
|
||||
var err error
|
||||
text, _, err = wire.Bytes(text, number)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if !utf8.Valid(text) {
|
||||
return nil, wire.ErrMalformed
|
||||
}
|
||||
candidate := textCandidate{field.scope, string(text)}
|
||||
if field.scope == "equipment_mark" {
|
||||
mark, _, _ := strings.Cut(candidate.text, "|")
|
||||
if strings.HasPrefix(mark, "~") {
|
||||
continue
|
||||
}
|
||||
candidate.text = strings.TrimPrefix(mark, "_")
|
||||
}
|
||||
if !approvals.values[candidate] && candidate.text != "" {
|
||||
if err := p.assembly.checkText(ctx, request.Identity.AccountID, field.scope, candidate.text, field.code); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
approvals.values[candidate] = true
|
||||
}
|
||||
}
|
||||
return &approvals, nil
|
||||
}
|
||||
|
||||
func (p *playerAssembly) checkProfileText(ctx command.Context, scope, text string) error {
|
||||
requestContext := ctx.Cancellation
|
||||
if requestContext == nil {
|
||||
requestContext = context.Background()
|
||||
}
|
||||
if approvals, ok := requestContext.Value(textApprovalKey{}).(*textApprovals); ok && approvals.identity == ctx.Identity && approvals.values[textCandidate{scope, text}] {
|
||||
return nil
|
||||
}
|
||||
if ctx.State != nil {
|
||||
return fmt.Errorf("text moderation was not prepared before the player transaction")
|
||||
}
|
||||
code := 74
|
||||
if scope == profile.GreetingText {
|
||||
code = 219
|
||||
}
|
||||
return p.checkText(requestContext, ctx.AccountID, scope, text, code)
|
||||
}
|
||||
|
||||
func (p *playerAssembly) checkText(ctx context.Context, accountID, scope, text string, code int) error {
|
||||
if p.options.textModerator == nil {
|
||||
return fmt.Errorf("text moderation is not initialized")
|
||||
}
|
||||
err := p.options.textModerator.Check(ctx, scope, accountID, text)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, textmoderation.ErrRejected) {
|
||||
return &command.GameError{PacketCode: code, ErrorType: 9001, Message: "Text is not allowed by this server's moderation policy."}
|
||||
}
|
||||
if errors.Is(err, textmoderation.ErrUnavailable) {
|
||||
return &command.GameError{PacketCode: code, ErrorType: 9002, Message: "Text moderation is temporarily unavailable. Please try again."}
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -48,12 +48,14 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error {
|
||||
if err := p.gachaService.AttachSchedule(ctx, p.options.calendars.GachaSeed); err != nil {
|
||||
return fmt.Errorf("attach gacha schedule: %w", err)
|
||||
}
|
||||
previewEventIndex, err := p.seeds.defaults.CashProductEventIndex(p.design.infiniteGacha.ProductGroupID, p.design.infiniteGacha.ProductID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load infinite preview event: %w", err)
|
||||
}
|
||||
if err := p.gachaService.AttachPreviewEventIndex(ctx, previewEventIndex); err != nil {
|
||||
return fmt.Errorf("attach infinite preview event: %w", err)
|
||||
if p.design.infiniteGacha != nil {
|
||||
previewEventIndex, err := p.seeds.defaults.CashProductEventIndex(p.design.infiniteGacha.ProductGroupID, p.design.infiniteGacha.ProductID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load infinite preview event: %w", err)
|
||||
}
|
||||
if err := p.gachaService.AttachPreviewEventIndex(ctx, previewEventIndex); err != nil {
|
||||
return fmt.Errorf("attach infinite preview event: %w", err)
|
||||
}
|
||||
}
|
||||
// The mapped client property is IsDoneFirstGachaPick. Its authoritative
|
||||
// local state is the explicit GachaSubType=3 completion marker.
|
||||
|
||||
@@ -2,8 +2,10 @@ package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Preflight validates the same shared rules as Serve without opening player or authentication databases.
|
||||
@@ -14,6 +16,11 @@ func Preflight(args []string) (preflightErr error) {
|
||||
return err
|
||||
}
|
||||
defer clear(config.authRuntime.MasterKey)
|
||||
moderator, err := textmoderation.New(config.gameRules.TextModeration, filepath.Dir(config.gameConfigPath))
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialize text moderation: %w", err)
|
||||
}
|
||||
defer func() { preflightErr = errors.Join(preflightErr, moderator.Close()) }()
|
||||
seeds, err := loadSeeds(config)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func profileGameplay(t *testing.T) *puzzleGameplay {
|
||||
t.Helper()
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
return g
|
||||
}
|
||||
|
||||
func profileGrant(g *puzzleGameplay, rewards ...gamedata.Reward) {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if _, err := g.owner.assembly.eventEconomy.Apply(command.Context{State: tx}, fmt.Sprintf("profile-test:%d", g.seq), nil, rewards); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func profileSelf(g *puzzleGameplay) []byte {
|
||||
g.t.Helper()
|
||||
identity, err := g.factory.profiles.GameIdentity(context.Background(), g.account)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
return g.call("/UserContentsInfo", wire.AppendVarint(nil, 2, uint64(identity.OwnerIndex)))
|
||||
}
|
||||
|
||||
func profileVarint(t *testing.T, b []byte, field int) uint64 {
|
||||
t.Helper()
|
||||
n, _, err := wire.Varint(b, field)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func profileBytes(t *testing.T, b []byte, field int) []byte {
|
||||
t.Helper()
|
||||
value, found, err := wire.Bytes(b, field)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("missing field%d: %v", field, err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func profileRows(t *testing.T, b []byte, field int) [][]byte {
|
||||
t.Helper()
|
||||
var rows [][]byte
|
||||
if err := wire.Walk(b, func(f wire.Field) error {
|
||||
if f.Number == field {
|
||||
if f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
rows = append(rows, f.Value)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
func profileRepeatedNumbers(t *testing.T, b []byte, field int) []uint64 {
|
||||
t.Helper()
|
||||
var out []uint64
|
||||
if err := wire.Walk(b, func(f wire.Field) error {
|
||||
if f.Number != field {
|
||||
return nil
|
||||
}
|
||||
if f.Type != 0 && f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
for raw := f.Value; len(raw) > 0; {
|
||||
n, size := binary.Uvarint(raw)
|
||||
if size <= 0 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
out = append(out, n)
|
||||
raw = raw[size:]
|
||||
if f.Type == 0 && len(raw) > 0 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestPersonalProfileEditsPersistAndRejectUnownedSelections(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
// TitleItemTable ID1 is real Type26; setup grants an owned test title.
|
||||
profileGrant(g, gamedata.Reward{Type: 26, ID: 1, Count: 1})
|
||||
g.call("/UserGreetingChange", wire.AppendString(nil, 2, "今天很好!"))
|
||||
order := []uint64{0, 5, 12, 1, 3, 4, 6, 7, 8, 9, 10, 11}
|
||||
options := wire.AppendVarint(nil, 2, 1)
|
||||
for _, hidden := range []uint64{1, 12} {
|
||||
options = wire.AppendVarint(options, 3, hidden)
|
||||
}
|
||||
for _, n := range order {
|
||||
options = wire.AppendVarint(options, 4, n)
|
||||
}
|
||||
g.call("/UpdateUserContentsInfoOption", options)
|
||||
g.call("/UserTitleChange", wire.AppendVarint(nil, 2, 1))
|
||||
portrait := g.owner.assembly.collection.Costumes()[0].ID
|
||||
g.call("/UserPortraitChange", wire.AppendVarint(nil, 2, portrait))
|
||||
g.reopen()
|
||||
assertSettings := func() {
|
||||
t.Helper()
|
||||
body := profileSelf(g)
|
||||
if string(profileBytes(t, body, 5)) != "今天很好!" || profileVarint(t, body, 11) != 1 || profileVarint(t, body, 3) != 1 || profileVarint(t, body, 4) != portrait {
|
||||
t.Fatal("saved profile edits are missing")
|
||||
}
|
||||
sorts := profileRepeatedNumbers(t, body, 27)
|
||||
hidden := profileRepeatedNumbers(t, body, 12)
|
||||
slices.Sort(hidden)
|
||||
if !slices.Equal(sorts, order) || !slices.Equal(hidden, []uint64{1, 12}) {
|
||||
t.Fatalf("saved visibility/order=%v/%v", hidden, sorts)
|
||||
}
|
||||
login := profileBytes(t, g.call("/LoginUser", nil), 1)
|
||||
if profileVarint(t, login, 66) != 1 {
|
||||
t.Fatal("LoginUser did not project selected owned title")
|
||||
}
|
||||
}
|
||||
assertSettings()
|
||||
for _, bad := range []string{"abc", "hello\tworld", "hello😀"} {
|
||||
g.execute(g.request("/UserGreetingChange", wire.AppendString(nil, 2, bad)), true)
|
||||
}
|
||||
for _, bad := range []struct {
|
||||
path string
|
||||
fields []byte
|
||||
}{
|
||||
{"/UserTitleChange", wire.AppendVarint(nil, 2, 2)},
|
||||
{"/UserPortraitChange", wire.AppendVarint(nil, 2, math.MaxInt32)},
|
||||
{"/UpdateUserContentsInfoOption", wire.AppendVarint(nil, 3, 0)},
|
||||
{"/UpdateUserContentsInfoOption", wire.AppendVarint(wire.AppendVarint(nil, 4, 0), 4, 5)},
|
||||
} {
|
||||
g.execute(g.request(bad.path, bad.fields), true)
|
||||
}
|
||||
assertSettings()
|
||||
g.call("/UserTitleChange", nil)
|
||||
g.call("/UserPortraitChange", nil)
|
||||
g.reopen()
|
||||
if body := profileSelf(g); profileVarint(t, body, 3) != 0 || profileVarint(t, body, 4) != 0 {
|
||||
t.Fatal("cleared title/portrait did not persist")
|
||||
}
|
||||
if profileVarint(t, profileBytes(t, g.call("/LoginUser", nil), 1), 66) != 0 {
|
||||
t.Fatal("cleared title remains in LoginUser")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPlayerCanPersistGameDataDefaultPortraitWithoutOwningCostume(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
login := profileBytes(t, g.call("/LoginUser", nil), 1)
|
||||
if profileVarint(t, login, 14) != 0 {
|
||||
t.Fatal("fresh player must start without a selected portrait")
|
||||
}
|
||||
// UserDBInfo.SetPortraitCostumeId sends GameDefaultTable field29 when the login portrait is zero.
|
||||
defaultPortrait := g.factory.design.profileDesign.DefaultPortraitCostumeID
|
||||
if defaultPortrait == 0 {
|
||||
t.Fatal("GameData default portrait is missing")
|
||||
}
|
||||
if _, owned := g.owner.assembly.collection.CostumeByID(defaultPortrait); owned {
|
||||
t.Fatal("starter already owns the default portrait; unowned default scenario was lost")
|
||||
}
|
||||
costumeCount := len(g.owner.assembly.collection.Costumes())
|
||||
changed := g.call("/UserPortraitChange", wire.AppendVarint(nil, 2, defaultPortrait))
|
||||
if profileVarint(t, changed, 1) != defaultPortrait {
|
||||
t.Fatal("default portrait request was not acknowledged")
|
||||
}
|
||||
g.reopen()
|
||||
assertDefault := func() {
|
||||
t.Helper()
|
||||
if profileVarint(t, profileSelf(g), 4) != defaultPortrait {
|
||||
t.Fatal("default portrait selection did not persist in public profile")
|
||||
}
|
||||
if profileVarint(t, profileBytes(t, g.call("/LoginUser", nil), 1), 14) != defaultPortrait {
|
||||
t.Fatal("LoginUser did not project the saved default portrait")
|
||||
}
|
||||
if _, owned := g.owner.assembly.collection.CostumeByID(defaultPortrait); owned || len(g.owner.assembly.collection.Costumes()) != costumeCount {
|
||||
t.Fatal("selecting the default portrait granted costume ownership")
|
||||
}
|
||||
}
|
||||
assertDefault()
|
||||
_, candidates := g.factory.design.regularGacha.MigrationFacts()
|
||||
var unowned uint64
|
||||
for _, candidate := range candidates {
|
||||
if candidate.CostumeID == defaultPortrait {
|
||||
continue
|
||||
}
|
||||
if _, owned := g.owner.assembly.collection.CostumeByID(candidate.CostumeID); !owned {
|
||||
unowned = candidate.CostumeID
|
||||
break
|
||||
}
|
||||
}
|
||||
if unowned == 0 {
|
||||
t.Fatal("current GameData has no unowned alternate costume for the ownership check")
|
||||
}
|
||||
g.execute(g.request("/UserPortraitChange", wire.AppendVarint(nil, 2, unowned)), true)
|
||||
g.reopen()
|
||||
assertDefault()
|
||||
}
|
||||
|
||||
func profileCardItem(index, id uint64, x, y int32, scale float32, color string) []byte {
|
||||
b := wire.AppendVarint(nil, 1, index)
|
||||
b = wire.AppendVarint(b, 2, id)
|
||||
b = wire.AppendVarint(b, 3, uint64(int64(x)))
|
||||
b = wire.AppendVarint(b, 4, uint64(int64(y)))
|
||||
b = binary.AppendUvarint(b, 6<<3|5)
|
||||
b = binary.LittleEndian.AppendUint32(b, math.Float32bits(scale))
|
||||
return wire.AppendString(b, 8, color)
|
||||
}
|
||||
|
||||
func profileBuy(id, price uint64) []byte {
|
||||
payment := wire.AppendVarint(nil, 3, 44)
|
||||
payment = wire.AppendVarint(payment, 4, price)
|
||||
item := wire.AppendVarint(nil, 1, id)
|
||||
item = wire.AppendVarint(item, 2, 1)
|
||||
return wire.AppendBytes(nil, 2, wire.AppendBytes(item, 3, payment))
|
||||
}
|
||||
|
||||
func TestIdCardRecoveryShopLayoutsAndPresetsUseRealPersistentOwnership(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
// Current common GameData: 920000 opens to 10001..10020 and40001,
|
||||
// each Type47 count1. Shop10101 costs100 Type44, illustration30001 costs150.
|
||||
if g.itemCount(47, 10001) != 0 {
|
||||
t.Fatal("fixture unexpectedly owns default card")
|
||||
}
|
||||
recovery := g.request("/IdCardRecovery", nil)
|
||||
first := g.execute(recovery, false)
|
||||
if !bytes.Equal(first, g.execute(recovery, false)) {
|
||||
t.Fatal("recovery replay differs")
|
||||
}
|
||||
profileBytes(t, first, 1)
|
||||
defaultCard := profileBytes(t, first, 2)
|
||||
background := profileBytes(t, defaultCard, 1)
|
||||
if profileVarint(t, background, 2) != 10001 || profileVarint(t, background, 1) == 0 {
|
||||
t.Fatal("default layout is not bound to actual inventory")
|
||||
}
|
||||
for id := uint64(10001); id <= 10020; id++ {
|
||||
if g.itemCount(47, id) != 1 {
|
||||
t.Fatalf("default background%d count !=1", id)
|
||||
}
|
||||
}
|
||||
if g.itemCount(47, 40001) != 1 {
|
||||
t.Fatal("default sticker grant missing")
|
||||
}
|
||||
g.reopen()
|
||||
recoveryReplay := recovery
|
||||
recoveryReplay.Identity.RequestID += "-domain-replay"
|
||||
if !bytes.Equal(first, g.execute(recoveryReplay, false)) {
|
||||
t.Fatal("reopened recovery domain receipt did not replay its actual reward bundle")
|
||||
}
|
||||
second := g.call("/IdCardRecovery", nil)
|
||||
if _, found, err := wire.Bytes(second, 1); found || err != nil {
|
||||
t.Fatal("fresh recovery repeated default grant")
|
||||
}
|
||||
for id := uint64(10001); id <= 10020; id++ {
|
||||
if g.itemCount(47, id) != 1 {
|
||||
t.Fatalf("recovery duplicated background%d", id)
|
||||
}
|
||||
}
|
||||
profileGrant(g, gamedata.Reward{Type: 44, Count: 500})
|
||||
budget := g.wordCurrency()
|
||||
g.execute(g.request("/IdCardShopBuy", profileBuy(10101, 99)), true)
|
||||
batch := append(profileBuy(10101, 100), profileBuy(30001, 149)...)
|
||||
g.execute(g.request("/IdCardShopBuy", batch), true)
|
||||
if g.wordCurrency() != budget || g.itemCount(47, 10101) != 0 || g.itemCount(47, 30001) != 0 {
|
||||
t.Fatal("rejected batch spent money or granted a partial purchase")
|
||||
}
|
||||
buy := g.request("/IdCardShopBuy", append(profileBuy(10101, 100), profileBuy(30001, 150)...))
|
||||
reply := g.execute(buy, false)
|
||||
if !bytes.Equal(reply, g.execute(buy, false)) {
|
||||
t.Fatal("purchase replay differs")
|
||||
}
|
||||
domainReplay := buy
|
||||
domainReplay.Identity.RequestID += "-domain-replay"
|
||||
if !bytes.Equal(reply, g.execute(domainReplay, false)) {
|
||||
t.Fatal("card purchase domain receipt did not replay for a new actor request identity")
|
||||
}
|
||||
conflict := buy
|
||||
conflict.Identity.RequestID += "-domain-conflict"
|
||||
conflict.Requests = slices.Clone(buy.Requests)
|
||||
// Independent GameData:10102 is unrestricted, unowned, max1 and costs100.
|
||||
// Its otherwise-valid purchase must fail solely because this seq is spent.
|
||||
if g.itemCount(47, 10102) != 0 {
|
||||
t.Fatal("conflict fixture already owns alternative product")
|
||||
}
|
||||
conflict.Requests[0].Body = append(wire.AppendVarint(nil, 1, profileVarint(t, buy.Requests[0].Body, 1)), profileBuy(10102, 100)...)
|
||||
conflict.Digest = sha256.Sum256(append([]byte("/IdCardShopBuy"), conflict.Requests[0].Body...))
|
||||
g.execute(conflict, true)
|
||||
if g.itemCount(47, 10102) != 0 || g.wordCurrency() != budget-250 {
|
||||
t.Fatal("conflicting economic retry granted alternative product or spent more currency")
|
||||
}
|
||||
if g.wordCurrency() != budget-250 || g.itemCount(47, 10101) != 1 || g.itemCount(47, 30001) != 1 {
|
||||
t.Fatal("card purchase did not exchange actual currency for actual items once")
|
||||
}
|
||||
g.execute(g.request("/IdCardShopBuy", profileBuy(10101, 100)), true)
|
||||
card := wire.AppendBytes(nil, 1, profileCardItem(0, 10101, -123, 45, 1, ""))
|
||||
card = wire.AppendBytes(card, 4, profileCardItem(0, 30001, 12, -34, 0.5, ""))
|
||||
card = wire.AppendBytes(card, 5, profileCardItem(0, 0, -218, 156, 0.75, "FFFFFF80"))
|
||||
card = wire.AppendVarint(card, 6, 90)
|
||||
g.call("/IdCardSave", wire.AppendBytes(nil, 2, card))
|
||||
for index := range uint64(5) {
|
||||
preset := wire.AppendVarint(nil, 1, index)
|
||||
preset = wire.AppendBytes(preset, 2, card)
|
||||
g.call("/IdCardPresetSave", wire.AppendBytes(nil, 2, preset))
|
||||
}
|
||||
g.reopen()
|
||||
assertLayout := func(saved []byte) {
|
||||
t.Helper()
|
||||
if profileVarint(t, saved, 6) != 90 {
|
||||
t.Fatal("card rotation did not persist")
|
||||
}
|
||||
bg := profileBytes(t, saved, 1)
|
||||
if profileVarint(t, bg, 2) != 10101 || profileVarint(t, bg, 1) == 0 || int32(profileVarint(t, bg, 3)) != -123 {
|
||||
t.Fatal("saved card lost purchased background/index/negative coordinate")
|
||||
}
|
||||
art := profileRows(t, saved, 4)
|
||||
if len(art) != 1 || profileVarint(t, art[0], 2) != 30001 || profileVarint(t, art[0], 1) == 0 {
|
||||
t.Fatal("owned illustration not saved with inventory instance")
|
||||
}
|
||||
if string(profileBytes(t, profileBytes(t, saved, 5), 8)) != "FFFFFF80" {
|
||||
t.Fatal("RGBA alpha did not persist")
|
||||
}
|
||||
}
|
||||
assertLayout(profileBytes(t, profileSelf(g), 28))
|
||||
if rows := profileRows(t, g.call("/IdCardPresetInfo", nil), 1); len(rows) != 5 {
|
||||
t.Fatalf("preset count=%d want5", len(rows))
|
||||
} else {
|
||||
seen := map[uint64]bool{}
|
||||
for _, row := range rows {
|
||||
id := profileVarint(t, row, 1)
|
||||
if id >= 5 || seen[id] {
|
||||
t.Fatal("preset IDs do not contain distinct0..4")
|
||||
}
|
||||
seen[id] = true
|
||||
assertLayout(profileBytes(t, row, 2))
|
||||
}
|
||||
}
|
||||
badCards := [][]byte{
|
||||
wire.AppendVarint(wire.AppendBytes(nil, 1, background), 6, 1),
|
||||
wire.AppendBytes(nil, 1, profileCardItem(999999999, 10101, 0, 0, 1, "")),
|
||||
wire.AppendBytes(nil, 4, profileCardItem(0, 30002, 0, 0, 1, "")),
|
||||
wire.AppendBytes(nil, 1, profileCardItem(0, 10101, 0, 0, float32(math.NaN()), "")),
|
||||
wire.AppendBytes(nil, 1, profileCardItem(0, 10101, 0, 0, 1, "BADBAD")),
|
||||
wire.AppendBytes(wire.AppendBytes(nil, 4, profileCardItem(0, 30001, 0, 0, 1, "")), 4, profileCardItem(0, 30001, 0, 0, 1, "")),
|
||||
}
|
||||
for _, bad := range badCards {
|
||||
g.execute(g.request("/IdCardSave", wire.AppendBytes(nil, 2, bad)), true)
|
||||
}
|
||||
preset := wire.AppendVarint(nil, 1, 5)
|
||||
preset = wire.AppendBytes(preset, 2, card)
|
||||
g.execute(g.request("/IdCardPresetSave", wire.AppendBytes(nil, 2, preset)), true)
|
||||
assertLayout(profileBytes(t, profileSelf(g), 28))
|
||||
g.call("/IdCardPresetDelete", wire.AppendVarint(nil, 2, 4))
|
||||
g.reopen()
|
||||
if rows := profileRows(t, g.call("/IdCardPresetInfo", nil), 1); len(rows) != 4 {
|
||||
t.Fatal("preset deletion did not persist")
|
||||
}
|
||||
counts := profileRows(t, g.call("/IdCardShopInfo", nil), 1)
|
||||
if len(counts) != 2 {
|
||||
t.Fatalf("persisted shop purchases=%d want2", len(counts))
|
||||
}
|
||||
for _, row := range counts {
|
||||
if profileVarint(t, row, 2) != 1 {
|
||||
t.Fatal("shop purchase count duplicated")
|
||||
}
|
||||
}
|
||||
if g.wordCurrency() != budget-250 || g.itemCount(47, 10101) != 1 || g.itemCount(47, 30001) != 1 {
|
||||
t.Fatal("card edits or reopening changed purchase economy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupporterRegistrationPreservesSlotsAndReturnsOwnedBattleCharacter(t *testing.T) {
|
||||
g := profileGameplay(t)
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Current CostumeTable101 is permanent character UniqueChar1. The
|
||||
// integration starter only has story characters, so grant actual ownership.
|
||||
if _, err := g.owner.assembly.collection.GrantCostumes(command.Context{State: tx}, "profile-supporter-fixture", []uint64{101}, g.factory.design.rewardCostumes); err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
characters := g.owner.assembly.worldService.CharacterService().All(command.Context{State: tx})
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var charIndex, costumeIndex, costumeID uint64
|
||||
for _, char := range characters {
|
||||
if roster.IsStoryCharacter(char) || roster.IsCharmCharacter(char) {
|
||||
continue
|
||||
}
|
||||
for _, costume := range g.owner.assembly.collection.Costumes() {
|
||||
d, ok := g.factory.design.rewardCostumes.Character(costume.ID)
|
||||
if ok && (char.ID == d.ID || slices.Contains(d.GrowthCharacterIDs, char.ID)) {
|
||||
charIndex, costumeIndex, costumeID = char.InvenIndex, costume.InvenIndex, costume.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
if charIndex != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if charIndex == 0 || costumeIndex == 0 {
|
||||
t.Fatal("fixture has no permanent equipped character")
|
||||
}
|
||||
register := wire.AppendVarint(nil, 2, 1)
|
||||
register = wire.AppendVarint(register, 3, charIndex)
|
||||
register = wire.AppendVarint(register, 4, costumeIndex)
|
||||
register = wire.AppendVarint(register, 5, 123)
|
||||
g.call("/SupporterRegister", register)
|
||||
g.reopen()
|
||||
for _, query := range []struct {
|
||||
path string
|
||||
field int
|
||||
}{{"/SupporterInfo", 1}, {"/SupporterStatus", 2}} {
|
||||
rows := profileRows(t, g.call(query.path, nil), query.field)
|
||||
if len(rows) != 2 || profileVarint(t, rows[0], 1) != 0 || profileVarint(t, rows[1], 1) != costumeID {
|
||||
t.Fatalf("%s lost supporter slot1 placeholder: %v", query.path, rows)
|
||||
}
|
||||
}
|
||||
identity, err := g.factory.profiles.GameIdentity(context.Background(), g.account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail := wire.AppendVarint(nil, 2, uint64(identity.OwnerIndex))
|
||||
detail = wire.AppendVarint(detail, 3, 1)
|
||||
slot := profileBytes(t, g.call("/SupporterDetail", detail), 1)
|
||||
if profileVarint(t, slot, 1) != uint64(identity.OwnerIndex) || profileVarint(t, slot, 2) != 1 || profileVarint(t, slot, 3) != costumeID || profileVarint(t, slot, 4) != 123 || profileVarint(t, slot, 7) == 0 {
|
||||
t.Fatal("supporter details do not reflect actual registered state")
|
||||
}
|
||||
battle, err := base64.StdEncoding.DecodeString(string(profileBytes(t, slot, 6)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
character := profileBytes(t, battle, 1)
|
||||
if profileVarint(t, character, 1) != charIndex || profileVarint(t, character, 5) != costumeID || profileVarint(t, character, 7) != costumeIndex {
|
||||
t.Fatal("supporter battle snapshot is not the chosen owned character/costume")
|
||||
}
|
||||
if len(profileRows(t, battle, 2)) == 0 {
|
||||
t.Fatal("supporter snapshot has no real costumes")
|
||||
}
|
||||
duplicate := wire.AppendVarint(nil, 3, charIndex)
|
||||
duplicate = wire.AppendVarint(duplicate, 4, costumeIndex)
|
||||
g.execute(g.request("/SupporterRegister", duplicate), true)
|
||||
for _, temporary := range characters {
|
||||
if roster.IsStoryCharacter(temporary) || roster.IsCharmCharacter(temporary) {
|
||||
bad := wire.AppendVarint(nil, 3, temporary.InvenIndex)
|
||||
bad = wire.AppendVarint(bad, 4, costumeIndex)
|
||||
g.execute(g.request("/SupporterRegister", bad), true)
|
||||
break
|
||||
}
|
||||
}
|
||||
g.execute(g.request("/SupporterRegister", wire.AppendVarint(wire.AppendVarint(nil, 2, 2), 3, charIndex)), true)
|
||||
g.execute(g.request("/SupporterRegister", wire.AppendVarint(wire.AppendVarint(nil, 3, math.MaxInt64), 4, costumeIndex)), true)
|
||||
g.execute(g.request("/SupporterDetail", wire.AppendVarint(wire.AppendVarint(nil, 2, math.MaxInt64), 3, 1)), true)
|
||||
g.execute(g.request("/SupporterReward", nil), true)
|
||||
g.call("/SupporterRemove", wire.AppendVarint(nil, 2, 1))
|
||||
g.reopen()
|
||||
rows := profileRows(t, g.call("/SupporterInfo", nil), 1)
|
||||
if len(rows) != 2 || profileVarint(t, rows[0], 1) != 0 || profileVarint(t, rows[1], 1) != 0 {
|
||||
t.Fatal("supporter removal did not persist")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
)
|
||||
|
||||
type puzzleGameplay struct {
|
||||
t *testing.T
|
||||
factory *PlayerFactory
|
||||
account string
|
||||
owner *playerInstance
|
||||
seq uint64
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) request(path string, fields []byte) player.Command {
|
||||
g.seq++
|
||||
request := registryCommand(g.account, fmt.Sprintf("puzzle-%d", g.seq), path, append(appScalar(1, g.seq), fields...))
|
||||
if path == "/LoginUser" {
|
||||
request.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) execute(request player.Command, wantFailure bool) []byte {
|
||||
g.t.Helper()
|
||||
reply, err := g.owner.Execute(context.Background(), request)
|
||||
if wantFailure {
|
||||
if err == nil {
|
||||
g.t.Fatalf("%s unexpectedly succeeded", request.Requests[0].Path)
|
||||
}
|
||||
if recoverErr := g.owner.Recover(context.Background()); recoverErr != nil {
|
||||
g.t.Fatal(recoverErr)
|
||||
}
|
||||
return []byte(err.Error())
|
||||
}
|
||||
if err != nil || len(reply.Responses) != 1 {
|
||||
g.t.Fatalf("%s: responses=%d error=%v", request.Requests[0].Path, len(reply.Responses), err)
|
||||
}
|
||||
return reply.Responses[0].Body
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) call(path string, fields []byte) []byte {
|
||||
return g.execute(g.request(path, fields), false)
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) reopen() {
|
||||
g.t.Helper()
|
||||
if err := g.owner.Close(); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
g.owner = nil
|
||||
var err error
|
||||
g.owner, err = g.factory.open(g.account)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) itemCount(itemType, id uint64) uint64 {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
var count uint64
|
||||
for _, item := range g.owner.assembly.ownedItems.All(command.Context{State: tx}) {
|
||||
if item.Type == itemType && item.ID == id {
|
||||
count += item.Count
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) wordCurrency() uint64 {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
balances, err := g.owner.assembly.eventEconomy.AdditionalCurrencies(command.Context{State: tx})
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
return balances[54]
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) grantTokens(count uint64) {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
ctx := command.Context{State: tx}
|
||||
if _, err := g.owner.assembly.ownedItems.GrantOnce(ctx, fmt.Sprintf("puzzle-budget-%d", g.seq), []gamedata.BattleReward{{Type: 8, ID: 2021, Count: count}}); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) cost(field int, count uint64) []byte {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
items, err := g.owner.assembly.ownedItems.SelectMutable(command.Context{State: tx}, 8, 2021, count)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
var fields []byte
|
||||
for _, item := range items {
|
||||
row := append(appScalar(1, item.InvenIndex), appScalar(2, item.ID)...)
|
||||
row = append(row, appScalar(3, item.Type)...)
|
||||
row = append(row, appScalar(4, item.Count)...)
|
||||
fields = append(fields, appMessage(field, row)...)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func puzzleNumbers(t *testing.T, row []byte, wanted int) []uint64 {
|
||||
t.Helper()
|
||||
var numbers []uint64
|
||||
err := wire.Walk(row, func(field wire.Field) error {
|
||||
if field.Number != wanted {
|
||||
return nil
|
||||
}
|
||||
if field.Type == 0 {
|
||||
value, _ := binary.Uvarint(field.Value)
|
||||
numbers = append(numbers, value)
|
||||
return nil
|
||||
}
|
||||
if field.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
for value := field.Value; len(value) > 0; {
|
||||
number, length := binary.Uvarint(value)
|
||||
if length <= 0 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
numbers = append(numbers, number)
|
||||
value = value[length:]
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return numbers
|
||||
}
|
||||
|
||||
func (g *puzzleGameplay) info(uid uint64) []byte {
|
||||
g.t.Helper()
|
||||
rows := appRows(g.call("/MiniPuzzleInfo", appScalar(2, uid)), 1)
|
||||
if len(rows) != 1 || appValue(rows[0], 1) != uid {
|
||||
g.t.Fatalf("puzzle info does not identify schedule %d: %x", uid, rows)
|
||||
}
|
||||
return rows[0]
|
||||
}
|
||||
|
||||
func puzzleResponseState(t *testing.T, response []byte, field int) []byte {
|
||||
t.Helper()
|
||||
rows := appRows(response, field)
|
||||
if len(rows) != 1 {
|
||||
t.Fatalf("puzzle response field %d: got %d rows", field, len(rows))
|
||||
}
|
||||
return rows[0]
|
||||
}
|
||||
|
||||
func puzzleWordReward(t *testing.T, response []byte, itemType, id, count uint64) {
|
||||
t.Helper()
|
||||
bundle := puzzleResponseState(t, response, 5)
|
||||
rows := appRows(bundle, 1)
|
||||
if len(rows) != 1 || appValue(rows[0], 3) != itemType || appValue(rows[0], 2) != id || appValue(rows[0], 4) != count {
|
||||
t.Fatalf("wrong word reward: %x; want %d/%d x %d", bundle, itemType, id, count)
|
||||
}
|
||||
}
|
||||
|
||||
// 2.36.7 MiniGamePuzzleUI.GetPossiblePlayCount bounds maximum-open by the
|
||||
// available token balance and unopened cells. GameData 20261008155037 puzzle
|
||||
// event 10 has 25-cell stages, token 8/2021 x 1, stage-1 word cells 1..7 with
|
||||
// currency 44 x 500, stage-2 material 8/113 x 600, and a terminal stage 12.
|
||||
// This exercises actual client requests, the production reward economy and
|
||||
// the account SQLite transaction rather than an isolated imitation of play.
|
||||
func TestPuzzleMaximumOpenWordsRenewalAndPersistence(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
var schedule events.Schedule
|
||||
for _, candidate := range owner.assembly.eventRegistry.List() {
|
||||
if candidate.Type == 17 && candidate.ID == 10 && candidate.Start <= time.Now().UnixMilli() && candidate.End > time.Now().UnixMilli() {
|
||||
schedule = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if schedule.UID == 0 {
|
||||
t.Fatal("current puzzle event 10 schedule required")
|
||||
}
|
||||
uid := appScalar(2, schedule.UID)
|
||||
g.call("/LoginUser", nil)
|
||||
var loginTask []byte
|
||||
for _, row := range appRows(g.call("/EventMissionInfo", nil), 1) {
|
||||
if appValue(row, 1) == 30030 && appValue(row, 3) == 300301 {
|
||||
loginTask = row
|
||||
}
|
||||
}
|
||||
if appValue(loginTask, 4) != 1 || appValue(loginTask, 5) != 0 {
|
||||
t.Fatalf("puzzle login token mission did not complete: %x", loginTask)
|
||||
}
|
||||
mission := append(appScalar(3, 2), appScalar(4, 30030)...)
|
||||
mission = append(mission, appScalar(5, 300301)...)
|
||||
mission = append(mission, appScalar(6, 30030)...)
|
||||
claimRequest := g.request("/MissionClear", mission)
|
||||
beforeTokens := g.itemCount(8, 2021)
|
||||
g.execute(claimRequest, false)
|
||||
if got := g.itemCount(8, 2021); got != beforeTokens+2 {
|
||||
t.Fatalf("puzzle login mission delivered %d tokens, want %d", got, beforeTokens+2)
|
||||
}
|
||||
claimRequest.Identity.RequestID += "-replay"
|
||||
g.execute(claimRequest, false)
|
||||
if got := g.itemCount(8, 2021); got != beforeTokens+2 {
|
||||
t.Fatal("mission replay delivered tokens twice")
|
||||
}
|
||||
if beforeTokens != 0 {
|
||||
t.Fatal("fresh account unexpectedly contains puzzle tokens")
|
||||
}
|
||||
g.grantTokens(2)
|
||||
first := g.info(schedule.UID)
|
||||
board := puzzleNumbers(t, first, 3)
|
||||
sorted := slices.Clone(board)
|
||||
slices.Sort(sorted)
|
||||
if appValue(first, 2) != 1 || len(sorted) != 25 || sorted[0] != 1 || sorted[24] != 25 || len(slices.Compact(sorted)) != 25 {
|
||||
t.Fatalf("fresh stage has an invalid client board: %x", first)
|
||||
}
|
||||
bad := g.execute(g.request("/MiniPuzzleAllOpen", append(uid, g.cost(3, 3)...)), true)
|
||||
for _, detail := range []string{"/MiniPuzzleAllOpen", fmt.Sprintf("uid=%d", schedule.UID), "submitted=3", "expected=4", "unit_cost=1"} {
|
||||
if !strings.Contains(string(bad), detail) {
|
||||
t.Fatalf("cost diagnostic missing %q: %s", detail, bad)
|
||||
}
|
||||
}
|
||||
if !bytes.Equal(first, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 {
|
||||
t.Fatal("invalid maximum-open cost changed progress or inventory")
|
||||
}
|
||||
forged := append(appScalar(1, 1), appScalar(2, 2021)...)
|
||||
forged = append(forged, appScalar(3, 8)...)
|
||||
forged = append(forged, appScalar(4, 1)...)
|
||||
fields := append(slices.Clone(uid), appScalar(3, board[0])...)
|
||||
g.execute(g.request("/MiniPuzzleOpen", append(fields, appMessage(4, forged)...)), true)
|
||||
if !bytes.Equal(first, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 {
|
||||
t.Fatal("forged stack consumption changed puzzle progress or inventory")
|
||||
}
|
||||
maximum := g.request("/MiniPuzzleAllOpen", append(uid, g.cost(3, 4)...))
|
||||
response := g.execute(maximum, false)
|
||||
after := puzzleResponseState(t, response, 2)
|
||||
opened := puzzleNumbers(t, after, 4)
|
||||
if appValue(after, 2) != 1 || len(opened) != 4 || len(slices.Compact(slices.Sorted(slices.Values(opened)))) != 4 || g.itemCount(8, 2021) != 0 {
|
||||
t.Fatalf("four-token maximum-open did not open and charge four cells: %x", response)
|
||||
}
|
||||
if !bytes.Equal(first, puzzleResponseState(t, response, 1)) || !slices.Equal(board, puzzleNumbers(t, after, 3)) {
|
||||
t.Fatal("maximum-open rearranged the current board or lost its before snapshot")
|
||||
}
|
||||
g.reopen()
|
||||
if !bytes.Equal(after, g.info(schedule.UID)) {
|
||||
t.Fatal("restart lost partial puzzle progress")
|
||||
}
|
||||
maximum.Identity.RequestID += "-reopened-domain-replay"
|
||||
if got := g.execute(maximum, false); !bytes.Equal(got, response) || g.itemCount(8, 2021) != 0 {
|
||||
t.Fatal("restart replay changed the response or charged twice")
|
||||
}
|
||||
g.grantTokens(400)
|
||||
beforeWordCurrency := g.wordCurrency()
|
||||
var completed []byte
|
||||
for id := uint64(1); id <= 7; id++ {
|
||||
if slices.Contains(opened, id) {
|
||||
continue
|
||||
}
|
||||
fields := append(slices.Clone(uid), appScalar(3, id)...)
|
||||
fields = append(fields, g.cost(4, 1)...)
|
||||
result := g.call("/MiniPuzzleOpen", fields)
|
||||
opened = puzzleNumbers(t, puzzleResponseState(t, result, 2), 4)
|
||||
if len(appRows(result, 5)) > 0 {
|
||||
completed = result
|
||||
}
|
||||
}
|
||||
puzzleWordReward(t, completed, 44, 0, 500)
|
||||
if g.wordCurrency() != beforeWordCurrency+500 {
|
||||
t.Fatal("word completion did not credit its currency to durable account state")
|
||||
}
|
||||
if len(opened) >= 25 {
|
||||
t.Fatal("word-only fixture unexpectedly opened the entire board")
|
||||
}
|
||||
tokens := g.itemCount(8, 2021)
|
||||
renewed := g.call("/MiniPuzzleRenew", uid)
|
||||
if appValue(puzzleResponseState(t, renewed, 1), 2) != 1 || appValue(puzzleResponseState(t, renewed, 2), 2) != 2 || len(puzzleNumbers(t, puzzleResponseState(t, renewed, 2), 4)) != 0 || g.itemCount(8, 2021) != tokens {
|
||||
t.Fatal("word-complete renewal did not abandon incidental cells without charging")
|
||||
}
|
||||
beforeMaterial := g.itemCount(8, 113)
|
||||
fullRequest := g.request("/MiniPuzzleAllOpen", append(slices.Clone(uid), g.cost(3, 25)...))
|
||||
full := g.execute(fullRequest, false)
|
||||
puzzleWordReward(t, full, 8, 113, 600)
|
||||
if appValue(puzzleResponseState(t, full, 1), 2) != 2 || appValue(puzzleResponseState(t, full, 2), 2) != 3 || g.itemCount(8, 2021) != tokens-25 || g.itemCount(8, 113) != beforeMaterial+600 {
|
||||
t.Fatal("full second board did not settle its word reward and automatically advance")
|
||||
}
|
||||
g.reopen()
|
||||
fullRequest.Identity.RequestID += "-domain-reward-replay"
|
||||
if replay := g.execute(fullRequest, false); !bytes.Equal(replay, full) || g.itemCount(8, 2021) != tokens-25 || g.itemCount(8, 113) != beforeMaterial+600 || g.wordCurrency() != beforeWordCurrency+500 {
|
||||
t.Fatal("full-board replay after restart duplicated a cost or reward")
|
||||
}
|
||||
for stage := uint64(3); stage <= 12; stage++ {
|
||||
beforeTickets := g.itemCount(8, 1000)
|
||||
full = g.call("/MiniPuzzleAllOpen", append(slices.Clone(uid), g.cost(3, 25)...))
|
||||
wantStage := min(stage+1, uint64(12))
|
||||
if appValue(puzzleResponseState(t, full, 1), 2) != stage || appValue(puzzleResponseState(t, full, 2), 2) != wantStage {
|
||||
t.Fatalf("stage %d did not advance correctly: %x", stage, full)
|
||||
}
|
||||
if stage == 7 {
|
||||
puzzleWordReward(t, full, 8, 1000, 10)
|
||||
if g.itemCount(8, 1000) != beforeTickets+10 {
|
||||
t.Fatal("stage-seven word tickets were not credited to inventory")
|
||||
}
|
||||
}
|
||||
}
|
||||
puzzleWordReward(t, full, 4, 0, 100000)
|
||||
final := g.info(schedule.UID)
|
||||
if appValue(final, 2) != 12 || len(puzzleNumbers(t, final, 4)) != 25 {
|
||||
t.Fatal("terminal puzzle did not retain all completed cells")
|
||||
}
|
||||
tokens = g.itemCount(8, 2021)
|
||||
g.execute(g.request("/MiniPuzzleRenew", uid), true)
|
||||
g.execute(g.request("/MiniPuzzleAllOpen", uid), true)
|
||||
if !bytes.Equal(final, g.info(schedule.UID)) || g.itemCount(8, 2021) != tokens {
|
||||
t.Fatal("terminal operations changed assets or advanced beyond the final stage")
|
||||
}
|
||||
g.reopen()
|
||||
if !bytes.Equal(final, g.info(schedule.UID)) || g.itemCount(8, 2021) != tokens {
|
||||
t.Fatal("terminal puzzle progress or token balance changed after reopening SQLite")
|
||||
}
|
||||
calendar := g.owner.assembly.eventRegistry.List()
|
||||
for index := range calendar {
|
||||
if calendar[index].UID == schedule.UID {
|
||||
calendar[index].End = time.Now().Add(-time.Minute).UnixMilli()
|
||||
}
|
||||
}
|
||||
if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(final, g.info(schedule.UID)) {
|
||||
t.Fatal("expired info query erased previously completed progress")
|
||||
}
|
||||
closed := g.execute(g.request("/MiniPuzzleRenew", uid), true)
|
||||
if !strings.Contains(string(closed), "event is closed") || g.itemCount(8, 2021) != tokens {
|
||||
t.Fatal("expired puzzle allowed mutation or charged resources")
|
||||
}
|
||||
}
|
||||
|
||||
// ResourceTable 2021's current stack limit is 9999. A real grant of 10001
|
||||
// creates two stacks; consuming 9997 leaves two tokens in each. The native
|
||||
// maximum-open request must sum both concrete stacks while each schedule
|
||||
// retains its own board and open-cell history.
|
||||
func TestPuzzleMaximumOpenUsesSplitStacksAndSeparateSchedules(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
calendar := owner.assembly.eventRegistry.List()
|
||||
var schedule events.Schedule
|
||||
for _, candidate := range calendar {
|
||||
if candidate.Type == 17 && candidate.ID == 10 {
|
||||
schedule = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if schedule.UID == 0 {
|
||||
t.Fatal("current puzzle schedule required")
|
||||
}
|
||||
second := schedule
|
||||
second.UID = 2000000010
|
||||
calendar = append(calendar, second)
|
||||
if err := owner.assembly.eventRegistry.Replace(calendar); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
uid := appScalar(2, schedule.UID)
|
||||
firstBoard, secondBoard := g.info(schedule.UID), g.info(second.UID)
|
||||
g.grantTokens(10001)
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := command.Context{State: tx}
|
||||
spent, err := owner.assembly.ownedItems.SelectMutable(ctx, 8, 2021, 9997)
|
||||
if err == nil {
|
||||
err = owner.assembly.ownedItems.Consume(ctx, spent)
|
||||
}
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cost := g.cost(3, 4)
|
||||
stacks := appRows(cost, 3)
|
||||
if len(stacks) != 2 || appValue(stacks[0], 4) != 2 || appValue(stacks[1], 4) != 2 {
|
||||
t.Fatalf("split-stack fixture is not two independent two-token entries: %x", cost)
|
||||
}
|
||||
duplicate := append(appMessage(3, stacks[0]), appMessage(3, stacks[0])...)
|
||||
g.execute(g.request("/MiniPuzzleAllOpen", append(slices.Clone(uid), duplicate...)), true)
|
||||
if !bytes.Equal(firstBoard, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 {
|
||||
t.Fatal("duplicate submitted stack changed progress or token balance")
|
||||
}
|
||||
// A failed request rebuilds the production assembly from SQLite and its
|
||||
// configured calendar; reinstall only the second test schedule afterward.
|
||||
if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := g.call("/MiniPuzzleAllOpen", append(slices.Clone(uid), cost...))
|
||||
if len(puzzleNumbers(t, puzzleResponseState(t, result, 2), 4)) != 4 || g.itemCount(8, 2021) != 0 || !bytes.Equal(secondBoard, g.info(second.UID)) {
|
||||
t.Fatal("maximum-open did not consume both stacks or mixed the two schedule states")
|
||||
}
|
||||
firstAfter := g.info(schedule.UID)
|
||||
g.grantTokens(1)
|
||||
board := puzzleNumbers(t, secondBoard, 3)
|
||||
fields := append(appScalar(2, second.UID), appScalar(3, board[0])...)
|
||||
fields = append(fields, g.cost(4, 1)...)
|
||||
result = g.call("/MiniPuzzleOpen", fields)
|
||||
if len(puzzleNumbers(t, puzzleResponseState(t, result, 2), 4)) != 1 || !bytes.Equal(firstAfter, g.info(schedule.UID)) || g.itemCount(8, 2021) != 0 {
|
||||
t.Fatal("single-open used another schedule's cells or did not charge its token")
|
||||
}
|
||||
g.reopen()
|
||||
if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(firstAfter, g.info(schedule.UID)) || len(puzzleNumbers(t, g.info(second.UID), 4)) != 1 {
|
||||
t.Fatal("SQLite restart merged independent puzzle schedule progress")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
chatpolicy "bd2server/internal/server/domain/chat"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
type guildChatRecord struct {
|
||||
Owner uint64
|
||||
AtMS int64
|
||||
Body []byte
|
||||
}
|
||||
type guildChatReceipt struct{ Digest string }
|
||||
|
||||
// The native Chat connection also carries matchmaking packets.
|
||||
type realtimeChat struct {
|
||||
rooms interface {
|
||||
Handle(context.Context, room.Connection, room.Frame) ([]room.Delivery, error)
|
||||
Disconnect(context.Context, room.Connection) ([]room.Delivery, error)
|
||||
}
|
||||
shared *sharedRuntime
|
||||
rules room.TextRules
|
||||
historyCount int
|
||||
historyAge time.Duration
|
||||
emojis map[uint64]bool
|
||||
now func() time.Time
|
||||
mu sync.Mutex
|
||||
connections map[string]room.Connection
|
||||
}
|
||||
|
||||
func chatJSON(tx *shared.Tx, bucket, key string, value any) (bool, error) {
|
||||
raw, found, err := tx.Get(bucket, key)
|
||||
if err != nil || !found {
|
||||
return found, err
|
||||
}
|
||||
return true, json.Unmarshal(raw, value)
|
||||
}
|
||||
func putChatJSON(tx *shared.Tx, bucket, key string, value any) error {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Put(bucket, key, raw)
|
||||
}
|
||||
func chatScalar(raw []byte, n int) uint64 { v, _, _ := wire.Varint(raw, n); return v }
|
||||
func chatBytes(raw []byte, n int) []byte { v, _, _ := wire.Bytes(raw, n); return v }
|
||||
func chatPolicy(tx *shared.Tx, account string) (chatpolicy.Policy, error) {
|
||||
var p chatpolicy.Policy
|
||||
_, err := chatJSON(tx, "chat.policy", account, &p)
|
||||
return p, err
|
||||
}
|
||||
|
||||
func canonicalChatUser(tx *shared.Tx, p room.Principal, language uint64) ([]byte, uint64, error) {
|
||||
var published social.FriendProfile
|
||||
found, err := chatJSON(tx, "friend.directory", fmt.Sprintf("%020d", p.OwnerIndex), &published)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if found && published.AccountID != p.AccountID {
|
||||
return nil, 0, room.ErrUnauthorized
|
||||
}
|
||||
var account social.Account
|
||||
if _, err := chatJSON(tx, "social.accounts", p.AccountID, &account); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
guildID := account.GuildID
|
||||
if guildID != 0 {
|
||||
var guild social.Guild
|
||||
found, err := chatJSON(tx, "social.guilds", fmt.Sprintf("%020d", guildID), &guild)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
member, ok := guild.Members[p.AccountID]
|
||||
if !found || !ok || member.OwnerIndex != uint64(p.OwnerIndex) {
|
||||
return nil, 0, room.ErrUnauthorized
|
||||
}
|
||||
if published.AccountID == "" {
|
||||
published.Snapshot.UserID = member.Name
|
||||
published.Snapshot.PortraitCostumeID = member.PortraitID
|
||||
published.Snapshot.PortraitDesignID = member.PortraitDesignID
|
||||
published.Snapshot.TitleID = member.TitleID
|
||||
}
|
||||
}
|
||||
u := wire.AppendVarint(nil, 1, uint64(p.OwnerIndex))
|
||||
u = wire.AppendVarint(u, 2, guildID)
|
||||
u = wire.AppendString(u, 4, published.Snapshot.UserID)
|
||||
u = wire.AppendVarint(u, 5, published.Snapshot.PortraitCostumeID)
|
||||
u = wire.AppendVarint(u, 6, published.Snapshot.PortraitDesignID)
|
||||
u = wire.AppendVarint(u, 7, published.Snapshot.TitleID)
|
||||
return wire.AppendVarint(u, 10, language), guildID, nil
|
||||
}
|
||||
func chatMessage(now time.Time, user []byte, code uint64, body []byte) []byte {
|
||||
h := wire.AppendVarint(nil, 1, uint64(now.Unix()))
|
||||
h = wire.AppendVarint(h, 2, code)
|
||||
h = wire.AppendBytes(h, 3, user)
|
||||
return append(wire.AppendBytes(nil, 1, h), body...)
|
||||
}
|
||||
func chatReply(c room.Connection, f room.Frame, now time.Time, user []byte, code uint64, body []byte) room.Delivery {
|
||||
return room.Delivery{ConnectionID: c.ID, Frame: room.Frame{Type: f.Type + 1, Sequence: f.Sequence, OwnerIndex: c.Principal.OwnerIndex, Payload: chatMessage(now, user, code, body)}}
|
||||
}
|
||||
func (r *realtimeChat) Handle(ctx context.Context, c room.Connection, f room.Frame) ([]room.Delivery, error) {
|
||||
if c.Channel != room.Matching && f.Type != 1 && f.Type != 5 && f.Type != 11 {
|
||||
return r.rooms.Handle(ctx, c, f)
|
||||
}
|
||||
switch f.Type {
|
||||
case 1, 5, 11, 13, 15, 18, 10, 180, 188:
|
||||
default:
|
||||
return r.rooms.Handle(ctx, c, f)
|
||||
}
|
||||
if f.UDP || f.OwnerIndex != 0 && f.OwnerIndex != c.Principal.OwnerIndex {
|
||||
return nil, room.ErrUnauthorized
|
||||
}
|
||||
if err := wire.Walk(f.Payload, func(wire.Field) error { return nil }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clientUser := chatBytes(chatBytes(f.Payload, 1), 3)
|
||||
if owner := chatScalar(clientUser, 1); owner != 0 && owner != uint64(c.Principal.OwnerIndex) {
|
||||
return nil, room.ErrUnauthorized
|
||||
}
|
||||
if f.Type == 10 || f.Type == 18 {
|
||||
return nil, nil
|
||||
}
|
||||
if f.Type == 15 {
|
||||
code := uint64(0)
|
||||
if err := r.validateGuildPayload(ctx, c, f.Payload); err != nil {
|
||||
code = 2
|
||||
}
|
||||
if f.Sequence <= 0 {
|
||||
code = 2
|
||||
}
|
||||
if code != 0 {
|
||||
return []room.Delivery{chatReply(c, f, r.now(), wire.AppendVarint(nil, 1, uint64(c.Principal.OwnerIndex)), code, nil)}, nil
|
||||
}
|
||||
}
|
||||
now := r.now()
|
||||
var deliveries []room.Delivery
|
||||
transact := r.shared.store.View
|
||||
if f.Type == 15 {
|
||||
transact = r.shared.store.Update
|
||||
}
|
||||
err := transact(ctx, func(tx *shared.Tx) error {
|
||||
user, guildID, err := canonicalChatUser(tx, c.Principal, chatScalar(clientUser, 10))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if f.Type == 1 || f.Type == 5 || f.Type == 11 || f.Type == 180 {
|
||||
deliveries = append(deliveries, chatReply(c, f, now, user, 0, nil))
|
||||
return nil
|
||||
}
|
||||
if f.Type == 188 {
|
||||
sender := chatScalar(f.Payload, 2)
|
||||
at := chatScalar(f.Payload, 4)
|
||||
translationUser := wire.AppendVarint(nil, 1, sender)
|
||||
body := wire.AppendString(nil, 2, string(chatBytes(f.Payload, 3)))
|
||||
body = wire.AppendVarint(body, 3, at)
|
||||
deliveries = append(deliveries, chatReply(c, f, now, translationUser, 17, body))
|
||||
return nil
|
||||
}
|
||||
if guildID == 0 {
|
||||
deliveries = append(deliveries, chatReply(c, f, now, user, 3, nil))
|
||||
return nil
|
||||
}
|
||||
policy, err := chatPolicy(tx, c.Principal.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key := fmt.Sprintf("%020d", guildID)
|
||||
var history []guildChatRecord
|
||||
if _, err := chatJSON(tx, "chat.guild_history", key, &history); err != nil {
|
||||
return err
|
||||
}
|
||||
live := history[:0]
|
||||
for _, record := range history {
|
||||
if now.UnixMilli()-record.AtMS < int64(r.historyAge/time.Millisecond) {
|
||||
live = append(live, record)
|
||||
}
|
||||
}
|
||||
history = live
|
||||
if f.Type == 13 {
|
||||
var body []byte
|
||||
for _, record := range history {
|
||||
if !slices.Contains(policy.Blocked, record.Owner) {
|
||||
body = wire.AppendBytes(body, 2, record.Body)
|
||||
}
|
||||
}
|
||||
deliveries = append(deliveries, chatReply(c, f, now, user, 0, body))
|
||||
return nil
|
||||
}
|
||||
if policy.PenaltyUntilMS > now.UnixMilli() {
|
||||
deliveries = append(deliveries, chatReply(c, f, now, user, 2, nil))
|
||||
return nil
|
||||
}
|
||||
idRaw := sha256.Sum256([]byte(c.Principal.AccountID + "\x00" + c.Principal.SessionID + "\x00" + fmt.Sprint(f.Sequence)))
|
||||
id := hex.EncodeToString(idRaw[:])
|
||||
digestRaw := sha256.Sum256(f.Payload)
|
||||
digest := hex.EncodeToString(digestRaw[:])
|
||||
var receipt guildChatReceipt
|
||||
found, err := chatJSON(tx, "chat.guild_receipts", id, &receipt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
code := uint64(0)
|
||||
if receipt.Digest != digest {
|
||||
code = 2
|
||||
}
|
||||
deliveries = append(deliveries, chatReply(c, f, now, user, code, nil))
|
||||
return nil
|
||||
}
|
||||
at := now.UnixMilli()
|
||||
if len(history) > 0 && at <= history[len(history)-1].AtMS {
|
||||
at = history[len(history)-1].AtMS + 1
|
||||
}
|
||||
body := wire.AppendVarint(nil, 2, chatScalar(f.Payload, 2))
|
||||
field := 3 + int(chatScalar(f.Payload, 2))
|
||||
body = wire.AppendBytes(body, field, chatBytes(f.Payload, field))
|
||||
body = wire.AppendVarint(body, 7, uint64(at))
|
||||
packet := chatMessage(now, user, 0, body)
|
||||
history = append(history, guildChatRecord{Owner: uint64(c.Principal.OwnerIndex), AtMS: at, Body: packet})
|
||||
if len(history) > r.historyCount {
|
||||
history = history[len(history)-r.historyCount:]
|
||||
}
|
||||
if err := putChatJSON(tx, "chat.guild_history", key, history); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := putChatJSON(tx, "chat.guild_receipts", id, guildChatReceipt{Digest: digest}); err != nil {
|
||||
return err
|
||||
}
|
||||
deliveries = append(deliveries, chatReply(c, f, now, user, 0, nil))
|
||||
var guild social.Guild
|
||||
if _, err := chatJSON(tx, "social.guilds", key, &guild); err != nil {
|
||||
return err
|
||||
}
|
||||
var recipients []room.Connection
|
||||
r.mu.Lock()
|
||||
for account := range guild.Members {
|
||||
if recipient, found := r.connections[account]; found {
|
||||
recipients = append(recipients, recipient)
|
||||
}
|
||||
}
|
||||
r.mu.Unlock()
|
||||
for _, recipient := range recipients {
|
||||
_, recipientGuild, err := canonicalChatUser(tx, recipient.Principal, 0)
|
||||
if errors.Is(err, room.ErrUnauthorized) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if recipientGuild != guildID {
|
||||
continue
|
||||
}
|
||||
recipientPolicy, err := chatPolicy(tx, recipient.Principal.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if slices.Contains(recipientPolicy.Blocked, uint64(c.Principal.OwnerIndex)) {
|
||||
continue
|
||||
}
|
||||
deliveries = append(deliveries, room.Delivery{ConnectionID: recipient.ID, Frame: room.Frame{Type: 17, OwnerIndex: c.Principal.OwnerIndex, Payload: packet}})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err == nil && f.Type == 11 && c.Channel == room.Matching {
|
||||
r.mu.Lock()
|
||||
if r.connections == nil {
|
||||
r.connections = map[string]room.Connection{}
|
||||
}
|
||||
r.connections[c.Principal.AccountID] = c
|
||||
r.mu.Unlock()
|
||||
}
|
||||
return deliveries, err
|
||||
}
|
||||
func (r *realtimeChat) validateGuildPayload(ctx context.Context, c room.Connection, raw []byte) error {
|
||||
if len(raw) > 128000 || c.Principal.OwnerIndex <= 0 {
|
||||
return room.ErrUnauthorized
|
||||
}
|
||||
typ := chatScalar(raw, 2)
|
||||
if typ > 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
for field := 3; field <= 6; field++ {
|
||||
if field != 3+int(typ) && len(chatBytes(raw, field)) != 0 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
}
|
||||
value := chatBytes(raw, 3+int(typ))
|
||||
if len(value) == 0 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
if err := wire.Walk(value, func(wire.Field) error { return nil }); err != nil {
|
||||
return err
|
||||
}
|
||||
if typ == 0 {
|
||||
text := string(chatBytes(value, 1))
|
||||
if !utf8.ValidString(text) || strings.TrimSpace(text) == "" || utf8.RuneCountInString(text) > 100 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
return r.rules.CheckRoomText(ctx, c.Principal, text)
|
||||
}
|
||||
if typ == 1 && !r.emojis[chatScalar(value, 1)] {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
if typ == 2 {
|
||||
name := string(chatBytes(value, 2))
|
||||
if !utf8.ValidString(name) || utf8.RuneCountInString(name) > 100 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
if err := wire.Walk(value, func(f wire.Field) error {
|
||||
if f.Number == 1 {
|
||||
_, characterPresent, characterErr := wire.Bytes(f.Value, 1)
|
||||
if f.Type != 2 || !characterPresent || characterErr != nil {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
return wire.Walk(f.Value, func(nested wire.Field) error {
|
||||
if nested.Number >= 1 && nested.Number <= 4 {
|
||||
if nested.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
return wire.Walk(nested.Value, func(wire.Field) error { return nil })
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if name != "" {
|
||||
return r.rules.CheckRoomText(ctx, c.Principal, name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (r *realtimeChat) Disconnect(ctx context.Context, c room.Connection) ([]room.Delivery, error) {
|
||||
r.mu.Lock()
|
||||
if current := r.connections[c.Principal.AccountID]; current.ID == c.ID {
|
||||
delete(r.connections, c.Principal.AccountID)
|
||||
}
|
||||
r.mu.Unlock()
|
||||
return r.rooms.Disconnect(ctx, c)
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) consumeChatPolicy(ctx context.Context, source string, raw []byte) error {
|
||||
var p chatpolicy.Policy
|
||||
if err := json.Unmarshal(raw, &p); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.AccountID != source || p.OwnerIndex == 0 || p.Version == 0 {
|
||||
return social.ErrPermission
|
||||
}
|
||||
return s.store.Update(ctx, func(tx *shared.Tx) error {
|
||||
old, err := chatPolicy(tx, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if old.Version >= p.Version {
|
||||
return nil
|
||||
}
|
||||
return putChatJSON(tx, "chat.policy", source, p)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
chatpolicy "bd2server/internal/server/domain/chat"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/gateway/realtime"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
type chatTestRooms struct{ calls int }
|
||||
|
||||
func (r *chatTestRooms) Handle(context.Context, room.Connection, room.Frame) ([]room.Delivery, error) {
|
||||
r.calls++
|
||||
return nil, nil
|
||||
}
|
||||
func (*chatTestRooms) Disconnect(context.Context, room.Connection) ([]room.Delivery, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type chatTestText struct{}
|
||||
|
||||
func (chatTestText) CheckRoomText(_ context.Context, _ room.Principal, text string) error {
|
||||
if text == "rejected" {
|
||||
return room.ErrTextRejected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newChatTest(t *testing.T) (*realtimeChat, []room.Connection, *time.Time) {
|
||||
t.Helper()
|
||||
store, err := shared.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
now := time.Date(2026, 10, 11, 1, 0, 0, 0, time.UTC)
|
||||
r := &realtimeChat{shared: &sharedRuntime{store: store}, rooms: &chatTestRooms{}, rules: chatTestText{}, historyCount: 2, historyAge: time.Hour, emojis: map[uint64]bool{1: true}, now: func() time.Time { return now }}
|
||||
var clients []room.Connection
|
||||
for i := 1; i <= 4; i++ {
|
||||
clients = append(clients, room.Connection{ID: fmt.Sprint(i), Channel: room.Matching, Principal: room.Principal{AccountID: fmt.Sprint(i), OwnerIndex: int64(i), SessionID: "session", Generation: 1}})
|
||||
}
|
||||
err = store.Update(context.Background(), func(tx *shared.Tx) error {
|
||||
g1 := social.Guild{ID: 1, Members: map[string]social.Membership{}, Reserved: map[string]bool{}}
|
||||
g2 := social.Guild{ID: 2, Members: map[string]social.Membership{}, Reserved: map[string]bool{}}
|
||||
for _, c := range clients {
|
||||
id := uint64(1)
|
||||
if c.ID == "4" {
|
||||
id = 2
|
||||
}
|
||||
member := social.Membership{PublicMember: social.PublicMember{AccountID: c.Principal.AccountID, OwnerIndex: uint64(c.Principal.OwnerIndex), Name: "canonical-" + c.ID}}
|
||||
if id == 1 {
|
||||
g1.Members[c.Principal.AccountID] = member
|
||||
} else {
|
||||
g2.Members[c.Principal.AccountID] = member
|
||||
}
|
||||
if err := putChatJSON(tx, "social.accounts", c.Principal.AccountID, social.Account{GuildID: id}); err != nil {
|
||||
return err
|
||||
}
|
||||
p := social.FriendProfile{AccountID: c.Principal.AccountID, OwnerIndex: uint64(c.Principal.OwnerIndex), Version: 1, Snapshot: profile.Snapshot{OwnerIndex: uint64(c.Principal.OwnerIndex), UserID: member.Name, PortraitCostumeID: 42}}
|
||||
if err := putChatJSON(tx, "friend.directory", fmt.Sprintf("%020d", c.Principal.OwnerIndex), p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := putChatJSON(tx, "social.guilds", fmt.Sprintf("%020d", 1), g1); err != nil {
|
||||
return err
|
||||
}
|
||||
return putChatJSON(tx, "social.guilds", fmt.Sprintf("%020d", 2), g2)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r, clients, &now
|
||||
}
|
||||
func chatTestFrame(c room.Connection, typ, seq int32, body []byte) room.Frame {
|
||||
u := wire.AppendVarint(nil, 1, uint64(c.Principal.OwnerIndex))
|
||||
u = wire.AppendVarint(u, 2, 999)
|
||||
u = wire.AppendString(u, 4, "forged")
|
||||
h := wire.AppendBytes(nil, 3, u)
|
||||
return room.Frame{Type: typ, Sequence: seq, OwnerIndex: c.Principal.OwnerIndex, Payload: append(wire.AppendBytes(nil, 1, h), body...)}
|
||||
}
|
||||
func chatTestHandle(t *testing.T, r *realtimeChat, c room.Connection, f room.Frame) []room.Delivery {
|
||||
t.Helper()
|
||||
d, err := r.Handle(context.Background(), c, f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return d
|
||||
}
|
||||
func chatHistoryRows(raw []byte) [][]byte {
|
||||
var rows [][]byte
|
||||
_ = wire.Walk(raw, func(f wire.Field) error {
|
||||
if f.Number == 2 {
|
||||
rows = append(rows, f.Value)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return rows
|
||||
}
|
||||
|
||||
// Packet numbers and field layouts are from 2.36.7 Network/TCP ENetMsg,
|
||||
// CommonHeader, CSGuildMessageLoadResponse and SCGuildBroadcastRequest.
|
||||
func TestNativeGuildChatCanonicalHandshakeAudienceAndBlockHistory(t *testing.T) {
|
||||
r, clients, _ := newChatTest(t)
|
||||
for _, c := range clients {
|
||||
d := chatTestHandle(t, r, c, chatTestFrame(c, 11, 1, nil))
|
||||
u := chatBytes(chatBytes(d[0].Frame.Payload, 1), 3)
|
||||
guild := uint64(1)
|
||||
if c.ID == "4" {
|
||||
guild = 2
|
||||
}
|
||||
if d[0].Frame.Type != 12 || string(chatBytes(u, 4)) != "canonical-"+c.ID || chatScalar(u, 2) != guild {
|
||||
t.Fatal("handshake trusted forged profile or omitted required UserInfo")
|
||||
}
|
||||
}
|
||||
policy := chatpolicy.Policy{AccountID: "2", OwnerIndex: 2, Version: 2, Blocked: []uint64{1}}
|
||||
if err := r.shared.store.Update(context.Background(), func(tx *shared.Tx) error { return putChatJSON(tx, "chat.policy", "2", policy) }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := wire.AppendBytes(nil, 3, wire.AppendString(nil, 1, "hello"))
|
||||
d := chatTestHandle(t, r, clients[0], chatTestFrame(clients[0], 15, 2, body))
|
||||
got := map[string]bool{}
|
||||
for _, delivery := range d {
|
||||
if delivery.Frame.Type == 17 {
|
||||
got[delivery.ConnectionID] = true
|
||||
u := chatBytes(chatBytes(delivery.Frame.Payload, 1), 3)
|
||||
if string(chatBytes(u, 4)) != "canonical-1" {
|
||||
t.Fatal("broadcast trusted client name")
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(got) != 2 || !got["1"] || !got["3"] {
|
||||
t.Fatalf("guild/block audience = %v", got)
|
||||
}
|
||||
for _, i := range []int{1, 2, 3} {
|
||||
loaded := chatTestHandle(t, r, clients[i], chatTestFrame(clients[i], 13, 3, nil))
|
||||
rows := chatHistoryRows(loaded[0].Frame.Payload)
|
||||
want := 0
|
||||
if i == 2 {
|
||||
want = 1
|
||||
}
|
||||
if len(rows) != want {
|
||||
t.Fatalf("client %s history=%d want%d", clients[i].ID, len(rows), want)
|
||||
}
|
||||
}
|
||||
if _, err := r.Handle(context.Background(), clients[0], room.Frame{Type: 78}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.rooms.(*chatTestRooms).calls != 1 {
|
||||
t.Fatal("matchmaking did not reach existing room handler")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeGuildChatReplayReconnectMembershipAndRetention(t *testing.T) {
|
||||
r, clients, now := newChatTest(t)
|
||||
for _, c := range clients {
|
||||
chatTestHandle(t, r, c, chatTestFrame(c, 11, 1, nil))
|
||||
}
|
||||
body := wire.AppendVarint(nil, 2, 1)
|
||||
body = wire.AppendBytes(body, 4, wire.AppendVarint(nil, 1, 1))
|
||||
f := chatTestFrame(clients[0], 15, 2, body)
|
||||
chatTestHandle(t, r, clients[0], f)
|
||||
reconnected := clients[0]
|
||||
reconnected.ID = "new"
|
||||
chatTestHandle(t, r, reconnected, chatTestFrame(reconnected, 11, 3, nil))
|
||||
if _, err := r.Disconnect(context.Background(), clients[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay := chatTestHandle(t, r, reconnected, f)
|
||||
if len(replay) != 1 || replay[0].Frame.Type != 16 {
|
||||
t.Fatal("replay rebroadcast durable message")
|
||||
}
|
||||
if err := r.shared.store.Update(context.Background(), func(tx *shared.Tx) error {
|
||||
var g social.Guild
|
||||
if _, err := chatJSON(tx, "social.guilds", fmt.Sprintf("%020d", 1), &g); err != nil {
|
||||
return err
|
||||
}
|
||||
delete(g.Members, "3")
|
||||
if err := putChatJSON(tx, "social.guilds", fmt.Sprintf("%020d", 1), g); err != nil {
|
||||
return err
|
||||
}
|
||||
return putChatJSON(tx, "social.accounts", "3", social.Account{})
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for seq := int32(4); seq <= 5; seq++ {
|
||||
d := chatTestHandle(t, r, reconnected, chatTestFrame(reconnected, 15, seq, body))
|
||||
for _, delivery := range d {
|
||||
if delivery.Frame.Type == 17 && delivery.ConnectionID == "3" {
|
||||
t.Fatal("removed member received guild chat")
|
||||
}
|
||||
}
|
||||
}
|
||||
loaded := chatTestHandle(t, r, reconnected, chatTestFrame(reconnected, 13, 6, nil))
|
||||
rows := chatHistoryRows(loaded[0].Frame.Payload)
|
||||
if len(rows) != 2 || chatScalar(rows[0], 7) >= chatScalar(rows[1], 7) {
|
||||
t.Fatal("history not bounded or native millisecond message timestamps collide")
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
loaded = chatTestHandle(t, r, reconnected, chatTestFrame(reconnected, 13, 7, nil))
|
||||
if len(chatHistoryRows(loaded[0].Frame.Payload)) != 0 {
|
||||
t.Fatal("expired history returned")
|
||||
}
|
||||
denied := chatTestHandle(t, r, clients[2], chatTestFrame(clients[2], 15, 8, body))
|
||||
if len(denied) != 1 || chatScalar(chatBytes(denied[0].Frame.Payload, 1), 2) != 3 {
|
||||
t.Fatal("removed member could send")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeGuildChatRejectsTextAndMalformedNamedDeckWithoutDisconnect(t *testing.T) {
|
||||
r, clients, _ := newChatTest(t)
|
||||
c := clients[0]
|
||||
chatTestHandle(t, r, c, chatTestFrame(c, 11, 1, nil))
|
||||
for i, body := range [][]byte{wire.AppendBytes(nil, 3, wire.AppendString(nil, 1, "rejected")), append(wire.AppendVarint(nil, 2, 2), wire.AppendBytes(nil, 5, wire.AppendBytes(wire.AppendString(nil, 2, "named"), 1, nil))...)} {
|
||||
d := chatTestHandle(t, r, c, chatTestFrame(c, 15, int32(i+2), body))
|
||||
if len(d) != 1 || chatScalar(chatBytes(d[0].Frame.Payload, 1), 2) != 2 {
|
||||
t.Fatal("rejected text or null deck character broadcast")
|
||||
}
|
||||
}
|
||||
ping := chatTestHandle(t, r, c, chatTestFrame(c, 1, 5, nil))
|
||||
if ping[0].Frame.Type != 2 {
|
||||
t.Fatal("invalid chat closed healthy socket")
|
||||
}
|
||||
}
|
||||
|
||||
type chatSocketTickets struct{ principal room.Principal }
|
||||
|
||||
func (t chatSocketTickets) Consume(context.Context, string, string, string) (room.Principal, func(), error) {
|
||||
return t.principal, func() {}, nil
|
||||
}
|
||||
func (chatSocketTickets) Validate(context.Context, room.Principal) error { return nil }
|
||||
|
||||
func TestNativeGuildChatSocketHandshakeAndIdleHeartbeatsStayConnected(t *testing.T) {
|
||||
r, clients, _ := newChatTest(t)
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address := listener.Addr().String()
|
||||
if err := listener.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
certFile, keyFile, pool := chatSocketCertificate(t)
|
||||
server, err := realtime.New(realtime.Config{TCPListen: address, TLSCertFile: certFile, TLSKeyFile: keyFile, IdleTimeout: time.Second}, r, chatSocketTickets{principal: clients[0].Principal})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- server.Serve(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
if err := server.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
var socket net.Conn
|
||||
for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); {
|
||||
socket, err = tls.DialWithDialer(&net.Dialer{Timeout: 100 * time.Millisecond}, "tcp", address, &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12})
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := socket.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
if err := socket.SetDeadline(time.Now().Add(6 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
auth, err := json.Marshal(realtime.AuthRequest{Ticket: "test-ticket", Channel: "matching", InstanceID: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
header := append([]byte(realtime.AuthMagic), 0, 0)
|
||||
binary.LittleEndian.PutUint16(header[8:], uint16(len(auth)))
|
||||
if _, err := socket.Write(append(header, auth...)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ack [10]byte
|
||||
if _, err := io.ReadFull(socket, ack[:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(ack[:8]) != realtime.AckMagic {
|
||||
t.Fatal("authenticated transport handshake failed")
|
||||
}
|
||||
ackBody := make([]byte, binary.LittleEndian.Uint16(ack[8:]))
|
||||
if _, err := io.ReadFull(socket, ackBody); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := chatTestFrame(clients[0], 11, 1, nil)
|
||||
if _, err := socket.Write(realtime.EncodeFrame(f)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response, err := realtime.ReadFrame(socket, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := chatBytes(chatBytes(response.Payload, 1), 3)
|
||||
if response.Type != 12 || chatScalar(user, 1) != 1 || string(chatBytes(user, 4)) != "canonical-1" {
|
||||
t.Fatal("native login response omitted canonical UserInfo")
|
||||
}
|
||||
for sequence := int32(2); sequence < 14; sequence++ {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if _, err := socket.Write(realtime.EncodeFrame(chatTestFrame(clients[0], 1, sequence, nil))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response, err := realtime.ReadFrame(socket, 4096)
|
||||
if err != nil {
|
||||
t.Fatalf("healthy heartbeat connection dropped: %v", err)
|
||||
}
|
||||
if response.Type != 2 || response.Sequence != sequence || chatScalar(chatBytes(response.Payload, 1), 2) != 0 {
|
||||
t.Fatal("native heartbeat response invalid")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func chatSocketCertificate(t *testing.T) (string, string, *x509.CertPool) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cert := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
|
||||
der, err := x509.CreateCertificate(rand.Reader, cert, cert, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyDER, err := x509.MarshalECPrivateKey(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
|
||||
dir := t.TempDir()
|
||||
certPath, keyPath := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")
|
||||
if err := os.WriteFile(certPath, certPEM, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, keyPEM, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(certPEM) {
|
||||
t.Fatal("test trust root invalid")
|
||||
}
|
||||
return certPath, keyPath, pool
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/fishing"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
)
|
||||
|
||||
func (r *roomResults) FishingRooms(command.Context) ([]fishing.RoomInfo, error) {
|
||||
if r.rooms == nil {
|
||||
return nil, room.ErrClosed
|
||||
}
|
||||
views := r.rooms.FishingRooms()
|
||||
result := make([]fishing.RoomInfo, 0, len(views))
|
||||
for _, view := range views {
|
||||
result = append(result, fishing.RoomInfo{Code: view.RoomCode, MapID: uint64(view.Selection.MapID), BoatLevel: uint64(view.Selection.BoatLevel), Members: uint64(len(view.Members))})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *roomResults) updateFishing(ctx context.Context, event outbox.Pending) error {
|
||||
var projection fishing.Projection
|
||||
if err := json.Unmarshal(event.Envelope.Event.Payload, &projection); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.rooms == nil || projection.InstanceID == "" {
|
||||
return nil
|
||||
}
|
||||
view, err := r.rooms.SnapshotForSession(event.Envelope.Source, projection.SessionID, room.Fishing)
|
||||
if errors.Is(err, room.ErrNotFound) || errors.Is(err, room.ErrUnauthorized) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if view.InstanceID != projection.InstanceID {
|
||||
return nil
|
||||
}
|
||||
for _, member := range view.Members {
|
||||
if member.Principal.AccountID != event.Envelope.Source {
|
||||
continue
|
||||
}
|
||||
profile := member.Profile
|
||||
profile.RodID = int64(projection.Profile.RodID)
|
||||
profile.BoatLevel = int64(projection.Profile.BoatLevel)
|
||||
profile.BoatSkinID = int64(projection.Profile.BoatSkinID)
|
||||
profile.FishingMaps = projection.Profile.Maps
|
||||
var buffs [][]byte
|
||||
for _, buff := range projection.Buffs {
|
||||
raw := wire.AppendVarint(nil, 1, buff.ID)
|
||||
raw = wire.AppendVarint(raw, 2, uint64(buff.End))
|
||||
buffs = append(buffs, raw)
|
||||
}
|
||||
deliveries, err := r.rooms.UpdateFishingProjection(ctx, member.Principal, profile, buffs, int64(projection.ItemID), event.Envelope.Event.ID)
|
||||
if errors.Is(err, room.ErrNotFound) || errors.Is(err, room.ErrNotReady) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.deliver != nil {
|
||||
r.deliver(deliveries)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,831 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gameconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
eventplay "bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
func TestNativeRoomGameplayUsesRealDesignAndCommitsParticipantRewardsOnce(t *testing.T) {
|
||||
for _, family := range []string{"Action", "Defense"} {
|
||||
t.Run(family, func(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
catalog := factory.design.eventPlay
|
||||
kind := uint64(8)
|
||||
if family == "Defense" {
|
||||
kind = 7
|
||||
}
|
||||
var eventID uint64
|
||||
for _, row := range catalog.Tables["PackEventMiniGameTable"] {
|
||||
if appValue(row, 3) == kind {
|
||||
eventID = appValue(row, 8)
|
||||
break
|
||||
}
|
||||
}
|
||||
if eventID == 0 {
|
||||
t.Fatal("current GameData has no native family")
|
||||
}
|
||||
var selected gamedata.NativeMinigame
|
||||
var character uint64
|
||||
if family == "Defense" {
|
||||
var err error
|
||||
selected, err = catalog.NativeMinigameRules(family, eventID, 0, 0, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
for _, char := range catalog.Tables["ActionGameCharTable"] {
|
||||
for _, stage := range catalog.Tables["ActionGameStageTable"] {
|
||||
rules, err := catalog.NativeMinigameRules(family, eventID, appValue(char, 14), appValue(stage, 1), false)
|
||||
if err == nil {
|
||||
selected, character = rules, appValue(char, 14)
|
||||
break
|
||||
}
|
||||
}
|
||||
if character != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if character == 0 {
|
||||
t.Fatal("current GameData has no approved party action selection")
|
||||
}
|
||||
}
|
||||
// Only calendar dates are fixtures. All event, stage, monster and reward IDs come from installed GameData.
|
||||
now := time.Now()
|
||||
schedule := events.Schedule{UID: eventID, Type: 11, ID: eventID, Start: now.Add(-time.Hour).UnixMilli(), End: now.Add(time.Hour).UnixMilli()}
|
||||
factory.options.calendars.Events = []events.Schedule{schedule}
|
||||
state, err := openSharedRuntime(ctx, factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := state.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.shared, factory.pvpSource, factory.roomResults = state, state.pvp, state.rooms
|
||||
registry := newPlayerRegistry(factory, time.Hour)
|
||||
t.Cleanup(func() {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
clock := new(atomic.Int64)
|
||||
clock.Store(now.UnixNano())
|
||||
published := make(chan []room.Delivery, 8)
|
||||
manager, err := room.New(room.Config{AdvertisedHost: "127.0.0.1", TCPPort: 9000, Now: func() time.Time { return time.Unix(0, clock.Load()) }, PublishResult: state.rooms.publish, Publish: func(d []room.Delivery) { published <- d }}, roomRules{players: registry, shared: state})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := manager.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
state.rooms.rooms = manager
|
||||
var actors [2]*player.Runtime
|
||||
var clients [2]room.Connection
|
||||
var seq [2]uint64
|
||||
for i, account := range accounts {
|
||||
actor, release, err := registry.Acquire(ctx, account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(release)
|
||||
actors[i] = actor
|
||||
profile, err := factory.profiles.GameIdentity(ctx, account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clients[i] = room.Connection{ID: fmt.Sprintf("matching-%d", i), Channel: room.Matching, Principal: room.Principal{AccountID: account, OwnerIndex: profile.OwnerIndex, SessionID: "registry-client", Generation: actor.Generation()}}
|
||||
}
|
||||
call := func(i int, path string, fields []byte) (player.Command, player.Reply, error) {
|
||||
seq[i]++
|
||||
body := wire.AppendVarint(nil, 1, seq[i])
|
||||
body = append(body, fields...)
|
||||
cmd := registryCommand(accounts[i], fmt.Sprintf("native-%s-%d", path, seq[i]), path, body)
|
||||
future, err := actors[i].Submit(ctx, cmd)
|
||||
if err != nil {
|
||||
return cmd, player.Reply{}, err
|
||||
}
|
||||
reply, err := future.Wait(ctx)
|
||||
return cmd, reply, err
|
||||
}
|
||||
items := func(i int) map[[2]uint64]uint64 {
|
||||
t.Helper()
|
||||
_, reply, err := call(i, "/ItemInfo", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return appItemTotals(reply.Responses[0].Body)
|
||||
}
|
||||
drain := func(i int) {
|
||||
t.Helper()
|
||||
seq[i]++
|
||||
command := player.Command{Identity: command.Identity{AccountID: accounts[i], SessionID: "native-delivery", RequestID: fmt.Sprint(seq[i])}, System: &player.SystemRequest{Kind: player.ReadOutbox}}
|
||||
reply := registryExecute(t, actors[i], command)
|
||||
var pending []outbox.Pending
|
||||
if err := json.Unmarshal(reply.Responses[0].Body, &pending); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, event := range pending {
|
||||
if err := state.Consume(ctx, event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := json.Marshal(struct {
|
||||
Key string `json:"key"`
|
||||
Digest string `json:"digest"`
|
||||
}{event.Key, event.Digest})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seq[i]++
|
||||
command.Identity.RequestID = fmt.Sprint(seq[i])
|
||||
command.Digest = sha256.Sum256(raw)
|
||||
command.System = &player.SystemRequest{Kind: player.AcknowledgeOutbox, Body: raw}
|
||||
registryExecute(t, actors[i], command)
|
||||
}
|
||||
}
|
||||
handle := func(i int, typ int32, payload []byte) []room.Delivery {
|
||||
t.Helper()
|
||||
d, err := manager.Handle(ctx, clients[i], room.Frame{Type: typ, Payload: payload})
|
||||
if err != nil {
|
||||
t.Fatalf("native type %d: %v", typ, err)
|
||||
}
|
||||
return d
|
||||
}
|
||||
if family == "Action" {
|
||||
b := wire.AppendVarint(nil, 2, schedule.UID)
|
||||
b = wire.AppendVarint(b, 4, 2)
|
||||
b = wire.AppendVarint(b, 5, character)
|
||||
b = wire.AppendVarint(b, 6, selected.MonsterID)
|
||||
handle(0, 82, b)
|
||||
} else {
|
||||
handle(0, 76, wire.AppendVarint(wire.AppendVarint(nil, 2, schedule.UID), 3, 2))
|
||||
}
|
||||
view, err := manager.View(ctx, clients[0].Principal, room.Kind(bytes.ToLower([]byte(family))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if family == "Action" {
|
||||
handle(1, 90, wire.AppendVarint(wire.AppendString(nil, 2, view.RoomCode), 3, character))
|
||||
handle(0, 104, nil)
|
||||
} else {
|
||||
handle(1, 76, wire.AppendString(wire.AppendVarint(wire.AppendVarint(nil, 2, schedule.UID), 3, 3), 4, view.RoomCode))
|
||||
handle(0, 74, nil)
|
||||
}
|
||||
if uint64(view.Selection.GroupID) != selected.GroupID || uint64(view.Selection.StageID) != selected.StageID || view.Selection.Capacity != selected.Capacity {
|
||||
t.Fatalf("native room selection differs from GameData: %+v want %+v", view.Selection, selected)
|
||||
}
|
||||
var guids [2]string
|
||||
for i := range clients {
|
||||
clients[i].Channel = room.Kind(bytes.ToLower([]byte(family)))
|
||||
clients[i].ID = fmt.Sprintf("game-%d", i)
|
||||
d := handle(i, 23, wire.AppendString(nil, 2, view.RoomCode))
|
||||
guid, found, err := wire.Bytes(d[0].Frame.Payload, 4)
|
||||
if err != nil || !found {
|
||||
t.Fatal("native entry missing guid")
|
||||
}
|
||||
guids[i] = string(guid)
|
||||
handle(i, 45, wire.AppendString(nil, 2, guids[i]))
|
||||
}
|
||||
before := [2]map[[2]uint64]uint64{items(0), items(1)}
|
||||
for i := range clients {
|
||||
_, _, err := call(i, "/MiniGame"+family+"Start", wire.AppendVarint(nil, 2, schedule.UID))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
drain(i)
|
||||
}
|
||||
view, err = manager.View(ctx, clients[0].Principal, clients[0].Channel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range view.Members {
|
||||
if !m.AcceptedRun || m.RunGUID != m.NativeGUID {
|
||||
t.Fatal("player commit did not admit native room participant")
|
||||
}
|
||||
}
|
||||
endFields := func(i int) []byte {
|
||||
b := wire.AppendString(nil, 2, guids[i])
|
||||
if family == "Action" {
|
||||
b = wire.AppendVarint(b, 3, selected.GroupID)
|
||||
b = wire.AppendVarint(b, 4, selected.StageID)
|
||||
b = wire.AppendVarint(b, 6, selected.MonsterID)
|
||||
b = wire.AppendVarint(b, 7, 1)
|
||||
} else {
|
||||
b = wire.AppendVarint(b, 3, 1)
|
||||
}
|
||||
return b
|
||||
}
|
||||
if _, _, err := call(0, "/MiniGame"+family+"End", endFields(0)); !errors.Is(err, eventplay.ErrRoomNotFinished) {
|
||||
t.Fatalf("unfinished native room accepted HTTP completion: %v", err)
|
||||
}
|
||||
clock.Add(int64(5 * time.Second))
|
||||
if family == "Action" {
|
||||
monster := wire.AppendVarint(nil, 3, selected.MonsterID)
|
||||
if d := handle(0, 111, wire.AppendBytes(wire.AppendString(nil, 2, guids[0]), 5, monster)); len(d) != 0 {
|
||||
t.Fatal("terminal notification preceded durable persistence")
|
||||
}
|
||||
} else {
|
||||
for i := range clients {
|
||||
b := wire.AppendString(nil, 2, guids[i])
|
||||
b = wire.AppendVarint(b, 3, 5)
|
||||
b = wire.AppendVarint(b, 5, selected.LastWave)
|
||||
handle(i, 48, b)
|
||||
}
|
||||
}
|
||||
var final room.FinalResult
|
||||
select {
|
||||
case final = <-state.rooms.queue:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("native terminal result was not queued")
|
||||
}
|
||||
if !final.Clear || final.ScoreMilliseconds != 5000 || len(final.View.Members) != 2 {
|
||||
t.Fatalf("native terminal projection wrong: %+v", final)
|
||||
}
|
||||
if err := state.rooms.persist(ctx, final); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case frames := <-published:
|
||||
terminal := int32(108)
|
||||
if family == "Defense" {
|
||||
terminal = 51
|
||||
}
|
||||
count := 0
|
||||
for _, d := range frames {
|
||||
if d.Frame.Type == terminal {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count != 2 {
|
||||
t.Fatalf("durable ack released %d participant terminal frames", count)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("durable persistence did not release terminal frames")
|
||||
}
|
||||
wantRewards := map[[2]uint64]uint64{}
|
||||
if family == "Defense" {
|
||||
for _, row := range catalog.Tables["MGDRewardTable"] {
|
||||
if appValue(row, 6) <= selected.LastWave {
|
||||
rr, err := gamedata.EventPlayRewards(row, 5, 3, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, r := range rr {
|
||||
wantRewards[[2]uint64{r.Type, r.ID}] += r.Count
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(wantRewards) == 0 {
|
||||
t.Fatal("current Defense design has no terminal rewards")
|
||||
}
|
||||
}
|
||||
for i := range clients {
|
||||
otherBefore := items(1 - i)
|
||||
cmd, reply, err := call(i, "/MiniGame"+family+"End", endFields(i))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if family == "Action" && appValue(reply.Responses[0].Body, 1) != 5000 {
|
||||
t.Fatal("HTTP score overrode authoritative native completion")
|
||||
}
|
||||
got := items(i)
|
||||
want := make(map[[2]uint64]uint64, len(before[i])+len(wantRewards))
|
||||
maps.Copy(want, before[i])
|
||||
for key, n := range wantRewards {
|
||||
want[key] += n
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("participant%d assets differ from GameData rewards: got=%v want=%v", i, got, want)
|
||||
}
|
||||
if !reflect.DeepEqual(items(1-i), otherBefore) {
|
||||
t.Fatal("participant completion changed another player's assets")
|
||||
}
|
||||
replay := registryExecute(t, actors[i], cmd)
|
||||
if !bytes.Equal(replay.Responses[0].Body, reply.Responses[0].Body) || !reflect.DeepEqual(items(i), got) {
|
||||
t.Fatal("HTTP replay changed response or granted twice")
|
||||
}
|
||||
drain(i)
|
||||
if i == 0 {
|
||||
prepared, err := state.rooms.PrepareResults(ctx, accounts[1], []eventplay.NativeRun{{InstanceID: final.View.InstanceID, GUID: guids[1], Family: family}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := prepared.Result(command.Context{Identity: command.Identity{AccountID: accounts[1]}}, eventplay.NativeRun{InstanceID: final.View.InstanceID, GUID: guids[1], Family: family}); err != nil {
|
||||
t.Fatal("first claim removed second participant entitlement", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := state.store.View(ctx, func(tx *shared.Tx) error {
|
||||
_, found, err := tx.Get("room.results", final.View.InstanceID)
|
||||
if found {
|
||||
t.Error("all participant claims retained full result")
|
||||
}
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if family == "Action" {
|
||||
rows, err := state.rooms.NativeRankings(command.Context{Identity: command.Identity{AccountID: accounts[0]}}, schedule.UID, selected.MonsterID, 2)
|
||||
if err != nil || len(rows) != 1 || rows[0].Score != 5000 || len(rows[0].Members) != 2 {
|
||||
t.Fatalf("real room completion ranking=%+v err=%v", rows, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeFishingVoyageUsesRealBoatAndIndependentParticipantClaims(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
base := t.TempDir()
|
||||
policy := gameconfig.DefaultTextModeration()
|
||||
policy.RuleFiles = []string{moderationRulesFile(t, base, `{"rules":[{"text":"Blocked","match":"exact","scopes":["chat"]}]}`)}
|
||||
moderator, err := textmoderation.New(policy, base)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := moderator.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.options.textModerator = moderator
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
state, err := openSharedRuntime(ctx, factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := state.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.shared, factory.pvpSource, factory.roomResults = state, state.pvp, state.rooms
|
||||
var starterBoat, partyBoat uint64
|
||||
for _, row := range factory.design.eventPlay.Tables["FishingBoatTable"] {
|
||||
id := appValue(row, 8)
|
||||
if id > 0 && (starterBoat == 0 || id < starterBoat) {
|
||||
starterBoat = id
|
||||
}
|
||||
if appValue(row, 9) >= 2 && (partyBoat == 0 || id < partyBoat) {
|
||||
partyBoat = id
|
||||
}
|
||||
}
|
||||
if partyBoat == 0 {
|
||||
t.Fatal("current GameData has no two-person boat")
|
||||
}
|
||||
var budget []gamedata.Reward
|
||||
for id := starterBoat + 1; id <= partyBoat; id++ {
|
||||
row, err := factory.design.eventPlay.Row("FishingBoatTable", 8, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
budget = append(budget, gamedata.Reward{Type: appValue(row, 4), ID: appValue(row, 3), Count: appValue(row, 2)})
|
||||
}
|
||||
// Grant only the real upgrade costs; the host still purchases each boat through the player route.
|
||||
fixture, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err := fixture.repository.BeginCommand(ctx)
|
||||
if err != nil {
|
||||
_ = fixture.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fixture.assembly.eventEconomy.Apply(command.Context{Identity: command.Identity{AccountID: accounts[0]}, State: tx}, "native-fishing-upgrade-budget", nil, budget); err != nil {
|
||||
_ = tx.Rollback()
|
||||
_ = fixture.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
_ = fixture.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fixture.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := newPlayerRegistry(factory, time.Hour)
|
||||
t.Cleanup(func() {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
clock := new(atomic.Int64)
|
||||
clock.Store(time.Now().UnixNano())
|
||||
published := make(chan []room.Delivery, 8)
|
||||
rules := roomRules{players: registry, shared: state}
|
||||
manager, err := room.New(room.Config{AdvertisedHost: "127.0.0.1", TCPPort: 9000, Now: func() time.Time { return time.Unix(0, clock.Load()) }, PublishResult: state.rooms.publish, Publish: func(d []room.Delivery) { published <- d }}, rules)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := manager.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
state.rooms.rooms = manager
|
||||
var actors [2]*player.Runtime
|
||||
var clients [2]room.Connection
|
||||
var seq [2]uint64
|
||||
for i, account := range accounts {
|
||||
actor, release, err := registry.Acquire(ctx, account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(release)
|
||||
actors[i] = actor
|
||||
profile, err := factory.profiles.GameIdentity(ctx, account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clients[i] = room.Connection{ID: fmt.Sprintf("fish-matching-%d", i), Channel: room.Matching, Principal: room.Principal{AccountID: account, OwnerIndex: profile.OwnerIndex, SessionID: "registry-client", Generation: actor.Generation()}}
|
||||
}
|
||||
call := func(i int, path string, fields []byte) (player.Command, player.Reply) {
|
||||
t.Helper()
|
||||
seq[i]++
|
||||
body := wire.AppendVarint(nil, 1, seq[i])
|
||||
body = append(body, fields...)
|
||||
cmd := registryCommand(accounts[i], fmt.Sprintf("fish-%s-%d", path, seq[i]), path, body)
|
||||
if path == "/LoginUser" {
|
||||
cmd.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
|
||||
}
|
||||
return cmd, registryExecute(t, actors[i], cmd)
|
||||
}
|
||||
drain := func(i int) {
|
||||
t.Helper()
|
||||
seq[i]++
|
||||
cmd := player.Command{Identity: command.Identity{AccountID: accounts[i], SessionID: "fish-delivery", RequestID: fmt.Sprint(seq[i])}, System: &player.SystemRequest{Kind: player.ReadOutbox}}
|
||||
reply := registryExecute(t, actors[i], cmd)
|
||||
var pending []outbox.Pending
|
||||
if err := json.Unmarshal(reply.Responses[0].Body, &pending); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, event := range pending {
|
||||
if err := state.Consume(ctx, event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := json.Marshal(struct {
|
||||
Key string `json:"key"`
|
||||
Digest string `json:"digest"`
|
||||
}{event.Key, event.Digest})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seq[i]++
|
||||
cmd.Identity.RequestID = fmt.Sprint(seq[i])
|
||||
cmd.Digest = sha256.Sum256(raw)
|
||||
cmd.System = &player.SystemRequest{Kind: player.AcknowledgeOutbox, Body: raw}
|
||||
registryExecute(t, actors[i], cmd)
|
||||
}
|
||||
}
|
||||
handle := func(i int, typ int32, payload []byte) []room.Delivery {
|
||||
t.Helper()
|
||||
d, err := manager.Handle(ctx, clients[i], room.Frame{Type: typ, Payload: payload})
|
||||
if err != nil {
|
||||
t.Fatalf("native fishing type%d: %v", typ, err)
|
||||
}
|
||||
return d
|
||||
}
|
||||
for id := starterBoat + 1; id <= partyBoat; id++ {
|
||||
_, reply := call(0, "/FishingBoatUpgrade", nil)
|
||||
if appValue(reply.Responses[0].Body, 1) != id {
|
||||
t.Fatal("host upgrade did not purchase GameData boat")
|
||||
}
|
||||
}
|
||||
profile, err := rules.Profile(ctx, clients[0].Principal)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(profile.FishingMaps) == 0 {
|
||||
t.Fatal("real starter owns no fishing map")
|
||||
}
|
||||
mapID := profile.FishingMaps[0]
|
||||
boat, err := factory.design.eventPlay.NativeFishingRules(mapID, uint64(profile.BoatLevel), uint64(profile.BoatSkinID))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := wire.AppendVarint(nil, 3, uint64(profile.BoatLevel))
|
||||
request = wire.AppendVarint(request, 4, mapID)
|
||||
request = wire.AppendVarint(request, 5, uint64(profile.BoatSkinID))
|
||||
handle(0, 149, request)
|
||||
view, err := manager.View(ctx, clients[0].Principal, room.Fishing)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handle(1, 155, wire.AppendString(nil, 2, view.RoomCode))
|
||||
message := func(value string) []byte {
|
||||
return wire.AppendBytes(nil, 2, wire.AppendString(wire.AppendString(nil, 1, view.RoomCode), 4, value))
|
||||
}
|
||||
rejected := handle(0, 172, message("Blocked"))
|
||||
if len(rejected) != 1 || rejected[0].ConnectionID != clients[0].ID || rejected[0].Frame.Type != 173 {
|
||||
t.Fatalf("blocked matching text must receive EParam without broadcasting: %+v", rejected)
|
||||
}
|
||||
header, _, err := wire.Bytes(rejected[0].Frame.Payload, 1)
|
||||
if err != nil || appValue(header, 2) != 2 {
|
||||
t.Fatal("blocked matching text response omitted EParam")
|
||||
}
|
||||
allowed := handle(0, 172, message("Allowed"))
|
||||
guestReceived := false
|
||||
for _, delivery := range allowed {
|
||||
if delivery.ConnectionID == clients[1].ID && delivery.Frame.Type == 174 {
|
||||
body, _, err := wire.Bytes(delivery.Frame.Payload, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text, _, err := wire.Bytes(body, 4)
|
||||
guestReceived = err == nil && string(text) == "Allowed"
|
||||
}
|
||||
}
|
||||
if !guestReceived {
|
||||
t.Fatal("valid matching text did not reach guest after rejected text")
|
||||
}
|
||||
handle(0, 157, nil)
|
||||
if view.Selection.Capacity != boat.Capacity || view.Selection.ReconnectWindow != boat.ReconnectWindow || view.Selection.Duration != boat.Duration {
|
||||
t.Fatalf("native fishing limits differ from GD boat: %+v want %+v", view.Selection, boat)
|
||||
}
|
||||
var guids [2]string
|
||||
for i := range clients {
|
||||
clients[i].Channel = room.Fishing
|
||||
clients[i].ID = fmt.Sprintf("fish-game-%d", i)
|
||||
d := handle(i, 23, wire.AppendString(nil, 2, view.RoomCode))
|
||||
guid, found, err := wire.Bytes(d[0].Frame.Payload, 4)
|
||||
if err != nil || !found {
|
||||
t.Fatal("fishing entry missing GUID")
|
||||
}
|
||||
guids[i] = string(guid)
|
||||
}
|
||||
var beforeAP [2]uint64
|
||||
loginAP := func(i int) uint64 {
|
||||
t.Helper()
|
||||
_, reply := call(i, "/LoginUser", nil)
|
||||
rows := appRows(reply.Responses[0].Body, 1)
|
||||
if len(rows) != 1 {
|
||||
t.Fatal("LoginUser missing player")
|
||||
}
|
||||
return appValue(rows[0], 62)
|
||||
}
|
||||
for i := range clients {
|
||||
beforeAP[i] = loginAP(i)
|
||||
}
|
||||
if beforeAP[0] == 0 {
|
||||
t.Fatal("real starter has no multiplayer fishing ticket")
|
||||
}
|
||||
var starts [2]player.Command
|
||||
for i := range clients {
|
||||
cmd, reply := call(i, "/FishingVoyageStart", wire.AppendVarint(nil, 2, mapID))
|
||||
starts[i] = cmd
|
||||
if reply.Responses[0].PacketCode != 500 {
|
||||
t.Fatal("wrong FishingVoyageStart packet")
|
||||
}
|
||||
if i == 0 && appValue(reply.Responses[0].Body, 1) != 1 {
|
||||
t.Fatal("host response omitted room host indication")
|
||||
}
|
||||
drain(i)
|
||||
}
|
||||
// Read the guest's committed snapshot independently of the room projection.
|
||||
path := filepath.Join(factory.options.stateDirectory, "accounts", accountDirectoryName(accounts[1]), "state.db")
|
||||
u := url.URL{Scheme: "file", Path: "/" + filepath.ToSlash(path)}
|
||||
query := u.Query()
|
||||
query.Set("mode", "ro")
|
||||
query.Set("_pragma", "query_only(1)")
|
||||
u.RawQuery = query.Encode()
|
||||
db, err := sql.Open("sqlite", u.String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var saved []byte
|
||||
readErr := db.QueryRowContext(ctx, "SELECT payload FROM domain_entry WHERE domain_name='fishing' AND bucket='state' AND entry_key='core'").Scan(&saved)
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
var guest struct {
|
||||
Boat uint64
|
||||
Voyage *eventplay.NativeRun
|
||||
VoyageStarted, NextAuto int64
|
||||
}
|
||||
if err := json.Unmarshal(saved, &guest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if guest.Boat != starterBoat || guest.Voyage == nil || guest.Voyage.BoatLevel != partyBoat || guest.Voyage.Members != 2 {
|
||||
t.Fatalf("guest's personal boat or host voyage changed: %+v", guest)
|
||||
}
|
||||
boatRow, err := factory.design.eventPlay.Row("FishingBoatTable", 8, partyBoat)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitReduction := float64(0)
|
||||
for _, group := range appPacked(boatRow, 1) {
|
||||
for _, row := range factory.design.eventPlay.Rows("FishingBoatBuffTable", 2, group) {
|
||||
if appValue(row, 3) != 2 {
|
||||
continue
|
||||
}
|
||||
buff, err := factory.design.eventPlay.Row("FishingBuffTable", 4, appValue(row, 1))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if appValue(buff, 2) == 7 {
|
||||
waitReduction += nativeFixtureDouble(t, buff, 3)
|
||||
}
|
||||
}
|
||||
}
|
||||
defaults, err := factory.design.eventPlay.Row("FishingDefaultTable", 25, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
baseWait := nativeFixtureDouble(t, defaults, 5)
|
||||
if waitReduction <= 0 {
|
||||
t.Fatal("selected real party boat has no waiting-time buff to distinguish guest boat")
|
||||
}
|
||||
wantWait := int64(math.Ceil(math.Max(1, baseWait-waitReduction)))
|
||||
if guest.NextAuto-guest.VoyageStarted != wantWait {
|
||||
t.Fatalf("guest auto waiting time=%d want host boat two-person buff=%d", guest.NextAuto-guest.VoyageStarted, wantWait)
|
||||
}
|
||||
if got := loginAP(0); got != beforeAP[0]-1 {
|
||||
t.Fatalf("host ticket debit=%d want%d", got, beforeAP[0]-1)
|
||||
}
|
||||
if got := loginAP(1); got != beforeAP[1] {
|
||||
t.Fatal("guest spent host multiplayer ticket")
|
||||
}
|
||||
registryExecute(t, actors[0], starts[0])
|
||||
if got := loginAP(0); got != beforeAP[0]-1 {
|
||||
t.Fatal("replayed Start spent another ticket")
|
||||
}
|
||||
for i := range clients {
|
||||
b := wire.AppendString(nil, 2, guids[i])
|
||||
b = wire.AppendString(b, 3, view.RoomCode)
|
||||
b = wire.AppendBytes(b, 4, wire.AppendVarint(nil, 1, uint64(clients[i].Principal.OwnerIndex)))
|
||||
handle(i, 212, b)
|
||||
}
|
||||
view, err = manager.View(ctx, clients[0].Principal, room.Fishing)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range view.Members {
|
||||
if !m.AcceptedRun || !m.Ready {
|
||||
t.Fatal("committed fishing admission did not reach ready native state")
|
||||
}
|
||||
}
|
||||
chat := func(value string) []byte {
|
||||
payload := wire.AppendString(wire.AppendVarint(nil, 1, uint64(clients[0].Principal.OwnerIndex)), 2, value)
|
||||
data := append(binary.LittleEndian.AppendUint32(nil, 9004), payload...)
|
||||
return wire.AppendBytes(wire.AppendString(nil, 2, guids[0]), 3, data)
|
||||
}
|
||||
if rejected := handle(0, 70, chat("Blocked")); len(rejected) != 0 {
|
||||
t.Fatal("blocked fishing chat was broadcast")
|
||||
}
|
||||
allowed = handle(0, 70, chat("Allowed"))
|
||||
guestReceived = false
|
||||
for _, delivery := range allowed {
|
||||
guestReceived = guestReceived || delivery.ConnectionID == clients[1].ID && delivery.Frame.Type == 71 && bytes.Contains(delivery.Frame.Payload, []byte("Allowed"))
|
||||
}
|
||||
if !guestReceived {
|
||||
t.Fatal("valid fishing chat did not reach guest after rejected text")
|
||||
}
|
||||
info := wire.AppendVarint(nil, 1, uint64(clients[1].Principal.OwnerIndex))
|
||||
d := handle(1, 210, wire.AppendVarint(wire.AppendBytes(wire.AppendString(nil, 2, guids[1]), 3, info), 4, 1))
|
||||
if len(d) != 1 || d[0].ConnectionID != clients[0].ID || d[0].Frame.Type != 211 {
|
||||
t.Fatal("guest fishing state was not relayed only to other participant")
|
||||
}
|
||||
clock.Add(int64(5 * time.Second))
|
||||
handle(0, 192, wire.AppendString(nil, 2, guids[0]))
|
||||
var final room.FinalResult
|
||||
select {
|
||||
case final = <-state.rooms.queue:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("native fishing terminal missing")
|
||||
}
|
||||
if final.View.Kind != room.Fishing || len(final.View.Members) != 2 {
|
||||
t.Fatal("incomplete fishing terminal participants")
|
||||
}
|
||||
if err := state.rooms.persist(ctx, final); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case d := <-published:
|
||||
if len(d) != 2 || d[0].Frame.Type != 204 || d[1].Frame.Type != 204 {
|
||||
t.Fatal("durable fishing terminal not sent to both participants")
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("fishing persistence acknowledgement missing")
|
||||
}
|
||||
reopen := func() {
|
||||
t.Helper()
|
||||
if err := registry.Close(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry = newPlayerRegistry(factory, time.Hour)
|
||||
for i, account := range accounts {
|
||||
actor, release, err := registry.Acquire(ctx, account)
|
||||
if err != nil {
|
||||
t.Fatal("reopen committed fishing player", err)
|
||||
}
|
||||
t.Cleanup(release)
|
||||
actors[i] = actor
|
||||
}
|
||||
}
|
||||
reopen()
|
||||
if loginAP(0) != beforeAP[0]-1 || loginAP(1) != beforeAP[1] {
|
||||
t.Fatal("reopen lost committed voyage ticket debit")
|
||||
}
|
||||
var ends [2]player.Command
|
||||
for i := range clients {
|
||||
cmd, reply := call(i, "/FishingVoyageEnd", nil)
|
||||
ends[i] = cmd
|
||||
if reply.Responses[0].PacketCode != 508 {
|
||||
t.Fatal("wrong FishingVoyageEnd packet")
|
||||
}
|
||||
drain(i)
|
||||
replay := registryExecute(t, actors[i], cmd)
|
||||
if !bytes.Equal(reply.Responses[0].Body, replay.Responses[0].Body) {
|
||||
t.Fatal("fishing End replay changed response")
|
||||
}
|
||||
if i == 0 {
|
||||
if err := state.store.View(ctx, func(tx *shared.Tx) error {
|
||||
_, found, err := tx.Get("room.results", final.View.InstanceID)
|
||||
if !found {
|
||||
t.Error("host claim removed guest's retained result")
|
||||
}
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if loginAP(0) != beforeAP[0]-1 || loginAP(1) != beforeAP[1] {
|
||||
t.Fatal("fishing End or replay changed multiplayer tickets")
|
||||
}
|
||||
reopen()
|
||||
for i := range actors {
|
||||
registryExecute(t, actors[i], ends[i])
|
||||
registryExecute(t, actors[i], starts[i])
|
||||
}
|
||||
if loginAP(0) != beforeAP[0]-1 || loginAP(1) != beforeAP[1] {
|
||||
t.Fatal("durable replay after reopen changed fishing tickets")
|
||||
}
|
||||
if err := state.store.View(ctx, func(tx *shared.Tx) error {
|
||||
for _, bucket := range []string{"room.results", "room.runs", "room.claims"} {
|
||||
rows, err := tx.Scan(bucket, final.View.InstanceID, "", 128)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) != 0 {
|
||||
t.Errorf("claimed fishing instance retained%s", bucket)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func nativeFixtureDouble(t *testing.T, raw []byte, number int) float64 {
|
||||
t.Helper()
|
||||
var value float64
|
||||
if err := wire.Walk(raw, func(field wire.Field) error {
|
||||
if field.Number == number {
|
||||
if field.Type != 1 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
value = math.Float64frombits(binary.LittleEndian.Uint64(field.Value))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
)
|
||||
|
||||
type roomRules struct {
|
||||
players *playerRegistry
|
||||
shared *sharedRuntime
|
||||
}
|
||||
|
||||
func (r roomRules) CheckRoomText(ctx context.Context, p room.Principal, text string) error {
|
||||
moderator := r.players.factory.options.textModerator
|
||||
if moderator == nil {
|
||||
return errors.New("text moderation is unavailable")
|
||||
}
|
||||
err := moderator.Check(ctx, "chat", p.AccountID, text)
|
||||
if errors.Is(err, textmoderation.ErrRejected) {
|
||||
return room.ErrTextRejected
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (r roomRules) Profile(ctx context.Context, principal room.Principal) (room.Profile, error) {
|
||||
body, err := executePlayerSystem(ctx, r.players, principal.AccountID, player.ReadRoomProfile, nil)
|
||||
if err != nil {
|
||||
return room.Profile{}, err
|
||||
}
|
||||
var result room.Profile
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return result, err
|
||||
}
|
||||
guild, err := r.shared.guild.Account(ctx, principal.AccountID)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.UserInfo, _, err = wire.ReplaceVarint(result.UserInfo, 2, guild.GuildID)
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (r roomRules) ValidateSelection(profile room.Profile, selection room.Selection) (room.Selection, error) {
|
||||
if selection.Kind == room.Fishing {
|
||||
if !slices.Contains(profile.FishingMaps, uint64(selection.MapID)) {
|
||||
return selection, room.ErrUnauthorized
|
||||
}
|
||||
rules, err := r.players.factory.design.eventPlay.NativeFishingRules(uint64(selection.MapID), uint64(profile.BoatLevel), uint64(profile.BoatSkinID))
|
||||
if err != nil {
|
||||
return selection, err
|
||||
}
|
||||
selection.BoatLevel = profile.BoatLevel
|
||||
selection.BoatSkinID = profile.BoatSkinID
|
||||
selection.Capacity = rules.Capacity
|
||||
selection.LoadingLimit = rules.LoadingLimit
|
||||
selection.ReconnectWindow = rules.ReconnectWindow
|
||||
selection.Duration = rules.Duration
|
||||
return selection, nil
|
||||
}
|
||||
family := "Action"
|
||||
if selection.Kind == room.Defense {
|
||||
family = "Defense"
|
||||
} else if selection.Kind != room.Action {
|
||||
return selection, room.ErrUnauthorized
|
||||
}
|
||||
for _, event := range r.players.factory.options.calendars.Events {
|
||||
if int64(event.UID) != selection.EventScheduleID {
|
||||
continue
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
if now < event.Start || now >= event.End {
|
||||
return selection, errors.New("room event is outside its play window")
|
||||
}
|
||||
rules, err := r.players.factory.design.eventPlay.NativeMinigameRules(family, event.ID, uint64(selection.CharacterID), uint64(selection.MonsterID), selection.Solo)
|
||||
if err != nil {
|
||||
return selection, err
|
||||
}
|
||||
selection.Capacity = rules.Capacity
|
||||
selection.GroupID = int64(rules.GroupID)
|
||||
selection.StageID = int64(rules.StageID)
|
||||
selection.DefenseLastWave = int64(rules.LastWave)
|
||||
selection.LoadingLimit = rules.LoadingLimit
|
||||
selection.Duration = rules.Duration
|
||||
return selection, nil
|
||||
}
|
||||
return selection, errors.New("unknown room event")
|
||||
}
|
||||
|
||||
func (r roomRules) ValidateParticipant(profile room.Profile, selection room.Selection) error {
|
||||
if selection.Kind != room.Fishing || profile.RodID <= 0 {
|
||||
return room.ErrUnauthorized
|
||||
}
|
||||
_, err := r.players.factory.design.eventPlay.NativeFishingRules(uint64(selection.MapID), uint64(selection.BoatLevel), uint64(selection.BoatSkinID))
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *playerAssembly) roomProfile(ctx command.Context) ([]byte, error) {
|
||||
owner, err := p.ProfileOwner(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profile, err := p.PublicProfile(ctx, owner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := wire.AppendVarint(nil, 1, owner)
|
||||
user = wire.AppendString(user, 4, profile.UserID)
|
||||
user = wire.AppendVarint(user, 5, profile.PortraitCostumeID)
|
||||
user = wire.AppendVarint(user, 6, profile.PortraitDesignID)
|
||||
user = wire.AppendVarint(user, 7, profile.TitleID)
|
||||
avatar, err := p.avatarService.CurrentUse(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
use := wire.AppendVarint(nil, 1, owner)
|
||||
use = wire.AppendVarint(use, 2, avatar.UseCharID)
|
||||
for index, value := range avatar.Parts {
|
||||
use = wire.AppendVarint(use, index+3, value)
|
||||
}
|
||||
fish := p.fishingService.Profile()
|
||||
return json.Marshal(room.Profile{UserInfo: user, AvatarUseInfo: use, RodID: int64(fish.RodID), BoatLevel: int64(fish.BoatLevel), BoatSkinID: int64(fish.BoatSkinID), FishingMaps: fish.Maps})
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
eventplay "bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
)
|
||||
|
||||
func (r *roomResults) recordTeam(ctx context.Context, final room.FinalResult) error {
|
||||
if final.View.Kind != room.Action {
|
||||
return nil
|
||||
}
|
||||
stage := uint64(2)
|
||||
if final.View.Selection.Solo {
|
||||
stage = 1
|
||||
}
|
||||
record := ranking.CompletedTeamRun{ResultID: "room:" + final.View.InstanceID, InstanceID: final.View.InstanceID, EventUID: uint64(final.View.Selection.EventScheduleID), Monster: uint64(final.View.Selection.MonsterID), StageType: stage, Clear: final.Clear, Milliseconds: final.ScoreMilliseconds}
|
||||
for _, member := range final.View.Members {
|
||||
name, _, err := wire.Bytes(member.Profile.UserInfo, 4)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
record.Members = append(record.Members, ranking.TeamMember{AccountID: member.Principal.AccountID, OwnerIndex: uint64(member.Principal.OwnerIndex), Name: string(name), CharacterID: uint64(member.CharacterID)})
|
||||
}
|
||||
return r.teams.Record(ctx, record)
|
||||
}
|
||||
|
||||
func (r *roomResults) NativeRankings(ctx command.Context, event, monster, stage uint64) ([]eventplay.NativeRanking, error) {
|
||||
rows, err := r.teams.Rankings(ranking.TeamQuery{OwnerID: ctx.AccountID, EventUID: event, Monster: monster, StageType: stage, Limit: 100})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]eventplay.NativeRanking, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
result := eventplay.NativeRanking{InstanceID: row.InstanceID, EventUID: row.EventUID, Monster: row.Monster, StageType: row.StageType, Rank: row.Rank, Score: float64(row.Milliseconds), TopPercent: row.TopPercent, Own: row.Own}
|
||||
for _, member := range row.Members {
|
||||
result.Members = append(result.Members, eventplay.NativeRankMember{OwnerIndex: member.OwnerIndex, UserID: member.Name, CharacterID: member.CharacterID})
|
||||
}
|
||||
out = append(out, result)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
eventplay "bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
func roomMemberKey(account string) string {
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(account))
|
||||
}
|
||||
|
||||
type roomResults struct {
|
||||
teams *ranking.Teams
|
||||
endpoints []eventplay.RelayEndpoint
|
||||
deliver func([]room.Delivery)
|
||||
store *shared.Store
|
||||
rooms *room.Manager
|
||||
pending sync.Map
|
||||
queue chan room.FinalResult
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func (r *roomResults) RelayEndpoints() []eventplay.RelayEndpoint {
|
||||
return append([]eventplay.RelayEndpoint(nil), r.endpoints...)
|
||||
}
|
||||
|
||||
func openRoomResults(ctx context.Context, store *shared.Store) (*roomResults, error) {
|
||||
r := &roomResults{store: store, queue: make(chan room.FinalResult, 128), done: make(chan struct{})}
|
||||
var err error
|
||||
r.teams, err = ranking.NewTeams(ctx, rankingStore{store})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = r.recoverResults(ctx)
|
||||
return r, err
|
||||
}
|
||||
|
||||
func (r *roomResults) publish(final room.FinalResult) bool {
|
||||
r.pending.Store(final.View.InstanceID, struct{}{})
|
||||
select {
|
||||
case r.queue <- final:
|
||||
return true
|
||||
default:
|
||||
r.pending.Delete(final.View.InstanceID)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (r *roomResults) start() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
r.cancel = cancel
|
||||
go func() {
|
||||
defer close(r.done)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case final, ok := <-r.queue:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for {
|
||||
err := r.persist(ctx, final)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
slog.Warn("room result persistence deferred", "instance_id", final.View.InstanceID, "error", err)
|
||||
timer := time.NewTimer(time.Second)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (r *roomResults) persist(ctx context.Context, final room.FinalResult) error {
|
||||
raw, err := json.Marshal(final)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = r.store.Update(ctx, func(tx *shared.Tx) error {
|
||||
retired, err := retiredRoomResult(tx, final)
|
||||
if err != nil || retired {
|
||||
return err
|
||||
}
|
||||
old, found, err := tx.Get("room.results", final.View.InstanceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
var saved room.FinalResult
|
||||
if err := json.Unmarshal(old, &saved); err != nil {
|
||||
return err
|
||||
}
|
||||
if saved.ScoreMilliseconds != final.ScoreMilliseconds || saved.Clear != final.Clear || saved.View.Kind != final.View.Kind {
|
||||
return outbox.ErrConflict
|
||||
}
|
||||
final = saved
|
||||
return nil
|
||||
}
|
||||
return tx.Put("room.results", final.View.InstanceID, raw)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.recordTeam(ctx, final); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.retireClaimedResult(ctx, final); err != nil {
|
||||
return err
|
||||
}
|
||||
r.pending.Delete(final.View.InstanceID)
|
||||
if r.rooms == nil {
|
||||
return nil
|
||||
}
|
||||
err = r.rooms.AcknowledgeResult(ctx, final.View.InstanceID)
|
||||
if errors.Is(err, room.ErrNotFound) || errors.Is(err, room.ErrClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *roomResults) StartRun(ctx command.Context, family string) (eventplay.NativeRun, error) {
|
||||
if r.rooms == nil {
|
||||
return eventplay.NativeRun{}, eventplay.ErrNoRoom
|
||||
}
|
||||
kind := room.Kind(strings.ToLower(family))
|
||||
view, err := r.rooms.SnapshotForSession(ctx.AccountID, ctx.SessionID, kind)
|
||||
if err != nil {
|
||||
if errors.Is(err, room.ErrNotFound) {
|
||||
return eventplay.NativeRun{}, eventplay.ErrNoRoom
|
||||
}
|
||||
return eventplay.NativeRun{}, err
|
||||
}
|
||||
if view.RoomState != 2 && (kind != room.Fishing || view.RoomState != 1) {
|
||||
return eventplay.NativeRun{}, room.ErrNotReady
|
||||
}
|
||||
for _, member := range view.Members {
|
||||
if member.Principal.AccountID != ctx.AccountID || member.Principal.SessionID != ctx.SessionID {
|
||||
continue
|
||||
}
|
||||
if (!member.Ready && kind != room.Fishing) || member.NativeGUID == "" {
|
||||
return eventplay.NativeRun{}, room.ErrNotReady
|
||||
}
|
||||
started := int64(0)
|
||||
if !view.StartTime.IsZero() {
|
||||
started = view.StartTime.UnixMilli()
|
||||
}
|
||||
return eventplay.NativeRun{InstanceID: view.InstanceID, GUID: member.NativeGUID, Family: family, SessionID: ctx.SessionID, UID: uint64(view.Selection.EventScheduleID), Group: uint64(view.Selection.GroupID), Stage: uint64(view.Selection.StageID), Monster: uint64(view.Selection.MonsterID), Started: started, MapID: uint64(view.Selection.MapID), BoatLevel: uint64(view.Selection.BoatLevel), Host: member.Principal.OwnerIndex == view.HostOwnerIndex, Members: uint64(len(view.Members))}, nil
|
||||
}
|
||||
return eventplay.NativeRun{}, room.ErrUnauthorized
|
||||
}
|
||||
|
||||
func (r *roomResults) Result(ctx command.Context, run eventplay.NativeRun) (eventplay.NativeResult, error) {
|
||||
if _, pending := r.pending.Load(run.InstanceID); pending {
|
||||
return eventplay.NativeResult{}, eventplay.ErrRoomNotFinished
|
||||
}
|
||||
if r.rooms != nil {
|
||||
view, err := r.rooms.SnapshotForSession(ctx.AccountID, run.SessionID, room.Kind(strings.ToLower(run.Family)))
|
||||
if err == nil && view.InstanceID == run.InstanceID {
|
||||
return eventplay.NativeResult{}, eventplay.ErrRoomNotFinished
|
||||
}
|
||||
}
|
||||
return eventplay.NativeResult{}, eventplay.ErrRoomAbandoned
|
||||
}
|
||||
|
||||
func (r *roomResults) Consume(ctx context.Context, event outbox.Pending) error {
|
||||
var run eventplay.NativeRun
|
||||
if err := json.Unmarshal(event.Envelope.Event.Payload, &run); err != nil {
|
||||
return err
|
||||
}
|
||||
if run.InstanceID == "" || run.GUID == "" {
|
||||
return errors.New("invalid committed room run")
|
||||
}
|
||||
if event.Envelope.Event.Topic == "room.run.claimed" {
|
||||
return r.claim(ctx, event, run)
|
||||
}
|
||||
if event.Envelope.Event.Topic != "room.run.accepted" {
|
||||
return errors.New("unsupported room event")
|
||||
}
|
||||
if err := r.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
|
||||
return tx.Put("room.runs", run.InstanceID+":"+roomMemberKey(envelope.Source), envelope.Event.Payload)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
kind := room.Kind(strings.ToLower(run.Family))
|
||||
if r.rooms == nil {
|
||||
return nil
|
||||
}
|
||||
view, err := r.rooms.SnapshotForSession(event.Envelope.Source, run.SessionID, kind)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, member := range view.Members {
|
||||
if member.Principal.AccountID == event.Envelope.Source && member.NativeGUID == run.GUID {
|
||||
return r.rooms.AcceptRun(ctx, member.Principal, kind, run.InstanceID, run.GUID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *roomResults) claim(ctx context.Context, event outbox.Pending, run eventplay.NativeRun) error {
|
||||
err := r.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
|
||||
raw, found, err := tx.Get("room.results", run.InstanceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
if run.Family != "Fishing" {
|
||||
return errors.New("room claim has no durable result")
|
||||
}
|
||||
saved, accepted, err := tx.Get("room.runs", run.InstanceID+":"+roomMemberKey(envelope.Source))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var own eventplay.NativeRun
|
||||
if !accepted || json.Unmarshal(saved, &own) != nil || own != run {
|
||||
return room.ErrUnauthorized
|
||||
}
|
||||
key := run.InstanceID + ":" + roomMemberKey(envelope.Source)
|
||||
if err := tx.Put("room.claims", key, []byte(run.GUID)); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Delete("room.runs", key)
|
||||
return err
|
||||
}
|
||||
var final room.FinalResult
|
||||
if err := json.Unmarshal(raw, &final); err != nil {
|
||||
return err
|
||||
}
|
||||
memberFound := false
|
||||
for _, member := range final.View.Members {
|
||||
memberFound = memberFound || member.Principal.AccountID == envelope.Source && member.NativeGUID == run.GUID
|
||||
}
|
||||
if !memberFound {
|
||||
return room.ErrUnauthorized
|
||||
}
|
||||
if err := tx.Put("room.claims", run.InstanceID+":"+roomMemberKey(envelope.Source), []byte(run.GUID)); err != nil {
|
||||
return err
|
||||
}
|
||||
return retireClaimedRoom(tx, final)
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *roomResults) stop() {
|
||||
if r.cancel == nil {
|
||||
return
|
||||
}
|
||||
close(r.queue)
|
||||
timer := time.AfterFunc(30*time.Second, r.cancel)
|
||||
<-r.done
|
||||
timer.Stop()
|
||||
r.cancel()
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
eventplay "bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
type preparedRoomResult struct {
|
||||
result eventplay.NativeResult
|
||||
err error
|
||||
}
|
||||
|
||||
type preparedRoomResults struct {
|
||||
*roomResults
|
||||
account string
|
||||
results map[eventplay.NativeRun]preparedRoomResult
|
||||
}
|
||||
|
||||
// PrepareResults reads durable entitlements before the caller opens its player transaction.
|
||||
func (r *roomResults) PrepareResults(ctx context.Context, account string, runs []eventplay.NativeRun) (eventplay.RoomRuntime, error) {
|
||||
if account == "" {
|
||||
return nil, room.ErrUnauthorized
|
||||
}
|
||||
prepared := &preparedRoomResults{roomResults: r, account: account, results: make(map[eventplay.NativeRun]preparedRoomResult, len(runs))}
|
||||
err := r.store.View(ctx, func(tx *shared.Tx) error {
|
||||
for _, run := range runs {
|
||||
if _, loaded := prepared.results[run]; loaded {
|
||||
continue
|
||||
}
|
||||
raw, found, err := tx.Get("room.results", run.InstanceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var result eventplay.NativeResult
|
||||
if found {
|
||||
_, ready, readyErr := tx.Get("room.ready", run.InstanceID)
|
||||
if readyErr != nil {
|
||||
return readyErr
|
||||
}
|
||||
if !ready {
|
||||
prepared.results[run] = preparedRoomResult{err: eventplay.ErrRoomNotFinished}
|
||||
continue
|
||||
}
|
||||
var final room.FinalResult
|
||||
if err := json.Unmarshal(raw, &final); err != nil {
|
||||
return err
|
||||
}
|
||||
if final.View.InstanceID != run.InstanceID {
|
||||
return errors.New("invalid durable room result")
|
||||
}
|
||||
result, err = projectRoomResult(account, run, final)
|
||||
} else {
|
||||
result, err = r.Result(command.Context{Identity: command.Identity{AccountID: account}}, run)
|
||||
}
|
||||
prepared.results[run] = preparedRoomResult{result: result, err: err}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return prepared, err
|
||||
}
|
||||
|
||||
func (r *preparedRoomResults) Result(ctx command.Context, run eventplay.NativeRun) (eventplay.NativeResult, error) {
|
||||
if ctx.AccountID != r.account {
|
||||
return eventplay.NativeResult{}, room.ErrUnauthorized
|
||||
}
|
||||
prepared, found := r.results[run]
|
||||
if !found {
|
||||
// A run created in this command is eligible for prefetch on the next command.
|
||||
return eventplay.NativeResult{}, eventplay.ErrRoomNotFinished
|
||||
}
|
||||
result := prepared.result
|
||||
result.Evidence = append([]byte(nil), result.Evidence...)
|
||||
return result, prepared.err
|
||||
}
|
||||
|
||||
func projectRoomResult(account string, run eventplay.NativeRun, final room.FinalResult) (eventplay.NativeResult, error) {
|
||||
if string(final.View.Kind) != strings.ToLower(run.Family) {
|
||||
return eventplay.NativeResult{}, room.ErrUnauthorized
|
||||
}
|
||||
for _, member := range final.View.Members {
|
||||
if member.Principal.AccountID != account || member.NativeGUID != run.GUID {
|
||||
continue
|
||||
}
|
||||
score := final.ScoreMilliseconds
|
||||
if final.View.Kind == room.Defense {
|
||||
score = member.Wave
|
||||
}
|
||||
if score < 0 {
|
||||
return eventplay.NativeResult{}, errors.New("invalid negative room score")
|
||||
}
|
||||
return eventplay.NativeResult{Clear: final.Clear, Score: uint64(score), Evidence: append([]byte(nil), final.Evidence...)}, nil
|
||||
}
|
||||
return eventplay.NativeResult{}, room.ErrUnauthorized
|
||||
}
|
||||
|
||||
func (r *roomResults) recoverResults(ctx context.Context) error {
|
||||
for cursor := ""; ; {
|
||||
var rows []shared.Entry
|
||||
if err := r.store.View(ctx, func(tx *shared.Tx) error {
|
||||
var err error
|
||||
rows, err = tx.Scan("room.results", "", cursor, 128)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, row := range rows {
|
||||
var final room.FinalResult
|
||||
if err := json.Unmarshal(row.Value, &final); err != nil {
|
||||
return err
|
||||
}
|
||||
if row.Key != final.View.InstanceID {
|
||||
return errors.New("invalid durable room result")
|
||||
}
|
||||
if err := r.recordTeam(ctx, final); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.retireClaimedResult(ctx, final); err != nil {
|
||||
return err
|
||||
}
|
||||
cursor = row.Key
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func roomResultDigest(final room.FinalResult) ([]byte, error) {
|
||||
raw, err := json.Marshal(final)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
digest := sha256.Sum256(raw)
|
||||
return digest[:], nil
|
||||
}
|
||||
|
||||
func retiredRoomResult(tx *shared.Tx, final room.FinalResult) (bool, error) {
|
||||
prior, found, err := tx.Get("room.retired", final.View.InstanceID)
|
||||
if err != nil || !found {
|
||||
return false, err
|
||||
}
|
||||
digest, err := roomResultDigest(final)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !bytes.Equal(prior, digest) {
|
||||
return false, outbox.ErrConflict
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *roomResults) retireClaimedResult(ctx context.Context, final room.FinalResult) error {
|
||||
return r.store.Update(ctx, func(tx *shared.Tx) error {
|
||||
retired, err := retiredRoomResult(tx, final)
|
||||
if err != nil || retired {
|
||||
return err
|
||||
}
|
||||
if err := tx.Put("room.ready", final.View.InstanceID, []byte{1}); err != nil {
|
||||
return err
|
||||
}
|
||||
return retireClaimedRoom(tx, final)
|
||||
})
|
||||
}
|
||||
|
||||
func retireClaimedRoom(tx *shared.Tx, final room.FinalResult) error {
|
||||
_, ready, err := tx.Get("room.ready", final.View.InstanceID)
|
||||
if err != nil || !ready {
|
||||
return err
|
||||
}
|
||||
if len(final.View.Members) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, member := range final.View.Members {
|
||||
_, claimed, err := tx.Get("room.claims", final.View.InstanceID+":"+roomMemberKey(member.Principal.AccountID))
|
||||
if err != nil || !claimed {
|
||||
return err
|
||||
}
|
||||
}
|
||||
digest, err := roomResultDigest(final)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Keep the compact identity receipt so a delayed persistence retry cannot resurrect the payload.
|
||||
if err := tx.Put("room.retired", final.View.InstanceID, digest); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Delete("room.results", final.View.InstanceID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Delete("room.ready", final.View.InstanceID); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, bucket := range []string{"room.runs", "room.claims"} {
|
||||
prefix := final.View.InstanceID + ":"
|
||||
for cursor := ""; ; {
|
||||
rows, err := tx.Scan(bucket, prefix, cursor, 128)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
break
|
||||
}
|
||||
for _, row := range rows {
|
||||
if _, err := tx.Delete(bucket, row.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
cursor = row.Key
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
eventplay "bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/gateway/realtime"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
)
|
||||
|
||||
type realtimeRuntime struct {
|
||||
rooms *room.Manager
|
||||
server *realtime.Server
|
||||
tickets *realtimeTickets
|
||||
results *roomResults
|
||||
cancel context.CancelFunc
|
||||
done chan error
|
||||
}
|
||||
|
||||
func openRealtime(c *configuration, registry *playerRegistry, game *session.Server, shared *sharedRuntime, instance string) (*realtimeRuntime, error) {
|
||||
config := c.gameRules.Realtime
|
||||
if !config.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
results := shared.rooms
|
||||
results.endpoints = []eventplay.RelayEndpoint{{Region: "1", Host: config.PublicHost, TCPPort: strconv.Itoa(config.TCPPort)}}
|
||||
var transport atomic.Pointer[realtime.Server]
|
||||
rooms, err := room.New(room.Config{AdvertisedHost: config.PublicHost, TCPPort: config.TCPPort, UDPPort: config.UDPPort,
|
||||
Publish: func(frames []room.Delivery) {
|
||||
if server := transport.Load(); server != nil {
|
||||
server.Deliver(frames)
|
||||
}
|
||||
},
|
||||
PublishResult: results.publish,
|
||||
}, roomRules{players: registry, shared: shared})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
results.rooms = rooms
|
||||
tickets := &realtimeTickets{game: game, players: registry, rooms: rooms, bootID: instance,
|
||||
endpoint: realtimeEndpoint{TCPHost: config.PublicHost, TCPPort: config.TCPPort, UDPHost: config.PublicHost, UDPPort: config.UDPPort, TLSServerName: config.PublicHost, DevelopmentPlain: config.DevelopmentPlainLoopback},
|
||||
ownerIndex: func(ctx context.Context, account string) (int64, error) {
|
||||
if registry.factory.profiles != nil {
|
||||
profile, err := registry.factory.profiles.GameIdentity(ctx, account)
|
||||
return profile.OwnerIndex, err
|
||||
}
|
||||
owner, _, err := wire.Varint(registry.factory.seeds.login.UserInfo, 1)
|
||||
return int64(owner), err
|
||||
},
|
||||
}
|
||||
resolve := func(path string) string {
|
||||
if path == "" || filepath.IsAbs(path) {
|
||||
return path
|
||||
}
|
||||
return filepath.Join(filepath.Dir(c.gameConfigPath), path)
|
||||
}
|
||||
chatDesign, err := gamedata.LoadChatDesign(c.gameData, c.gameDataVersion)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, rooms.Close(context.Background()))
|
||||
}
|
||||
chat := &realtimeChat{rooms: rooms, shared: shared, rules: roomRules{players: registry, shared: shared}, historyCount: int(chatDesign.GuildHistoryCount), historyAge: time.Duration(chatDesign.GuildHistoryHours) * time.Hour, emojis: chatDesign.Emojis, now: time.Now}
|
||||
server, err := realtime.New(realtime.Config{TCPListen: config.TCPListen, UDPListen: config.UDPListen, TLSCertFile: resolve(config.TLSCertFile), TLSKeyFile: resolve(config.TLSKeyFile), DevelopmentPlainLoopback: config.DevelopmentPlainLoopback}, chat, tickets)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, rooms.Close(context.Background()))
|
||||
}
|
||||
transport.Store(server)
|
||||
results.deliver = server.Deliver
|
||||
results.start()
|
||||
registry.factory.roomResults = results
|
||||
shared.rooms = results
|
||||
c.bootstrap.MatchingAddress = net.JoinHostPort(config.PublicHost, strconv.Itoa(config.TCPPort))
|
||||
return &realtimeRuntime{rooms: rooms, server: server, tickets: tickets, results: results}, nil
|
||||
}
|
||||
|
||||
func (r *realtimeRuntime) start() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
r.cancel = cancel
|
||||
r.done = make(chan error, 1)
|
||||
go func() { r.done <- r.server.Serve(ctx) }()
|
||||
}
|
||||
|
||||
func (r *realtimeRuntime) close() error {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
if r.cancel != nil {
|
||||
r.cancel()
|
||||
}
|
||||
err := r.server.Close(context.Background())
|
||||
err = errors.Join(err, r.rooms.Close(context.Background()))
|
||||
r.results.stop()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
)
|
||||
|
||||
func TestRealtimeTicketUsesCurrentNativeGameSessionAndOneUseBindings(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
registry := newPlayerRegistry(factory, time.Minute)
|
||||
t.Cleanup(func() {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
game, err := session.NewServer(registry, nicknameAuthenticator{accounts[0]})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
login := func() string {
|
||||
t.Helper()
|
||||
reply, err := game.DispatchRaw(context.Background(), "/LoginUser", nicknameEncrypt(t, appScalar(1, 1), []byte("abcdefghijkrstuv024680wxyzlmnopq")), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return "s=" + reply.Cookie
|
||||
}
|
||||
cookie := login()
|
||||
tickets := &realtimeTickets{game: game, players: registry, bootID: "boot", ownerIndex: func(_ context.Context, account string) (int64, error) {
|
||||
if account != accounts[0] {
|
||||
return 0, errors.New("wrong account")
|
||||
}
|
||||
return 91, nil
|
||||
}}
|
||||
issue := func(cookie string, want int) string {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(http.MethodPost, "/realtime/ticket", strings.NewReader(`{"channel":"matching"}`))
|
||||
request.Header.Set("Cookie", cookie)
|
||||
reply := httptest.NewRecorder()
|
||||
tickets.ServeHTTP(reply, request)
|
||||
if reply.Code != want {
|
||||
t.Fatalf("ticket status=%d want%d: %s", reply.Code, want, reply.Body.String())
|
||||
}
|
||||
if want != http.StatusOK {
|
||||
return ""
|
||||
}
|
||||
var body struct {
|
||||
Ticket string `json:"ticket"`
|
||||
Instance string `json:"instance_id"`
|
||||
}
|
||||
if err := json.Unmarshal(reply.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(body.Ticket) != 43 || body.Instance != "boot" {
|
||||
t.Fatalf("invalid ticket response: %+v", body)
|
||||
}
|
||||
return body.Ticket
|
||||
}
|
||||
issue("", http.StatusUnauthorized)
|
||||
issue("s=invalid", http.StatusUnauthorized)
|
||||
principal, err := game.Principal(context.Background(), cookie)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token := issue(cookie, http.StatusOK)
|
||||
p, release, err := tickets.Consume(context.Background(), token, "matching", "boot")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if release == nil {
|
||||
t.Fatal("ticket omitted player lease")
|
||||
}
|
||||
release()
|
||||
if p.AccountID != principal.AccountID || p.SessionID != principal.SessionID || p.Generation != principal.Generation || p.OwnerIndex != 91 {
|
||||
t.Fatalf("ticket principal differs from native session: %+v vs %+v", p, principal)
|
||||
}
|
||||
if _, _, err = tickets.Consume(context.Background(), token, "matching", "boot"); !errors.Is(err, room.ErrUnauthorized) {
|
||||
t.Fatalf("ticket replay accepted: %v", err)
|
||||
}
|
||||
for _, tc := range []struct{ name, channel, instance string }{{"channel", "action", "boot"}, {"instance", "matching", "other-boot"}} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
token := issue(cookie, http.StatusOK)
|
||||
if _, _, err := tickets.Consume(context.Background(), token, tc.channel, tc.instance); !errors.Is(err, room.ErrUnauthorized) {
|
||||
t.Fatalf("ticket binding accepted: %v", err)
|
||||
}
|
||||
if _, _, err := tickets.Consume(context.Background(), token, "matching", "boot"); !errors.Is(err, room.ErrUnauthorized) {
|
||||
t.Fatalf("failed ticket use was reusable: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
expired := issue(cookie, http.StatusOK)
|
||||
key := sha256.Sum256([]byte(expired))
|
||||
tickets.mu.Lock()
|
||||
entry := tickets.pending[key]
|
||||
entry.expires = time.Now().Add(-time.Second)
|
||||
tickets.pending[key] = entry
|
||||
tickets.mu.Unlock()
|
||||
if _, _, err = tickets.Consume(context.Background(), expired, "matching", "boot"); !errors.Is(err, room.ErrUnauthorized) {
|
||||
t.Fatalf("expired ticket accepted: %v", err)
|
||||
}
|
||||
stale := issue(cookie, http.StatusOK)
|
||||
newCookie := login()
|
||||
issue(cookie, http.StatusUnauthorized)
|
||||
if _, _, err = tickets.Consume(context.Background(), stale, "matching", "boot"); !errors.Is(err, room.ErrUnauthorized) {
|
||||
t.Fatalf("old game session retained ticket authority: %v", err)
|
||||
}
|
||||
current := issue(newCookie, http.StatusOK)
|
||||
p, release, err = tickets.Consume(context.Background(), current, "matching", "boot")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if release == nil {
|
||||
t.Fatal("current ticket omitted lease")
|
||||
}
|
||||
release()
|
||||
if p.SessionID == principal.SessionID {
|
||||
t.Fatal("replacement login did not fence the old session")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
)
|
||||
|
||||
type realtimeEndpoint struct {
|
||||
TCPHost string `json:"tcp_host"`
|
||||
TCPPort int `json:"tcp_port"`
|
||||
UDPHost string `json:"udp_host"`
|
||||
UDPPort int `json:"udp_port"`
|
||||
TLSServerName string `json:"tls_server_name"`
|
||||
DevelopmentPlain bool `json:"development_plain"`
|
||||
}
|
||||
|
||||
type realtimeTicket struct {
|
||||
principal room.Principal
|
||||
channel room.Kind
|
||||
instance string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
type realtimeTickets struct {
|
||||
game *session.Server
|
||||
players session.RuntimeRouter
|
||||
rooms *room.Manager
|
||||
ownerIndex func(context.Context, string) (int64, error)
|
||||
endpoint realtimeEndpoint
|
||||
bootID string
|
||||
mu sync.Mutex
|
||||
pending map[[sha256.Size]byte]realtimeTicket
|
||||
}
|
||||
|
||||
func (t *realtimeTickets) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "POST required", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
defer func() { _ = r.Body.Close() }()
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 2049))
|
||||
if err != nil || len(body) > 2048 {
|
||||
http.Error(w, "invalid ticket request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Channel room.Kind `json:"channel"`
|
||||
Instance string `json:"instance_id"`
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
http.Error(w, "invalid ticket request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
http.Error(w, "invalid ticket request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if request.Channel != room.Matching && request.Channel != room.Action && request.Channel != room.Defense && request.Channel != room.Fishing {
|
||||
http.Error(w, "invalid channel", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
p, err := t.game.Principal(r.Context(), r.Header.Get("Cookie"))
|
||||
if err != nil {
|
||||
http.Error(w, "game session required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
owner, err := t.ownerIndex(r.Context(), p.AccountID)
|
||||
if err != nil || owner <= 0 {
|
||||
http.Error(w, "game identity unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
principal := room.Principal{AccountID: p.AccountID, OwnerIndex: owner, SessionID: p.SessionID, Generation: p.Generation}
|
||||
instance := t.bootID
|
||||
if request.Channel != room.Matching {
|
||||
view, err := t.rooms.View(r.Context(), principal, request.Channel)
|
||||
if err != nil {
|
||||
http.Error(w, "room membership required", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
instance = view.InstanceID
|
||||
}
|
||||
if instance == "" || request.Instance != "" && request.Instance != instance {
|
||||
http.Error(w, "instance changed", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
var secret [32]byte
|
||||
if _, err := rand.Read(secret[:]); err != nil {
|
||||
http.Error(w, "ticket unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(secret[:])
|
||||
key := sha256.Sum256([]byte(token))
|
||||
now := time.Now()
|
||||
expires := now.Add(30 * time.Second)
|
||||
t.mu.Lock()
|
||||
if t.pending == nil {
|
||||
t.pending = map[[sha256.Size]byte]realtimeTicket{}
|
||||
}
|
||||
for k, v := range t.pending {
|
||||
if !now.Before(v.expires) {
|
||||
delete(t.pending, k)
|
||||
}
|
||||
}
|
||||
count := 0
|
||||
for _, v := range t.pending {
|
||||
if v.principal.AccountID == p.AccountID {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count >= 8 || len(t.pending) >= 4096 {
|
||||
t.mu.Unlock()
|
||||
http.Error(w, "ticket capacity exhausted", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
t.pending[key] = realtimeTicket{principal: principal, channel: request.Channel, instance: instance, expires: expires}
|
||||
t.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Ticket string `json:"ticket"`
|
||||
Expires int64 `json:"expires_at"`
|
||||
Channel room.Kind `json:"channel"`
|
||||
Instance string `json:"instance_id"`
|
||||
realtimeEndpoint
|
||||
}{token, expires.UnixMilli(), request.Channel, instance, t.endpoint})
|
||||
}
|
||||
|
||||
func (t *realtimeTickets) Consume(ctx context.Context, token, channel, instance string) (room.Principal, func(), error) {
|
||||
denied := func() (room.Principal, func(), error) { return room.Principal{}, nil, room.ErrUnauthorized }
|
||||
if len(token) != 43 {
|
||||
return denied()
|
||||
}
|
||||
key := sha256.Sum256([]byte(token))
|
||||
t.mu.Lock()
|
||||
ticket, found := t.pending[key]
|
||||
delete(t.pending, key)
|
||||
t.mu.Unlock()
|
||||
if !found || !time.Now().Before(ticket.expires) || string(ticket.channel) != channel || ticket.instance != instance {
|
||||
return denied()
|
||||
}
|
||||
owner, release, err := t.players.Acquire(ctx, ticket.principal.AccountID)
|
||||
if err != nil {
|
||||
return room.Principal{}, nil, err
|
||||
}
|
||||
if release == nil {
|
||||
return room.Principal{}, nil, errors.New("realtime player lease missing")
|
||||
}
|
||||
valid := false
|
||||
defer func() {
|
||||
if !valid {
|
||||
release()
|
||||
}
|
||||
}()
|
||||
if owner.Generation() != ticket.principal.Generation || t.Validate(ctx, ticket.principal) != nil {
|
||||
return denied()
|
||||
}
|
||||
if ticket.channel != room.Matching {
|
||||
view, err := t.rooms.View(ctx, ticket.principal, ticket.channel)
|
||||
if err != nil || view.InstanceID != instance {
|
||||
return denied()
|
||||
}
|
||||
} else if instance != t.bootID {
|
||||
return denied()
|
||||
}
|
||||
valid = true
|
||||
return ticket.principal, release, nil
|
||||
}
|
||||
|
||||
func (t *realtimeTickets) Validate(ctx context.Context, p room.Principal) error {
|
||||
return t.game.ValidatePrincipal(ctx, session.Principal{AccountID: p.AccountID, SessionID: p.SessionID, Generation: p.Generation})
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
eventplay "bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/room"
|
||||
accountstate "bd2server/internal/server/storage/account"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
func TestRoomResultSurvivesRestartAndClaimsRemainBoundToParticipants(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
directory := t.TempDir()
|
||||
store, err := shared.Open(directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if store != nil {
|
||||
if err := store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
r, err := openRoomResults(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
final := room.FinalResult{Clear: true, ScoreMilliseconds: 65432, View: room.View{InstanceID: "finished-party", Kind: room.Action, Selection: room.Selection{EventScheduleID: 100, MonsterID: 200}, StartTime: time.UnixMilli(1000), EndTime: time.UnixMilli(66432), Members: []room.MemberView{
|
||||
{Principal: room.Principal{AccountID: "alice", OwnerIndex: 1, SessionID: "old-a", Generation: 1}, NativeGUID: "alice-run", CharacterID: 11, Ready: true, Profile: room.Profile{UserInfo: wire.AppendString(nil, 4, "Alice")}},
|
||||
{Principal: room.Principal{AccountID: "bob", OwnerIndex: 2, SessionID: "old-b", Generation: 2}, NativeGUID: "bob-run", CharacterID: 12, Ready: true, Profile: room.Profile{UserInfo: wire.AppendString(nil, 4, "Bob")}},
|
||||
}}}
|
||||
rawFinal, err := json.Marshal(final)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Simulate a stop after the final commits but before its ranking is published.
|
||||
if err := store.Update(ctx, func(tx *shared.Tx) error {
|
||||
return tx.Put("room.results", final.View.InstanceID, rawFinal)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeRanking, err := r.PrepareResults(ctx, "alice", []eventplay.NativeRun{{InstanceID: "finished-party", GUID: "alice-run", Family: "Action"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := beforeRanking.Result(command.Context{Identity: command.Identity{AccountID: "alice"}}, eventplay.NativeRun{InstanceID: "finished-party", GUID: "alice-run", Family: "Action"}); !errors.Is(err, eventplay.ErrRoomNotFinished) {
|
||||
t.Fatalf("unpublished ranking exposed claimable result: %v", err)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store = nil
|
||||
store, err = shared.Open(directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err = openRoomResults(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alice := command.Context{Identity: command.Identity{AccountID: "alice", SessionID: "new-login"}}
|
||||
run := eventplay.NativeRun{InstanceID: "finished-party", GUID: "alice-run", Family: "Action", SessionID: "old-a", UID: 100, Monster: 200}
|
||||
resultFor := func(identity command.Context, run eventplay.NativeRun) (eventplay.NativeResult, error) {
|
||||
t.Helper()
|
||||
prepared, err := r.PrepareResults(ctx, identity.AccountID, []eventplay.NativeRun{run})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return prepared.Result(identity, run)
|
||||
}
|
||||
result, err := resultFor(alice, run)
|
||||
if err != nil || !result.Clear || result.Score != 65432 {
|
||||
t.Fatalf("committed completion unavailable after restart: %+v %v", result, err)
|
||||
}
|
||||
intruder := command.Context{Identity: command.Identity{AccountID: "mallory"}}
|
||||
if _, err := resultFor(intruder, run); !errors.Is(err, room.ErrUnauthorized) {
|
||||
t.Fatalf("nonparticipant read another player's result: %v", err)
|
||||
}
|
||||
if err := r.persist(ctx, final); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ranks, err := r.NativeRankings(alice, 100, 200, 2)
|
||||
if err != nil || len(ranks) != 1 || ranks[0].Score != 65432 || len(ranks[0].Members) != 2 {
|
||||
t.Fatalf("retry changed canonical team record: %+v %v", ranks, err)
|
||||
}
|
||||
source, err := accountstate.Open(t.TempDir() + "/state.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := source.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
publish := func(account, topic string, run eventplay.NativeRun) outbox.Pending {
|
||||
t.Helper()
|
||||
tx, err := source.BeginCommand(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload, err := json.Marshal(run)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := outbox.Publish(tx, account, command.Event{ID: topic + ":" + account, Topic: topic, Payload: payload}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := outbox.Read(tx, 32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, event := range pending {
|
||||
if event.Envelope.Source == account && event.Envelope.Event.Topic == topic {
|
||||
return event
|
||||
}
|
||||
}
|
||||
t.Fatal("committed source claim missing")
|
||||
return outbox.Pending{}
|
||||
}
|
||||
if err := r.Consume(ctx, publish("alice", "room.run.accepted", run)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claimA := publish("alice", "room.run.claimed", run)
|
||||
if err := r.Consume(ctx, claimA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Consume(ctx, claimA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bob := command.Context{Identity: command.Identity{AccountID: "bob", SessionID: "new-b"}}
|
||||
run.GUID = "bob-run"
|
||||
run.SessionID = "old-b"
|
||||
if _, err := resultFor(bob, run); err != nil {
|
||||
t.Fatalf("first player's claim removed second player's entitlement: %v", err)
|
||||
}
|
||||
if err := r.Consume(ctx, publish("bob", "room.run.accepted", run)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claimB := publish("bob", "room.run.claimed", run)
|
||||
if err := r.Consume(ctx, claimB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Consume(ctx, claimA); err != nil {
|
||||
t.Fatalf("claim replay failed after cleanup: %v", err)
|
||||
}
|
||||
if err := r.persist(ctx, final); err != nil {
|
||||
t.Fatalf("persistence retry failed after cleanup: %v", err)
|
||||
}
|
||||
if err := store.View(ctx, func(tx *shared.Tx) error {
|
||||
for _, bucket := range []string{"room.results", "room.ready", "room.runs", "room.claims"} {
|
||||
rows, err := tx.Scan(bucket, "", "", 128)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) != 0 {
|
||||
t.Errorf("fully claimed room retained %s payloads: %d", bucket, len(rows))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err = openRoomResults(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resultFor(bob, run); !errors.Is(err, eventplay.ErrRoomAbandoned) {
|
||||
t.Fatalf("fully acknowledged result retained: %v", err)
|
||||
}
|
||||
ranks, err = r.NativeRankings(alice, 100, 200, 2)
|
||||
if err != nil || len(ranks) != 1 {
|
||||
t.Fatalf("claim cleanup lost season record: %+v %v", ranks, err)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/gateway/transport"
|
||||
"bd2server/internal/server/platform/lifecycle"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
identitystore "bd2server/internal/server/storage/identity"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
@@ -27,6 +28,11 @@ func Serve(args []string) (serveErr error) {
|
||||
return err
|
||||
}
|
||||
defer clear(c.authRuntime.MasterKey)
|
||||
c.textModerator, err = textmoderation.New(c.gameRules.TextModeration, filepath.Dir(c.gameConfigPath))
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialize text moderation: %w", err)
|
||||
}
|
||||
defer func() { serveErr = errors.Join(serveErr, c.textModerator.Close()) }()
|
||||
seeds, err := loadSeeds(c)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -52,12 +58,21 @@ func Serve(args []string) (serveErr error) {
|
||||
if err := lockServerState(c.stateDirectory, c.gameRules.Story.StartPackID); err != nil {
|
||||
return err
|
||||
}
|
||||
factory := &PlayerFactory{options: c, design: design, seeds: seeds}
|
||||
shared, err := openSharedRuntime(context.Background(), c, design)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { serveErr = errors.Join(serveErr, shared.store.Close()) }()
|
||||
factory := &PlayerFactory{options: c, design: design, seeds: seeds, pvpSource: shared.pvp, shared: shared, wakeOutbox: shared.wake}
|
||||
if authStore != nil {
|
||||
factory.profiles = authStore
|
||||
}
|
||||
registry := newPlayerRegistry(factory, 15*time.Minute)
|
||||
defer func() { serveErr = errors.Join(serveErr, registry.Close(context.Background())) }()
|
||||
discovery := outboxDiscovery{factory: factory}
|
||||
if authStore != nil {
|
||||
discovery.accounts = authStore
|
||||
}
|
||||
var authenticator session.LoginAuthenticator
|
||||
if authService != nil {
|
||||
authenticator = authService
|
||||
@@ -67,7 +82,6 @@ func Serve(args []string) (serveErr error) {
|
||||
return err
|
||||
}
|
||||
|
||||
dispatcher := transport.Bootstrap{Config: c.bootstrap}
|
||||
var authHandler http.Handler
|
||||
if authService != nil {
|
||||
authHandler = authService.Handler()
|
||||
@@ -78,10 +92,28 @@ func Serve(args []string) (serveErr error) {
|
||||
return fmt.Errorf("create server instance identity: %w", err)
|
||||
}
|
||||
instanceID := hex.EncodeToString(instanceBytes)
|
||||
realtime, err := openRealtime(c, registry, game, shared, instanceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { serveErr = errors.Join(serveErr, realtime.close()) }()
|
||||
if err := shared.start(registry, discovery); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { serveErr = errors.Join(serveErr, shared.stop()) }()
|
||||
var realtimeDone <-chan error
|
||||
var realtimeTickets http.Handler
|
||||
if realtime != nil {
|
||||
realtime.start()
|
||||
realtimeDone = realtime.done
|
||||
realtimeTickets = realtime.tickets
|
||||
}
|
||||
dispatcher := transport.Bootstrap{Config: c.bootstrap}
|
||||
handler := transport.HTTP{
|
||||
Dispatcher: dispatcher, Raw: game, Authentication: c.authentication,
|
||||
AuthenticationHandler: authHandler, ResourcePolicy: c.publicResources,
|
||||
CommerceManifest: func() any { return design.cashCatalog.Manifest() }, Availability: availability, InstanceID: instanceID,
|
||||
CommerceManifest: func() any { return design.cashCatalog.Manifest() }, Availability: availability, InstanceID: instanceID, RealtimeTickets: realtimeTickets,
|
||||
StoryCheckpoints: storyCheckpoints{game: game, players: registry},
|
||||
}.Handler()
|
||||
server := &http.Server{
|
||||
Addr: c.listen,
|
||||
@@ -91,6 +123,7 @@ func Serve(args []string) (serveErr error) {
|
||||
WriteTimeout: 20 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
defer func() { _ = server.Close() }()
|
||||
slog.Info("BD2 server listening", "address", c.listen, "instance_id", instanceID, "server_version", c.versions.ServerVersion, "game_version", c.bootstrap.Version, "bundle", c.bootstrap.BundleVer, "resourceMode", c.publicResources.Mode, "gameData", c.verifiedGameData.ArchivePath, "gameDataEntries", c.verifiedGameData.EntryCount, "accountSeed", c.accountSeed)
|
||||
serveResult := make(chan error, 1)
|
||||
go func() { serveResult <- server.ListenAndServe() }()
|
||||
@@ -98,6 +131,8 @@ func Serve(args []string) (serveErr error) {
|
||||
signal.Notify(signals, lifecycle.ShutdownSignals()...)
|
||||
defer signal.Stop(signals)
|
||||
select {
|
||||
case err := <-realtimeDone:
|
||||
return fmt.Errorf("realtime listener stopped: %w", err)
|
||||
case err := <-serveResult:
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/fishing"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
type publicFishing struct {
|
||||
Account string
|
||||
Owner uint64
|
||||
Name string
|
||||
Profile fishing.Profile
|
||||
CollectionCount uint64
|
||||
}
|
||||
|
||||
type directoryRecord struct {
|
||||
Version uint64
|
||||
Player publicFishing
|
||||
}
|
||||
type publicDirectory struct {
|
||||
store *shared.Store
|
||||
players sync.Map
|
||||
}
|
||||
|
||||
func openPublicDirectory(ctx context.Context, store *shared.Store) (*publicDirectory, error) {
|
||||
d := &publicDirectory{store: store}
|
||||
err := store.View(ctx, func(tx *shared.Tx) error {
|
||||
for cursor := ""; ; {
|
||||
rows, err := tx.Scan("player.directory", "", cursor, 256)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, row := range rows {
|
||||
var record directoryRecord
|
||||
if err := json.Unmarshal(row.Value, &record); err != nil {
|
||||
return err
|
||||
}
|
||||
if record.Player.Owner == 0 || record.Version == 0 {
|
||||
return errors.New("invalid public player directory")
|
||||
}
|
||||
d.players.Store(record.Player.Owner, record)
|
||||
cursor = row.Key
|
||||
}
|
||||
}
|
||||
})
|
||||
return d, err
|
||||
}
|
||||
|
||||
func (p *playerAssembly) publishDirectory(ctx command.Context) error {
|
||||
if p.shared == nil {
|
||||
return nil
|
||||
}
|
||||
owner, err := p.ProfileOwner(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
next := directoryRecord{Player: publicFishing{Account: ctx.AccountID, Owner: owner, Name: p.nicknameService.CurrentNickname(), Profile: p.fishingService.Profile(), CollectionCount: p.fishingService.CollectionCount()}}
|
||||
raw, found, err := ctx.State.LoadEntry("directory", "publication", "current")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
var old directoryRecord
|
||||
if err := json.Unmarshal(raw, &old); err != nil {
|
||||
return err
|
||||
}
|
||||
if reflect.DeepEqual(old.Player, next.Player) {
|
||||
return nil
|
||||
}
|
||||
next.Version = old.Version
|
||||
}
|
||||
if next.Version == ^uint64(0) {
|
||||
return errors.New("public directory version exhausted")
|
||||
}
|
||||
next.Version++
|
||||
raw, err = json.Marshal(next)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Publish(command.Event{ID: fmt.Sprintf("directory:%d", next.Version), Topic: "player.directory", Payload: raw}); err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.State.PutEntry("directory", "publication", "current", raw)
|
||||
}
|
||||
|
||||
func (d *publicDirectory) consume(ctx context.Context, event outbox.Pending) error {
|
||||
var next directoryRecord
|
||||
if err := json.Unmarshal(event.Envelope.Event.Payload, &next); err != nil {
|
||||
return err
|
||||
}
|
||||
if next.Version == 0 || next.Player.Account != event.Envelope.Source || next.Player.Owner == 0 {
|
||||
return errors.New("public player directory source mismatch")
|
||||
}
|
||||
err := d.store.Consume(ctx, event, func(tx *shared.Tx, _ outbox.Envelope) error {
|
||||
key := strconv.FormatUint(next.Player.Owner, 10)
|
||||
raw, found, err := tx.Get("player.directory", key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
var old directoryRecord
|
||||
if err := json.Unmarshal(raw, &old); err != nil {
|
||||
return err
|
||||
}
|
||||
if old.Player.Account != next.Player.Account {
|
||||
return errors.New("public player ownership conflict")
|
||||
}
|
||||
if old.Version >= next.Version {
|
||||
next = old
|
||||
return nil
|
||||
}
|
||||
}
|
||||
payload, err := json.Marshal(next)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Put("player.directory", key, payload)
|
||||
})
|
||||
if err == nil {
|
||||
d.players.Store(next.Player.Owner, next)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *publicDirectory) fishing(_ command.Context, owner uint64) (string, fishing.Profile, uint64, error) {
|
||||
value, ok := d.players.Load(owner)
|
||||
if !ok {
|
||||
return "", fishing.Profile{}, 0, errors.New("public player not found")
|
||||
}
|
||||
p := value.(directoryRecord).Player
|
||||
p.Profile.Maps = append([]uint64(nil), p.Profile.Maps...)
|
||||
return p.Name, p.Profile, p.CollectionCount, nil
|
||||
}
|
||||
@@ -0,0 +1,663 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
var errGuildConfirmationUnavailable = errors.New("guild confirmation unavailable")
|
||||
|
||||
type guildConfirmationFailure struct {
|
||||
social.Store
|
||||
failNext atomic.Bool
|
||||
}
|
||||
|
||||
func (s *guildConfirmationFailure) Update(ctx context.Context, apply func(social.Tx) error) error {
|
||||
if s.failNext.CompareAndSwap(true, false) {
|
||||
return errGuildConfirmationUnavailable
|
||||
}
|
||||
return s.Store.Update(ctx, apply)
|
||||
}
|
||||
|
||||
type guildConfirmationObserver struct{ store *guildConfirmationFailure }
|
||||
|
||||
func (g guildConfirmationObserver) BeforeDispatch(command.Context, string, []byte) error { return nil }
|
||||
func (g guildConfirmationObserver) AfterDispatch(_ command.Context, path string, _, _ []byte) ([]byte, error) {
|
||||
if path == "/GuildCreate" {
|
||||
g.store.failNext.Store(true)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type guildGameplay struct {
|
||||
t *testing.T
|
||||
factory *PlayerFactory
|
||||
owner *playerInstance
|
||||
runtime *player.Runtime
|
||||
account string
|
||||
seq uint64
|
||||
}
|
||||
|
||||
func (g *guildGameplay) open() {
|
||||
g.t.Helper()
|
||||
var err error
|
||||
g.owner, err = g.factory.open(g.account)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
g.runtime, err = player.New(g.account, g.owner, player.Limits{})
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func (g *guildGameplay) close() {
|
||||
g.t.Helper()
|
||||
if g.runtime != nil {
|
||||
if err := g.runtime.Close(context.Background()); err != nil {
|
||||
g.t.Error(err)
|
||||
}
|
||||
g.runtime = nil
|
||||
g.owner = nil
|
||||
}
|
||||
}
|
||||
func (g *guildGameplay) execute(c player.Command) (player.Reply, error) {
|
||||
g.t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
f, err := g.runtime.Submit(ctx, c)
|
||||
if err != nil {
|
||||
return player.Reply{}, err
|
||||
}
|
||||
return f.Wait(ctx)
|
||||
}
|
||||
func (g *guildGameplay) balance() assets.Currency {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := tx.Rollback(); err != nil {
|
||||
g.t.Error(err)
|
||||
}
|
||||
}()
|
||||
return g.owner.assembly.wallet.Snapshot(command.Context{State: tx})
|
||||
}
|
||||
func (g *guildGameplay) reconcile(r social.Reservation) {
|
||||
g.t.Helper()
|
||||
raw, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
_, err = g.execute(player.Command{Identity: command.Identity{AccountID: g.account, SessionID: "guild-recovery", RequestID: r.ID}, Digest: sha256.Sum256(raw), System: &player.SystemRequest{Kind: player.ReconcileSocial, Body: raw}})
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func (g *guildGameplay) pending() social.Reservation {
|
||||
g.t.Helper()
|
||||
ops, _, err := g.factory.shared.guild.PendingOperations(context.Background(), "", 128)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
for _, op := range ops {
|
||||
if op.ActorAccount == g.account {
|
||||
return op
|
||||
}
|
||||
}
|
||||
g.t.Fatal("expected recoverable guild operation")
|
||||
return social.Reservation{}
|
||||
}
|
||||
func (g *guildGameplay) member(guildID uint64) {
|
||||
g.t.Helper()
|
||||
account, err := g.factory.shared.guild.Account(context.Background(), g.account)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
if account.GuildID != guildID {
|
||||
g.t.Fatalf("membership = %d, want %d", account.GuildID, guildID)
|
||||
}
|
||||
if guildID != 0 {
|
||||
guild, err := g.factory.shared.guild.Guild(context.Background(), guildID)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
member, exists := guild.Members[g.account]
|
||||
if !exists || member.Role != social.Admin || len(guild.Members) != 1 {
|
||||
g.t.Fatalf("created guild membership is wrong: %+v", guild)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func seedGuildQualification(t *testing.T, owner *playerInstance) {
|
||||
t.Helper()
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := tx.Rollback(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
c := command.Context{Identity: command.Identity{AccountID: owner.accountID}, State: tx}
|
||||
rule := owner.factory.design.guild.Open
|
||||
grant := owner.factory.design.guild.Guild.CreateCost
|
||||
grant.Count *= 4
|
||||
if _, err = owner.assembly.eventEconomy.Apply(c, "guild-fixture-budget", nil, []gamedata.Reward{grant}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rule.TicketID != 0 {
|
||||
if _, err = owner.assembly.ownedItems.GrantOnce(c, "guild-fixture-unlock", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err = owner.assembly.missionService.EnsurePersisted(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := tx.Load("missions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var state map[string]json.RawMessage
|
||||
if err = json.Unmarshal(raw, &state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var claimed []string
|
||||
if err = json.Unmarshal(state["claimed"], &claimed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys := make([]gamedata.AchievementKey, 0, len(owner.factory.design.missionDesign.Achievements))
|
||||
for key := range owner.factory.design.missionDesign.Achievements {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
a, b := keys[i], keys[j]
|
||||
if a.ContentsGroup != b.ContentsGroup {
|
||||
return a.ContentsGroup < b.ContentsGroup
|
||||
}
|
||||
if a.GroupID != b.GroupID {
|
||||
return a.GroupID < b.GroupID
|
||||
}
|
||||
return a.ID < b.ID
|
||||
})
|
||||
var experience uint64
|
||||
for _, key := range keys {
|
||||
entry := fmt.Sprintf("achievement:%d/%d/%d", key.ContentsGroup, key.GroupID, key.ID)
|
||||
if slices.Contains(claimed, entry) {
|
||||
experience += owner.factory.design.missionDesign.Achievements[key].AddExp
|
||||
}
|
||||
}
|
||||
for _, key := range keys {
|
||||
if owner.factory.design.levelDesign.Level(experience) >= rule.SquadLevel {
|
||||
break
|
||||
}
|
||||
entry := fmt.Sprintf("achievement:%d/%d/%d", key.ContentsGroup, key.GroupID, key.ID)
|
||||
if slices.Contains(claimed, entry) {
|
||||
continue
|
||||
}
|
||||
claimed = append(claimed, entry)
|
||||
experience += owner.factory.design.missionDesign.Achievements[key].AddExp
|
||||
}
|
||||
if owner.factory.design.levelDesign.Level(experience) < rule.SquadLevel {
|
||||
t.Fatal("current GameData has insufficient achievement experience for guild unlock")
|
||||
}
|
||||
state["claimed"], err = json.Marshal(claimed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err = json.Marshal(state)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Save("missions", raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = owner.Recover(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func guildCreateCommand(t *testing.T, factory *PlayerFactory, account, id, name string, seq uint64) player.Command {
|
||||
t.Helper()
|
||||
var flags, emblems []uint64
|
||||
for id := range factory.design.guild.Guild.Flags {
|
||||
flags = append(flags, id)
|
||||
}
|
||||
for id := range factory.design.guild.Guild.Emblems {
|
||||
emblems = append(emblems, id)
|
||||
}
|
||||
slices.Sort(flags)
|
||||
slices.Sort(emblems)
|
||||
if len(flags) == 0 || len(emblems) == 0 {
|
||||
t.Fatal("current GameData has no guild icons")
|
||||
}
|
||||
body := appScalar(1, seq)
|
||||
body = append(body, appMessage(2, []byte(name))...)
|
||||
body = append(body, appScalar(3, emblems[0]*100000+flags[0])...)
|
||||
body = append(body, appMessage(4, []byte("#FFFFFFFF"))...)
|
||||
body = append(body, appMessage(5, []byte("Guild integration"))...)
|
||||
body = append(body, appScalar(6, uint64(social.OpenJoin))...)
|
||||
return registryCommand(account, id, "/GuildCreate", body)
|
||||
}
|
||||
func guildIDFromCreate(t *testing.T, reply player.Reply) uint64 {
|
||||
t.Helper()
|
||||
if len(reply.Responses) != 1 || reply.Responses[0].PacketCode != 296 {
|
||||
t.Fatalf("invalid GuildCreate response: %+v", reply)
|
||||
}
|
||||
info := appRows(reply.Responses[0].Body, 1)
|
||||
if len(info) != 1 {
|
||||
t.Fatal("GuildCreate lacks guild info")
|
||||
}
|
||||
base := appRows(info[0], 1)
|
||||
if len(base) != 1 {
|
||||
t.Fatal("guild info lacks base info")
|
||||
}
|
||||
id := appValue(base[0], 1)
|
||||
if id == 0 {
|
||||
t.Fatal("created guild has no identity")
|
||||
}
|
||||
return id
|
||||
}
|
||||
func expectedGuildCharge(t *testing.T, factory *PlayerFactory, before assets.Currency) assets.Currency {
|
||||
t.Helper()
|
||||
cost := factory.design.guild.Guild.CreateCost
|
||||
switch cost.Type {
|
||||
case 3:
|
||||
if before.FreeJewelry < cost.Count {
|
||||
t.Fatal("fixture budget too small")
|
||||
}
|
||||
before.FreeJewelry -= cost.Count
|
||||
case 2:
|
||||
before.Jewelry -= cost.Count
|
||||
case 4:
|
||||
before.Gold -= cost.Count
|
||||
default:
|
||||
t.Fatalf("unsupported current GD guild currency %d", cost.Type)
|
||||
}
|
||||
return before
|
||||
}
|
||||
|
||||
func TestSharedGuildGameplayTransactionsAndRecovery(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
failures := &guildConfirmationFailure{Store: socialStore{shared.store}}
|
||||
shared.guild, err = social.New(failures, factory.design.guild)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factory.shared, factory.pvpSource = shared, shared.pvp
|
||||
|
||||
t.Run("rollback recovers absent receipt then create charges once", func(t *testing.T) {
|
||||
g := &guildGameplay{t: t, factory: factory, account: accounts[0]}
|
||||
g.open()
|
||||
t.Cleanup(g.close)
|
||||
seedGuildQualification(t, g.owner)
|
||||
before := g.balance()
|
||||
failed := guildCreateCommand(t, factory, g.account, "guild-batch-fail", "Rollback", 1)
|
||||
failed.Requests = append(failed.Requests, player.Request{Path: "/GuildIntegrationUnknownPacket", Body: appScalar(1, 2)})
|
||||
failed.Digest = sha256.Sum256([]byte("guild-batch-rollback"))
|
||||
if _, err := g.execute(failed); err == nil {
|
||||
t.Fatal("batch with unimplemented packet unexpectedly committed")
|
||||
}
|
||||
if got := g.balance(); got != before {
|
||||
t.Fatalf("failed batch charged guild creation: %+v want %+v", got, before)
|
||||
}
|
||||
g.member(0)
|
||||
reservation := g.pending()
|
||||
g.close()
|
||||
g.open()
|
||||
g.reconcile(reservation)
|
||||
status, err := shared.guild.Reservation(context.Background(), reservation.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status.Status != social.Cancelled {
|
||||
t.Fatalf("absent committed receipt was not cancelled: %s", status.Status)
|
||||
}
|
||||
if _, err := shared.guild.Guild(context.Background(), reservation.GuildID); !errors.Is(err, social.ErrNotFound) {
|
||||
t.Fatalf("rolled back guild remained visible: %v", err)
|
||||
}
|
||||
create := guildCreateCommand(t, factory, g.account, "guild-create-ok", "Committed", 3)
|
||||
reply, err := g.execute(create)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gid := guildIDFromCreate(t, reply)
|
||||
g.member(gid)
|
||||
want := expectedGuildCharge(t, factory, before)
|
||||
if got := g.balance(); got != want {
|
||||
t.Fatalf("guild create charge = %+v want %+v", got, want)
|
||||
}
|
||||
duplicate, err := g.execute(create)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(duplicate.Responses[0].Body, reply.Responses[0].Body) {
|
||||
t.Fatal("duplicate changed guild response")
|
||||
}
|
||||
if got := g.balance(); got != want {
|
||||
t.Fatal("duplicate guild create charged twice")
|
||||
}
|
||||
g.close()
|
||||
g.open()
|
||||
if _, err = g.execute(create); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g.member(gid)
|
||||
if got := g.balance(); got != want {
|
||||
t.Fatal("durable command replay charged twice")
|
||||
}
|
||||
})
|
||||
t.Run("committed receipt confirms after player reload", func(t *testing.T) {
|
||||
g := &guildGameplay{t: t, factory: factory, account: accounts[1]}
|
||||
g.open()
|
||||
t.Cleanup(g.close)
|
||||
seedGuildQualification(t, g.owner)
|
||||
before := g.balance()
|
||||
g.owner.assembly.observers = append(g.owner.assembly.observers, guildConfirmationObserver{store: failures})
|
||||
create := guildCreateCommand(t, factory, g.account, "guild-confirm-unavailable", "Recovered", 1)
|
||||
if _, err := g.execute(create); !errors.Is(err, errGuildConfirmationUnavailable) {
|
||||
t.Fatalf("expected post-commit confirmation failure, got %v", err)
|
||||
}
|
||||
want := expectedGuildCharge(t, factory, before)
|
||||
if got := g.balance(); got != want {
|
||||
t.Fatalf("player transaction was not committed before confirmation failed: %+v", got)
|
||||
}
|
||||
g.member(0)
|
||||
reservation := g.pending()
|
||||
g.close()
|
||||
g.open()
|
||||
g.reconcile(reservation)
|
||||
g.member(reservation.GuildID)
|
||||
status, err := shared.guild.Reservation(context.Background(), reservation.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status.Status != social.Confirmed {
|
||||
t.Fatalf("durable receipt was not confirmed: %s", status.Status)
|
||||
}
|
||||
replay, err := g.execute(create)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if id := guildIDFromCreate(t, replay); id != reservation.GuildID {
|
||||
t.Fatalf("replayed guild %d != recovered %d", id, reservation.GuildID)
|
||||
}
|
||||
if got := g.balance(); got != want {
|
||||
t.Fatal("recovery or replay charged twice")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type rankingStorageGate struct {
|
||||
ranking.Store
|
||||
blocked chan struct{}
|
||||
armed atomic.Bool
|
||||
}
|
||||
|
||||
func (s *rankingStorageGate) Update(ctx context.Context, write func(ranking.Tx) error) error {
|
||||
if s.armed.CompareAndSwap(true, false) {
|
||||
close(s.blocked)
|
||||
}
|
||||
return s.Store.Update(ctx, write)
|
||||
}
|
||||
|
||||
func TestSharedPVPReadsContinueWhileProjectionWaitsForStorage(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
state, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := state.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
gate := &rankingStorageGate{Store: rankingStore{state.store}, blocked: make(chan struct{})}
|
||||
projection, err := ranking.NewPVP(context.Background(), gate, factory.design.pvp.Design, factory.design.pvp.Seasons)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
season := factory.design.pvp.Seasons[0]
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
holderDone := make(chan error, 1)
|
||||
go func() {
|
||||
holderDone <- state.store.Update(ctx, func(*shared.Tx) error { close(entered); <-release; return nil })
|
||||
}()
|
||||
<-entered
|
||||
released := false
|
||||
projectionDone := make(chan error, 1)
|
||||
defer func() {
|
||||
if !released {
|
||||
close(release)
|
||||
}
|
||||
if err := <-holderDone; err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := <-projectionDone; err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
publication := pvp.DefensePublished{Version: 1, Defense: pvp.PublishedSnapshot{Profile: pvp.Profile{OwnerID: accounts[0], OwnerIndex: 1}, Mode: season.Mode, Season: season.ID, Version: 1}}
|
||||
payload, err := json.Marshal(publication)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gate.armed.Store(true)
|
||||
go func() {
|
||||
projectionDone <- projection.Consume(ctx, accounts[0], command.Event{ID: "pvp-read-lock-probe", Topic: "pvp.defense.published", Payload: payload})
|
||||
}()
|
||||
select {
|
||||
case <-gate.blocked:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("projection never reached its storage transaction")
|
||||
}
|
||||
readDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := projection.Personal(pvp.ProgressQuery{Mode: season.Mode, Season: season.ID, Owner: accounts[1]})
|
||||
readDone <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-readDone:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("published PVP reads waited for shared storage commit")
|
||||
}
|
||||
close(release)
|
||||
released = true
|
||||
}
|
||||
|
||||
func (g *guildGameplay) pvpCall(path string, fields []byte) []byte {
|
||||
g.t.Helper()
|
||||
g.seq++
|
||||
request := registryCommand(g.account, fmt.Sprintf("pvp-%d", g.seq), path, append(appScalar(1, g.seq), fields...))
|
||||
if path == "/LoginUser" {
|
||||
request.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
|
||||
}
|
||||
reply, err := g.execute(request)
|
||||
if err != nil {
|
||||
g.t.Fatalf("%s: %v", path, err)
|
||||
}
|
||||
if len(reply.Responses) != 1 {
|
||||
g.t.Fatalf("%s returned %d responses", path, len(reply.Responses))
|
||||
}
|
||||
return reply.Responses[0].Body
|
||||
}
|
||||
func (g *guildGameplay) drainPVP() {
|
||||
g.t.Helper()
|
||||
g.seq++
|
||||
request := player.Command{Identity: command.Identity{AccountID: g.account, SessionID: "pvp-delivery", RequestID: fmt.Sprint(g.seq)}, System: &player.SystemRequest{Kind: player.ReadOutbox}}
|
||||
reply, err := g.execute(request)
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
var pending []outbox.Pending
|
||||
if err = json.Unmarshal(reply.Responses[0].Body, &pending); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
for _, event := range pending {
|
||||
if err = g.factory.shared.Consume(context.Background(), event); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
raw, err := json.Marshal(struct {
|
||||
Key string `json:"key"`
|
||||
Digest string `json:"digest"`
|
||||
}{event.Key, event.Digest})
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
g.seq++
|
||||
request.Identity.RequestID = fmt.Sprint(g.seq)
|
||||
request.System = &player.SystemRequest{Kind: player.AcknowledgeOutbox, Body: raw}
|
||||
request.Digest = sha256.Sum256(raw)
|
||||
if _, err = g.execute(request); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
func (g *guildGameplay) ownedPVPDeck() ([]byte, uint64) {
|
||||
g.t.Helper()
|
||||
tx, err := g.owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := tx.Rollback(); err != nil {
|
||||
g.t.Error(err)
|
||||
}
|
||||
}()
|
||||
ctx := command.Context{State: tx, Identity: command.Identity{AccountID: g.account}}
|
||||
for _, char := range g.owner.assembly.worldService.CharacterService().All(ctx) {
|
||||
if int64(char.ExpiryTime) > 0 {
|
||||
continue
|
||||
}
|
||||
for _, costume := range g.owner.assembly.collection.Costumes() {
|
||||
if costume.UseChar == char.InvenIndex {
|
||||
return append(appScalar(1, char.InvenIndex), appScalar(4, costume.InvenIndex)...), char.InvenIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
g.t.Fatal("current starter contains no permanent owned PVP character")
|
||||
return nil, 0
|
||||
}
|
||||
func TestNativePVPGameplayUsesOwnedSnapshotsAndTickets(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
state, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := state.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.shared, factory.pvpSource = state, state.pvp
|
||||
attacker := &guildGameplay{t: t, factory: factory, account: accounts[0]}
|
||||
defender := &guildGameplay{t: t, factory: factory, account: accounts[1]}
|
||||
attacker.open()
|
||||
defender.open()
|
||||
t.Cleanup(attacker.close)
|
||||
t.Cleanup(defender.close)
|
||||
login := appRows(attacker.pvpCall("/LoginUser", nil), 1)
|
||||
if len(login) != 1 {
|
||||
t.Fatal("login user missing")
|
||||
}
|
||||
if got := appValue(login[0], 57); got != factory.design.pvp.Design.Presets.BaseCount {
|
||||
t.Fatalf("Colosseum preset slots=%d want %d", got, factory.design.pvp.Design.Presets.BaseCount)
|
||||
}
|
||||
if got := appValue(login[0], 16); got != factory.design.pvp.Design.FreeMirrorTickets {
|
||||
t.Fatalf("free mirror ticket initial grant=%d", got)
|
||||
}
|
||||
attackDeck, character := attacker.ownedPVPDeck()
|
||||
defenseDeck, _ := defender.ownedPVPDeck()
|
||||
attacker.pvpCall("/PvpBattleDeckSave", append(appScalar(2, 0), appMessage(3, attackDeck)...))
|
||||
defender.pvpCall("/PvpBattleDeckSave", append(appScalar(2, 1), appMessage(3, defenseDeck)...))
|
||||
defender.drainPVP()
|
||||
mirror := attacker.pvpCall("/PvpBattleMatching", appScalar(2, 1))
|
||||
opponent, err := factory.profiles.GameIdentity(context.Background(), defender.account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if appValue(mirror, 4) != uint64(opponent.OwnerIndex) {
|
||||
t.Fatal("matching did not use the other account's published defense")
|
||||
}
|
||||
attacker.pvpCall("/PvpBattleEnd", append(appScalar(2, 1), appScalar(3, character)...))
|
||||
attacker.drainPVP()
|
||||
login = appRows(attacker.pvpCall("/LoginUser", nil), 1)
|
||||
if got, want := appValue(login[0], 16), factory.design.pvp.Design.FreeMirrorTickets-factory.design.pvp.Design.Mirror.TicketCost; got != want {
|
||||
t.Fatalf("mirror battle ticket debit=%d want %d", got, want)
|
||||
}
|
||||
history := attacker.pvpCall("/PvpBattleHistory", nil)
|
||||
if appValue(history, 5) != 1 || len(appRows(history, 1)) != 1 {
|
||||
t.Fatal("native mirror battle did not settle attack history")
|
||||
}
|
||||
attacker.pvpCall("/ColosseumDeckSave", appMessage(2, attackDeck))
|
||||
defender.pvpCall("/ColosseumDeckSave", appMessage(2, defenseDeck))
|
||||
defender.drainPVP()
|
||||
info := attacker.pvpCall("/ColosseumUserInfo", nil)
|
||||
season := appValue(info, 1)
|
||||
amount, err := factory.design.pvp.Design.ColosseumRule(season, 9)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
login = appRows(attacker.pvpCall("/LoginUser", nil), 1)
|
||||
if len(amount) != 1 || appValue(login[0], 58) != amount[0] {
|
||||
t.Fatal("arena free tickets do not match current season charge rule")
|
||||
}
|
||||
match := attacker.pvpCall("/ColosseumBattleMatching", nil)
|
||||
enemies := appRows(match, 3)
|
||||
if len(enemies) == 0 || appValue(enemies[0], 1) != uint64(opponent.OwnerIndex) {
|
||||
t.Fatal("arena did not match published opponent")
|
||||
}
|
||||
attacker.pvpCall("/ColosseumBattleStart", appScalar(2, uint64(opponent.OwnerIndex)))
|
||||
attacker.pvpCall("/ColosseumBattleEnd", appScalar(2, 1))
|
||||
attacker.drainPVP()
|
||||
history = attacker.pvpCall("/ColosseumBattleHistory", nil)
|
||||
if appValue(history, 5) != 1 || len(appRows(history, 1)) != 1 {
|
||||
t.Fatal("native arena battle did not settle attack history")
|
||||
}
|
||||
login = appRows(attacker.pvpCall("/LoginUser", nil), 1)
|
||||
want := amount[0]
|
||||
if want > 0 {
|
||||
want--
|
||||
}
|
||||
if got := appValue(login[0], 58); got != want {
|
||||
t.Fatalf("arena battle ticket debit=%d want %d", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/pvp"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
"context"
|
||||
)
|
||||
|
||||
type rankingStore struct{ store *shared.Store }
|
||||
type rankingTx struct{ *shared.Tx }
|
||||
|
||||
func (s rankingStore) View(ctx context.Context, read func(ranking.Tx) error) error {
|
||||
return s.store.View(ctx, func(tx *shared.Tx) error { return read(rankingTx{tx}) })
|
||||
}
|
||||
func (s rankingStore) Update(ctx context.Context, write func(ranking.Tx) error) error {
|
||||
return s.store.Update(ctx, func(tx *shared.Tx) error { return write(rankingTx{tx}) })
|
||||
}
|
||||
func (t rankingTx) Scan(bucket, prefix, after string, limit int) ([]ranking.Entry, error) {
|
||||
entries, err := t.Tx.Scan(bucket, prefix, after, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]ranking.Entry, len(entries))
|
||||
for i, row := range entries {
|
||||
out[i] = ranking.Entry{Key: row.Key, Value: row.Value}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func newSharedPVP(ctx context.Context, store *shared.Store, design *gamedata.PvpDesign, seasons []pvp.Season) (*ranking.PVP, error) {
|
||||
return ranking.NewPVP(ctx, rankingStore{store}, design, seasons)
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/runtime/delivery"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
type sharedRuntime struct {
|
||||
directory *publicDirectory
|
||||
rooms *roomResults
|
||||
store *shared.Store
|
||||
pvp *ranking.PVP
|
||||
guild *social.Owner
|
||||
friends *social.Friends
|
||||
delivery atomic.Pointer[delivery.Dispatcher]
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func openSharedRuntime(ctx context.Context, c *configuration, design *designCatalog) (*sharedRuntime, error) {
|
||||
store, err := shared.Open(filepath.Join(c.stateDirectory, "shared"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pvp, err := newSharedPVP(ctx, store, design.pvp.Design, design.pvp.Seasons)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
guild, err := social.New(socialStore{store}, design.guild)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
friends, err := social.NewFriends(socialStore{store}, design.friends)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
rooms, err := openRoomResults(ctx, store)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
directory, err := openPublicDirectory(ctx, store)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
return &sharedRuntime{store: store, pvp: pvp, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) wake(account string) {
|
||||
if d := s.delivery.Load(); d != nil {
|
||||
d.Wake(account)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error {
|
||||
if _, _, err := outbox.Validate(event); err != nil {
|
||||
return err
|
||||
}
|
||||
if event.Envelope.Event.Topic == "fishing.projection" {
|
||||
return s.rooms.updateFishing(ctx, event)
|
||||
}
|
||||
if event.Envelope.Event.Topic == "player.directory" {
|
||||
return s.directory.consume(ctx, event)
|
||||
}
|
||||
if event.Envelope.Event.Topic == "friend.directory" {
|
||||
var profile social.FriendProfile
|
||||
if err := json.Unmarshal(event.Envelope.Event.Payload, &profile); err != nil {
|
||||
return err
|
||||
}
|
||||
if profile.AccountID != event.Envelope.Source {
|
||||
return social.ErrPermission
|
||||
}
|
||||
return s.friends.Publish(ctx, profile)
|
||||
}
|
||||
if event.Envelope.Event.Topic == "chat.policy" {
|
||||
return s.consumeChatPolicy(ctx, event.Envelope.Source, event.Envelope.Event.Payload)
|
||||
}
|
||||
if strings.HasPrefix(event.Envelope.Event.Topic, "room.run.") && s.rooms != nil {
|
||||
return s.rooms.Consume(ctx, event)
|
||||
}
|
||||
if strings.HasPrefix(event.Envelope.Event.Topic, "pvp.") {
|
||||
return s.pvp.Consume(ctx, event.Envelope.Source, event.Envelope.Event)
|
||||
}
|
||||
if event.Envelope.Event.Topic == "social.confirm" {
|
||||
var proof social.CommitProof
|
||||
if err := json.Unmarshal(event.Envelope.Event.Payload, &proof); err != nil {
|
||||
return err
|
||||
}
|
||||
if proof.ActorAccount != event.Envelope.Source || proof.OperationID != event.Envelope.Event.ID {
|
||||
return errors.New("guild confirmation source mismatch")
|
||||
}
|
||||
_, err := s.guild.Confirm(ctx, proof)
|
||||
return err
|
||||
}
|
||||
if event.Envelope.Event.Topic == "social.raid_settle" {
|
||||
var result social.RaidResult
|
||||
if err := json.Unmarshal(event.Envelope.Event.Payload, &result); err != nil {
|
||||
return err
|
||||
}
|
||||
if result.AccountID != event.Envelope.Source || result.ResultID != event.Envelope.Event.ID {
|
||||
return errors.New("guild raid result source mismatch")
|
||||
}
|
||||
_, err := s.guild.SettleRaid(ctx, result)
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("unsupported shared event topic %q", event.Envelope.Event.Topic)
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) start(registry *playerRegistry, discovery outboxDiscovery) error {
|
||||
d, err := delivery.New(registry, s, discovery)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.delivery.Store(d)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s.cancel, s.done = cancel, make(chan struct{})
|
||||
go func() {
|
||||
defer close(s.done)
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if err := s.settle(ctx, registry, discovery); err != nil && ctx.Err() == nil {
|
||||
slog.Warn("shared settlement deferred", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) stop() error {
|
||||
if s.cancel != nil {
|
||||
s.cancel()
|
||||
<-s.done
|
||||
}
|
||||
if d := s.delivery.Load(); d != nil {
|
||||
return d.Close(context.Background())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) settle(ctx context.Context, registry *playerRegistry, discovery outboxDiscovery) error {
|
||||
if err := s.closeExpiredRaids(ctx, registry); err != nil {
|
||||
return err
|
||||
}
|
||||
operations, _, err := s.guild.PendingOperations(ctx, "", 128)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, operation := range operations {
|
||||
raw, err := json.Marshal(operation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = executePlayerSystem(ctx, registry, operation.ActorAccount, player.ReconcileSocial, raw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for cursor := ""; ; {
|
||||
guilds, next, err := s.guild.DueDeletions(ctx, time.Now().UnixMilli(), cursor, 128)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, guild := range guilds {
|
||||
if err := s.guild.FinalizeDeletion(ctx, guild, time.Now().UnixMilli()); err != nil && !errors.Is(err, social.ErrPending) && !errors.Is(err, social.ErrIneligible) && !errors.Is(err, social.ErrSeasonLocked) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(guilds) < 128 || next == cursor {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
for _, season := range registry.factory.design.pvp.Seasons {
|
||||
if uint64(time.Now().UnixMilli()) < season.End {
|
||||
continue
|
||||
}
|
||||
var accounts []string
|
||||
for cursor := ""; ; {
|
||||
page, err := discovery.Accounts(ctx, cursor, 128)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
for _, account := range page {
|
||||
if account <= cursor {
|
||||
return errors.New("nonadvancing settlement account cursor")
|
||||
}
|
||||
accounts = append(accounts, account)
|
||||
cursor = account
|
||||
}
|
||||
}
|
||||
if err := s.pvp.BeginClosing(ctx, season, accounts); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, closure := range s.pvp.RequiredClosures(128) {
|
||||
raw, err := json.Marshal(closure)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := executePlayerSystem(ctx, registry, closure.Owner, player.ClosePVPSeason, raw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := s.pvp.FreezeDue(ctx, time.Now()); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, content := range registry.factory.options.calendars.RegularService.Contents {
|
||||
if content.ID != 6 {
|
||||
continue
|
||||
}
|
||||
if uint64(time.Now().UnixMilli()) >= content.Current.EndMilliseconds+registry.factory.options.calendars.RegularService.CalculateMilliseconds {
|
||||
if err := s.guild.FinalizeSeason(ctx, content.Current.ID, time.Now().UnixMilli()); err != nil && !errors.Is(err, social.ErrPending) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) closeExpiredRaids(ctx context.Context, registry *playerRegistry) error {
|
||||
for cursor := ""; ; {
|
||||
entries, next, err := s.guild.PendingRaidEntries(ctx, cursor, 128)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
season, err := s.guild.Season(ctx, entry.GuildID, entry.Season)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if time.Now().UnixMilli() < season.EndsMS {
|
||||
continue
|
||||
}
|
||||
if _, err := executePlayerSystem(ctx, registry, entry.AccountID, player.CloseExpiredRaid, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if next == "" || next == cursor {
|
||||
return nil
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/server/domain/social"
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
type socialStore struct{ store *shared.Store }
|
||||
type socialTx struct{ *shared.Tx }
|
||||
|
||||
func (s socialStore) Update(ctx context.Context, apply func(social.Tx) error) error {
|
||||
return s.store.Update(ctx, func(tx *shared.Tx) error { return apply(socialTx{tx}) })
|
||||
}
|
||||
func (s socialStore) View(ctx context.Context, apply func(social.Tx) error) error {
|
||||
return s.store.View(ctx, func(tx *shared.Tx) error { return apply(socialTx{tx}) })
|
||||
}
|
||||
func (t socialTx) Scan(bucket, prefix, after string, limit int) ([]social.Entry, error) {
|
||||
entries, err := t.Tx.Scan(bucket, prefix, after, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]social.Entry, len(entries))
|
||||
for i, e := range entries {
|
||||
out[i] = social.Entry{Key: e.Key, Value: e.Value}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type outboxDiscovery struct {
|
||||
factory *PlayerFactory
|
||||
accounts interface {
|
||||
Accounts(context.Context, string, int) ([]string, error)
|
||||
}
|
||||
}
|
||||
|
||||
func (d outboxDiscovery) Accounts(ctx context.Context, after string, limit int) ([]string, error) {
|
||||
if d.accounts != nil {
|
||||
return d.accounts.Accounts(ctx, after, limit)
|
||||
}
|
||||
if after < "local-owner" {
|
||||
return []string{"local-owner"}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (d outboxDiscovery) HasPending(ctx context.Context, account string) (pending bool, result error) {
|
||||
path := filepath.Join(d.factory.options.stateDirectory, "accounts", accountDirectoryName(account), "state.db")
|
||||
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
} else if err != nil {
|
||||
return false, err
|
||||
}
|
||||
absolute, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
uriPath := filepath.ToSlash(absolute)
|
||||
if !strings.HasPrefix(uriPath, "/") {
|
||||
uriPath = "/" + uriPath
|
||||
}
|
||||
u := url.URL{Scheme: "file", Path: uriPath}
|
||||
q := u.Query()
|
||||
q.Set("mode", "ro")
|
||||
q.Set("_pragma", "query_only(1)")
|
||||
q.Add("_pragma", "busy_timeout(1000)")
|
||||
u.RawQuery = q.Encode()
|
||||
db, err := sql.Open("sqlite", u.String())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() { result = errors.Join(result, db.Close()) }()
|
||||
db.SetMaxOpenConns(1)
|
||||
err = db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domain_entry WHERE domain_name='outbox' AND bucket='pending' LIMIT 1)`).Scan(&pending)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("discover pending outbox for account %q: %w", account, err)
|
||||
}
|
||||
return pending, err
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
accountstate "bd2server/internal/server/storage/account"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
"modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func TestOutboxDiscoveryReadsCommittedAccountState(t *testing.T) {
|
||||
discovery, path := discoveryFixture(t)
|
||||
if pending, err := discovery.HasPending(t.Context(), "missing"); err != nil || pending {
|
||||
t.Fatalf("missing account: pending=%v, err=%v", pending, err)
|
||||
}
|
||||
repository, err := accountstate.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := repository.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
check := func(want bool) {
|
||||
t.Helper()
|
||||
pending, err := discovery.HasPending(t.Context(), "writer")
|
||||
if err != nil || pending != want {
|
||||
t.Fatalf("pending=%v, want %v, err=%v", pending, want, err)
|
||||
}
|
||||
}
|
||||
check(false)
|
||||
tx, err := repository.BeginCommand(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func(tx *accountstate.CommandStore) { _ = tx.Rollback() }(tx)
|
||||
if err := outbox.Publish(tx, "writer", command.Event{ID: "committed-event", Topic: "fixture", Payload: []byte(`{}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(false)
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(true)
|
||||
tx, err = repository.BeginCommand(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func(tx *accountstate.CommandStore) { _ = tx.Rollback() }(tx)
|
||||
entries, err := outbox.Read(tx, 1)
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatalf("read committed outbox: entries=%v, err=%v", entries, err)
|
||||
}
|
||||
if err := outbox.Acknowledge(tx, entries[0].Key, entries[0].Digest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(true)
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(false)
|
||||
}
|
||||
|
||||
func TestOutboxDiscoveryWaitsForTransientWALLock(t *testing.T) {
|
||||
discovery, path := discoveryFixture(t)
|
||||
repository, err := accountstate.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := repository.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
tx, err := repository.BeginCommand(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func(tx *accountstate.CommandStore) { _ = tx.Rollback() }(tx)
|
||||
if err := outbox.Publish(tx, "writer", command.Event{ID: "pending-event", Topic: "fixture", Payload: []byte(`{}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repository.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writer, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writer.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { _ = writer.Close() })
|
||||
if _, err := writer.ExecContext(t.Context(), `PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; UPDATE metadata SET value=value WHERE key='writer_epoch'; COMMIT`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u := url.URL{Scheme: "file", Path: "/" + filepath.ToSlash(path)}
|
||||
u.RawQuery = "mode=ro"
|
||||
reader, err := sql.Open("sqlite", u.String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reader.Close() })
|
||||
var count int
|
||||
err = reader.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM domain_entry`).Scan(&count)
|
||||
if closeErr := reader.Close(); closeErr != nil {
|
||||
t.Fatal(closeErr)
|
||||
}
|
||||
var sqliteErr *sqlite.Error
|
||||
if !errors.As(err, &sqliteErr) || sqliteErr.Code()&0xff != 5 {
|
||||
t.Fatalf("fixture must hold a real SQLITE_BUSY WAL lock, got %v", err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
type result struct {
|
||||
pending bool
|
||||
err error
|
||||
}
|
||||
started := make(chan struct{})
|
||||
completed := make(chan result, 1)
|
||||
go func() {
|
||||
close(started)
|
||||
pending, err := discovery.HasPending(ctx, "writer")
|
||||
completed <- result{pending, err}
|
||||
}()
|
||||
<-started
|
||||
select {
|
||||
case result := <-completed:
|
||||
t.Fatalf("discovery returned before the transient lock cleared: pending=%v, err=%v", result.pending, result.err)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case result := <-completed:
|
||||
if result.err != nil || !result.pending {
|
||||
t.Fatalf("discovery after releasing WAL lock: pending=%v, err=%v", result.pending, result.err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("discovery did not complete within its caller deadline")
|
||||
}
|
||||
}
|
||||
|
||||
func discoveryFixture(t *testing.T) (outboxDiscovery, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
factory := &PlayerFactory{options: &configuration{stateDirectory: root}}
|
||||
return outboxDiscovery{factory: factory}, filepath.Join(root, "accounts", accountDirectoryName("writer"), "state.db")
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/world"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type storyCheckpoints struct {
|
||||
game *session.Server
|
||||
players *playerRegistry
|
||||
}
|
||||
|
||||
func (h storyCheckpoints) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "POST required", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
defer func() { _ = r.Body.Close() }()
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 4097))
|
||||
if err != nil || len(body) > 4096 {
|
||||
http.Error(w, "invalid story checkpoint request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var request world.StoryCheckpointRequest
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err = decoder.Decode(&request); err != nil {
|
||||
http.Error(w, "invalid story checkpoint request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var trailing any
|
||||
if err = decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
http.Error(w, "invalid story checkpoint request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
principal, err := h.game.Principal(r.Context(), r.Header.Get("Cookie"))
|
||||
if err != nil {
|
||||
slog.Warn("Story checkpoint request failed", "phase", "authenticate", "operation", request.Operation, "error", err)
|
||||
http.Error(w, "game session required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
runtime, release, err := h.players.Acquire(r.Context(), principal.AccountID)
|
||||
if err != nil {
|
||||
slog.Warn("Story checkpoint request failed", "phase", "acquire", "operation", request.Operation, "error", err)
|
||||
http.Error(w, "player unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
identity := command.Identity{AccountID: principal.AccountID, SessionID: principal.SessionID, RequestID: fmt.Sprintf("story-checkpoint:%d", systemSequence.Add(1))}
|
||||
future, err := runtime.Submit(r.Context(), player.Command{Identity: identity, ExpectedGeneration: principal.Generation, Digest: sha256.Sum256(body), System: &player.SystemRequest{Kind: player.StoryCheckpoint, Body: body}})
|
||||
if err != nil {
|
||||
slog.Warn("Story checkpoint request failed", "phase", "submit", "operation", request.Operation, "error", err)
|
||||
http.Error(w, "player unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
reply, err := future.Wait(r.Context())
|
||||
if err != nil {
|
||||
slog.Warn("Story checkpoint request failed", "phase", "execute", "operation", request.Operation, "error", err)
|
||||
status := http.StatusServiceUnavailable
|
||||
if errors.Is(err, world.ErrInvalidRequest) {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
if errors.Is(err, world.ErrStoryCheckpointConflict) {
|
||||
status = http.StatusConflict
|
||||
}
|
||||
http.Error(w, "story checkpoint unavailable", status)
|
||||
return
|
||||
}
|
||||
if len(reply.Responses) != 1 {
|
||||
slog.Warn("Story checkpoint request failed", "phase", "response", "operation", request.Operation, "response_count", len(reply.Responses))
|
||||
http.Error(w, "invalid story checkpoint response", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(reply.Responses[0].Body)
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/world"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/gateway/transport"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func storyCheckpointCall(t *testing.T, owner *playerInstance, operation string, checkpoint world.StoryCheckpoint) world.StoryCheckpointReply {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(world.StoryCheckpointRequest{StoryCheckpoint: checkpoint, Operation: operation})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply, err := owner.Execute(context.Background(), player.Command{Identity: command.Identity{AccountID: owner.accountID, SessionID: "story-presentation", RequestID: fmt.Sprint(systemSequence.Add(1))}, Digest: sha256.Sum256(body), System: &player.SystemRequest{Kind: player.StoryCheckpoint, Body: body}})
|
||||
if err != nil || len(reply.Responses) != 1 {
|
||||
t.Fatalf("%s checkpoint: %v", operation, err)
|
||||
}
|
||||
var out world.StoryCheckpointReply
|
||||
if err := json.Unmarshal(reply.Responses[0].Body, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestStoryCheckpointHTTPNativeSessionReachesActorAndPersistsCompletion(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[0]}
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
t.Cleanup(func() {
|
||||
if s.owner != nil {
|
||||
closeNicknamePlayer(t, s.owner)
|
||||
}
|
||||
})
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if rule := p.design.world.Story.Packs[5].Open; rule != nil && rule.TicketID != 0 {
|
||||
if _, err := p.ownedItems.GrantOnce(ctx, "http-presentation-chapter-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for quest := 1; quest < 26; quest++ {
|
||||
if err := p.progressState.ClearQuest(ctx, quest, 5, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
s.protocol(t, "/PackInGameInfo", trapRequest(1, 5))
|
||||
s.position(t, 5, 51)
|
||||
s.protocol(t, "/QuestClear", wire.AppendVarint(trapRequest(2, 26), 3, 5))
|
||||
settledGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
|
||||
closeNicknamePlayer(t, s.owner)
|
||||
s.owner = nil
|
||||
var registry *playerRegistry
|
||||
t.Cleanup(func() {
|
||||
if registry != nil {
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
openHTTP := func() (http.Handler, string) {
|
||||
t.Helper()
|
||||
registry = newPlayerRegistry(factory, time.Minute)
|
||||
game, err := session.NewServer(registry, nicknameAuthenticator{accounts[0]})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
login, err := game.DispatchRaw(context.Background(), "/LoginUser", nicknameEncrypt(t, appScalar(1, 1), []byte("abcdefghijkrstuv024680wxyzlmnopq")), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := transport.HTTP{StoryCheckpoints: storyCheckpoints{game: game, players: registry}}.Handler()
|
||||
return handler, "s=" + login.Cookie
|
||||
}
|
||||
callHTTP := func(handler http.Handler, cookie, operation string, checkpoint world.StoryCheckpoint, status int) world.StoryCheckpointReply {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(world.StoryCheckpointRequest{StoryCheckpoint: checkpoint, Operation: operation})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/client/story-checkpoint", strings.NewReader(string(body)))
|
||||
request.Header.Set("Cookie", cookie)
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != status {
|
||||
t.Fatalf("HTTP checkpoint %s status=%d want%d: %s", operation, response.Code, status, response.Body.String())
|
||||
}
|
||||
var result world.StoryCheckpointReply
|
||||
if status == http.StatusOK {
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
handler, cookie := openHTTP()
|
||||
callHTTP(handler, "", "read", world.StoryCheckpoint{}, http.StatusUnauthorized)
|
||||
pending := callHTTP(handler, cookie, "read", world.StoryCheckpoint{}, http.StatusOK).Checkpoint
|
||||
if pending == nil || pending.QuestID != 26 || pending.Timeline != "Quest_Main_26" || pending.MapID != 51 {
|
||||
t.Fatalf("HTTP actor path did not restore actual pending cinema: %+v", pending)
|
||||
}
|
||||
begin := *pending
|
||||
begin.ID = "http-client-replay"
|
||||
if adopted := callHTTP(handler, cookie, "begin", begin, http.StatusOK).Checkpoint; adopted == nil || adopted.ID != pending.ID {
|
||||
t.Fatal("HTTP actor path failed to adopt pending checkpoint")
|
||||
}
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry = nil
|
||||
handler, freshCookie := openHTTP()
|
||||
callHTTP(handler, cookie, "read", world.StoryCheckpoint{}, http.StatusUnauthorized)
|
||||
if restored := callHTTP(handler, freshCookie, "read", world.StoryCheckpoint{}, http.StatusOK).Checkpoint; restored == nil || restored.ID != pending.ID {
|
||||
t.Fatal("HTTP checkpoint was lost across runtime/session restart")
|
||||
}
|
||||
if completed := callHTTP(handler, freshCookie, "complete", world.StoryCheckpoint{ID: pending.ID}, http.StatusOK).Checkpoint; completed != nil {
|
||||
t.Fatal("HTTP actor completion left playback pending")
|
||||
}
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry = nil
|
||||
handler, lastCookie := openHTTP()
|
||||
if replay := callHTTP(handler, lastCookie, "read", world.StoryCheckpoint{}, http.StatusOK).Checkpoint; replay != nil {
|
||||
t.Fatal("HTTP completion did not persist across restart")
|
||||
}
|
||||
if err := registry.Close(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry = nil
|
||||
owner := openNicknamePlayer(t, factory, accounts[0])
|
||||
defer closeNicknamePlayer(t, owner)
|
||||
if owner.assembly.wallet.Snapshot(command.Context{}).Gold != settledGold || !owner.assembly.progressState.QuestCleared(26, 5, 0) || owner.assembly.progressState.QuestCleared(27, 5, 0) {
|
||||
t.Fatal("HTTP playback recovery changed settled reward or quest progress")
|
||||
}
|
||||
}
|
||||
|
||||
// Current GameData 20261008155037 QuestTable5/26 has CompleteCinemaName
|
||||
// Quest_Main_26, TimelineStartMapId51, next27 and normal reward gold700.
|
||||
// QuestPacket.RecvQuestClearResponse starts this cinema after server clear.
|
||||
func TestUnfinishedQuestPresentationSurvivesReloadWithoutRewindingRewards(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[0]}
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if rule := p.design.world.Story.Packs[5].Open; rule != nil && rule.TicketID != 0 {
|
||||
if _, err := p.ownedItems.GrantOnce(ctx, "presentation-chapter-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for quest := 1; quest < 26; quest++ {
|
||||
if err := p.progressState.ClearQuest(ctx, quest, 5, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
s.protocol(t, "/PackInGameInfo", trapRequest(1, 5))
|
||||
s.position(t, 5, 51)
|
||||
beforeGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
|
||||
clear := wire.AppendVarint(trapRequest(2, 26), 3, 5)
|
||||
s.protocol(t, "/QuestClear", clear)
|
||||
if gold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold; gold != beforeGold+700 {
|
||||
t.Fatalf("quest gold=%d want%d", gold, beforeGold+700)
|
||||
}
|
||||
closeNicknamePlayer(t, s.owner)
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint
|
||||
if pending == nil || pending.PackID != 5 || pending.QuestID != 26 || pending.Phase != "complete" || pending.Timeline != "Quest_Main_26" || pending.MapID != 51 {
|
||||
t.Fatalf("unfinished cinema was not restored: %+v", pending)
|
||||
}
|
||||
if !s.owner.assembly.progressState.QuestCleared(26, 5, 0) || s.owner.assembly.progressState.QuestCleared(27, 5, 0) {
|
||||
t.Fatal("presentation recovery rewound or advanced quest state")
|
||||
}
|
||||
retryBegin := *pending
|
||||
retryBegin.ID = "client-restarted-playback"
|
||||
if adopted := storyCheckpointCall(t, s.owner, "begin", retryBegin).Checkpoint; adopted == nil || adopted.ID != pending.ID {
|
||||
t.Fatal("restarted playback failed to adopt the committed presentation identity")
|
||||
}
|
||||
s.protocol(t, "/QuestClear", clear)
|
||||
if gold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold; gold != beforeGold+700 {
|
||||
t.Fatal("quest retry duplicated settled reward")
|
||||
}
|
||||
_, err := s.execute("/QuestClear", wire.AppendVarint(trapRequest(3, 27), 3, 5))
|
||||
if !errors.Is(err, world.ErrStoryCheckpointConflict) {
|
||||
t.Fatalf("next quest overwrote unfinished cinema: %v", err)
|
||||
}
|
||||
if err := s.owner.Recover(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.owner.assembly.progressState.QuestCleared(27, 5, 0) || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold+700 {
|
||||
t.Fatal("rejected presentation transition advanced progress or rewards")
|
||||
}
|
||||
if pendingAfter := storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: "old-finished-dialogue"}).Checkpoint; pendingAfter == nil || pendingAfter.ID != pending.ID {
|
||||
t.Fatal("stale completion skipped the unfinished cinema")
|
||||
}
|
||||
if done := storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: pending.ID}).Checkpoint; done != nil {
|
||||
t.Fatal("completed cinema stayed pending")
|
||||
}
|
||||
storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: pending.ID})
|
||||
closeNicknamePlayer(t, s.owner)
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
if storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint != nil {
|
||||
t.Fatal("completed presentation returned after reload")
|
||||
}
|
||||
s.protocol(t, "/QuestClear", clear)
|
||||
if storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint != nil {
|
||||
t.Fatal("quest retry recreated a finished cinema")
|
||||
}
|
||||
if gold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold; gold != beforeGold+700 {
|
||||
t.Fatal("presentation acknowledgements changed settled gold")
|
||||
}
|
||||
}
|
||||
|
||||
// Current pack5 FieldQuestObject111 lists quest11 and simple talk group671.
|
||||
// Native InteractionQuest opens that balloon before sending QuestUpdate.
|
||||
func TestUnfinishedStoryInteractionRestartsBeforeQuestUpdateAndClear(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
s := &trapPlayerScenario{factory: factory, account: accounts[0]}
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
|
||||
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
|
||||
if rule := p.design.world.Story.Packs[5].Open; rule != nil && rule.TicketID != 0 {
|
||||
if _, err := p.ownedItems.GrantOnce(ctx, "interaction-chapter-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for quest := 1; quest < 11; quest++ {
|
||||
if err := p.progressState.ClearQuest(ctx, quest, 5, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
s.protocol(t, "/PackInGameInfo", trapRequest(1, 5))
|
||||
s.position(t, 5, 52)
|
||||
beforeGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
|
||||
interaction := world.StoryCheckpoint{ID: "unfinished-dialogue-671", PackID: 5, QuestID: 11, Phase: "interaction", ObjectID: 111, MapID: 52, SimpleTalkGroupID: 671}
|
||||
storyCheckpointCall(t, s.owner, "begin", interaction)
|
||||
closeNicknamePlayer(t, s.owner)
|
||||
s.owner = openNicknamePlayer(t, factory, s.account)
|
||||
pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint
|
||||
if pending == nil || *pending != interaction {
|
||||
t.Fatalf("dialogue beginning was not recovered: %+v", pending)
|
||||
}
|
||||
if _, updated := s.owner.assembly.progressState.QuestInPack(11, 5, 0); updated || s.owner.assembly.progressState.QuestCleared(11, 5, 0) || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold {
|
||||
t.Fatal("unfinished dialogue advanced quest or granted reward")
|
||||
}
|
||||
storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: interaction.ID})
|
||||
update := wire.AppendVarint(wire.AppendVarint(trapRequest(2, 11), 3, 5), 4, 1)
|
||||
s.protocol(t, "/QuestUpdate", update)
|
||||
if s.owner.assembly.progressState.QuestCleared(11, 5, 0) || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold {
|
||||
t.Fatal("dialogue update awarded quest-clear reward")
|
||||
}
|
||||
s.protocol(t, "/QuestClear", wire.AppendVarint(trapRequest(3, 11), 3, 5))
|
||||
completion := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint
|
||||
if completion == nil || completion.Phase != "complete" || completion.Timeline != "Quest_Main_11" || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold+700 {
|
||||
t.Fatal("finished interaction did not transition to settled quest and pending completion cinema")
|
||||
}
|
||||
if stillPending := storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: interaction.ID}).Checkpoint; stillPending == nil || stillPending.ID != completion.ID {
|
||||
t.Fatal("delayed dialogue finish cleared the subsequent cinema")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gameconfig"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
)
|
||||
|
||||
func TestTextModerationPreflightRejectsWholeBatchAndPreservesPreset(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
config := gameconfig.DefaultTextModeration()
|
||||
config.RuleFiles = []string{moderationRulesFile(t, base, `{"rules":[{"text":"Blocked","match":"exact","scopes":["preset_name","master_title"]}]}`)}
|
||||
g := newModerationGameplay(t, config, base)
|
||||
metadata := wire.AppendVarint(wire.AppendString(nil, 2, "Allowed"), 3, 1)
|
||||
g.call("/PresetInfoChange", metadata, 0)
|
||||
beforePreset := g.call("/PresetInfo", nil, 0)
|
||||
beforeTitle := g.call("/MasterTitleInfo", nil, 0)
|
||||
before := g.snapshot()
|
||||
g.call("/PresetSave", wire.AppendBytes(nil, 2, wire.AppendVarint(wire.AppendString(nil, 1, "Blocked"), 2, 1)), 9001)
|
||||
g.call("/PresetInfoChange", wire.AppendVarint(wire.AppendString(nil, 2, "Blocked"), 3, 1), 9001)
|
||||
g.call("/MasterTitleInfoUpdate", wire.AppendString(nil, 2, "Blocked"), 9001)
|
||||
g.seq++
|
||||
request := registryCommand(g.account, "moderation-batch", "/UserNicknameChange", wire.AppendString(appScalar(1, g.seq), 2, "BatchAlias"))
|
||||
request.Requests = append(request.Requests, player.Request{Path: "/PresetInfoChange", Body: wire.AppendString(appScalar(1, g.seq+1), 2, "Blocked")})
|
||||
request.Digest = sha256.Sum256(append(request.Requests[0].Body, request.Requests[1].Body...))
|
||||
_, err := g.owner.Execute(context.Background(), request)
|
||||
var gameError *command.GameError
|
||||
if !errors.As(err, &gameError) || gameError.PacketCode != 278 || gameError.ErrorType != 9001 {
|
||||
t.Fatalf("batch rejection=%v, want PresetInfoChange moderation error", err)
|
||||
}
|
||||
g.assertState(before)
|
||||
if got := g.call("/PresetInfo", nil, 0); !bytes.Equal(got, beforePreset) {
|
||||
t.Fatal("rejected save, rename or batch changed persisted preset")
|
||||
}
|
||||
g.reopen()
|
||||
g.assertState(before)
|
||||
if got := g.call("/PresetInfo", nil, 0); !bytes.Equal(got, beforePreset) {
|
||||
t.Fatal("rejected preset mutation survived account reopen")
|
||||
}
|
||||
if got := g.call("/MasterTitleInfo", nil, 0); !bytes.Equal(got, beforeTitle) {
|
||||
t.Fatal("rejected master title mutation survived account reopen")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextModerationProviderRunsOutsideTransactionAndCommittedReplaySkipsIt(t *testing.T) {
|
||||
var owner *playerInstance
|
||||
checks := make(chan error, 8)
|
||||
webhook := newModerationWebhook(t)
|
||||
webhook.check = func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
tx, err := owner.repository.BeginCommand(ctx)
|
||||
if err == nil {
|
||||
err = tx.Rollback()
|
||||
}
|
||||
checks <- err
|
||||
}
|
||||
config := moderationHTTPConfig(webhook.server.URL, "deny", []string{"nickname", "monster_hunt_preset_name"})
|
||||
config.Provider.TimeoutMS = 1000
|
||||
g := newModerationGameplay(t, config, t.TempDir())
|
||||
owner = g.owner
|
||||
request := registryCommand(g.account, "moderation-replay", "/UserNicknameChange", wire.AppendString(appScalar(1, 101), 2, "AcceptedAlias"))
|
||||
first, err := g.owner.Execute(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-checks; err != nil {
|
||||
t.Fatalf("provider could not begin a transaction: player transaction was still open: %v", err)
|
||||
}
|
||||
before := g.snapshot()
|
||||
webhook.setMode("unavailable")
|
||||
g.reopen()
|
||||
owner = g.owner
|
||||
replay, err := g.owner.Execute(context.Background(), request)
|
||||
if err != nil || len(replay.Responses) != 1 || !bytes.Equal(replay.Responses[0].Body, first.Responses[0].Body) || replay.Responses[0].PacketCode != first.Responses[0].PacketCode {
|
||||
t.Fatalf("committed replay failed while provider unavailable: reply=%+v, error=%v", replay, err)
|
||||
}
|
||||
if got := webhook.requests(); len(got) != 1 {
|
||||
t.Fatalf("committed replay invoked provider again: %d calls", len(got))
|
||||
}
|
||||
g.assertState(before)
|
||||
g.call("/MonsterHuntPresetSave", wire.AppendBytes(nil, 2, nil), 0)
|
||||
if got := webhook.requests(); len(got) != 1 {
|
||||
t.Fatal("proto3 omitted monster hunt preset name was sent as empty text to provider")
|
||||
}
|
||||
rows := appRows(g.call("/MonsterHuntPresetInfo", nil, 0), 1)
|
||||
if len(rows) != 1 {
|
||||
t.Fatal("blank monster hunt preset was not stored")
|
||||
}
|
||||
name, _, err := wire.Bytes(rows[0], 1)
|
||||
if err != nil || len(name) != 0 {
|
||||
t.Fatal("blank monster hunt preset name did not persist")
|
||||
}
|
||||
}
|
||||
|
||||
// These contracts are owner-defined server policy, including error types 9001/9002;
|
||||
// transport and persistence use the real account actor, encrypted packets and SQLite.
|
||||
func TestTextModerationDefaultAllowsFlechazo(t *testing.T) {
|
||||
g := newModerationGameplay(t, gameconfig.DefaultTextModeration(), t.TempDir())
|
||||
before := g.snapshot()
|
||||
g.edit("/UserNicknameChange", "Flechazo", 0)
|
||||
want := before
|
||||
want.name = "Flechazo"
|
||||
want.tickets--
|
||||
g.assertState(want)
|
||||
g.reopen()
|
||||
g.assertState(want)
|
||||
}
|
||||
|
||||
func TestTextModerationOwnerRulesControlRealProfileEdits(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
config := gameconfig.DefaultTextModeration()
|
||||
config.RuleFiles = []string{moderationRulesFile(t, base, `{"rules":[
|
||||
{"text":"lech","match":"word","scopes":["nickname"]},
|
||||
{"text":"BadAlias","match":"exact","scopes":["nickname"]},
|
||||
{"text":"secret","match":"substring","scopes":["nickname"]},
|
||||
{"text":"hazard","match":"substring","scopes":["nickname","greeting"],"exceptions":["SafeHazard"]},
|
||||
{"text":"SafeHazard","match":"exact","scopes":["nickname"]}
|
||||
]}`)}
|
||||
g := newModerationGameplay(t, config, base)
|
||||
for _, tc := range []struct {
|
||||
path, text string
|
||||
reject bool
|
||||
}{
|
||||
{"/UserNicknameChange", "Flechazo", false},
|
||||
{"/UserNicknameChange", "lech", true},
|
||||
{"/UserNicknameChange", "bAdAlIaS", true},
|
||||
{"/UserNicknameChange", "xBadAlias", false},
|
||||
{"/UserNicknameChange", "secretNote", true},
|
||||
{"/UserGreetingChange", "secretNote", false},
|
||||
{"/UserGreetingChange", "lech visitors", false},
|
||||
{"/UserGreetingChange", "hazard", true},
|
||||
{"/UserGreetingChange", "SafeHazard", false},
|
||||
{"/UserGreetingChange", "SafeHazardExtra", true},
|
||||
{"/UserNicknameChange", "SafeHazard", true},
|
||||
} {
|
||||
t.Run(tc.path+"/"+tc.text, func(t *testing.T) {
|
||||
parent := g.t
|
||||
g.t = t
|
||||
defer func() { g.t = parent }()
|
||||
before := g.snapshot()
|
||||
if tc.reject {
|
||||
g.edit(tc.path, tc.text, 9001)
|
||||
g.assertState(before)
|
||||
g.reopen()
|
||||
g.assertState(before)
|
||||
return
|
||||
}
|
||||
g.edit(tc.path, tc.text, 0)
|
||||
want := before
|
||||
if tc.path == "/UserNicknameChange" {
|
||||
want.name = tc.text
|
||||
want.tickets--
|
||||
} else {
|
||||
want.greeting = tc.text
|
||||
}
|
||||
g.assertState(want)
|
||||
})
|
||||
}
|
||||
before := g.snapshot()
|
||||
g.reopen()
|
||||
g.assertState(before)
|
||||
g.edit("/UserNicknameChange", "NextAlias", 0)
|
||||
g.edit("/UserGreetingChange", "Welcome back", 0)
|
||||
want := before
|
||||
want.name, want.greeting = "NextAlias", "Welcome back"
|
||||
want.tickets--
|
||||
g.reopen()
|
||||
g.assertState(want)
|
||||
}
|
||||
|
||||
func TestTextModerationRuleExceptionCannotBypassRemoteAndScopeGatesCalls(t *testing.T) {
|
||||
webhook := newModerationWebhook(t)
|
||||
base := t.TempDir()
|
||||
config := moderationHTTPConfig(webhook.server.URL, "deny", []string{"nickname"})
|
||||
config.RuleFiles = []string{moderationRulesFile(t, base, `{"rules":[{"text":"flech","match":"substring","scopes":["nickname"],"exceptions":["Flechazo"]}]}`)}
|
||||
g := newModerationGameplay(t, config, base)
|
||||
before := g.snapshot()
|
||||
g.edit("/UserGreetingChange", "flech visitors", 0)
|
||||
g.call("/ItemInfo", nil, 0)
|
||||
if got := webhook.requests(); len(got) != 0 {
|
||||
t.Fatalf("provider received requests outside configured nickname scope: %+v", got)
|
||||
}
|
||||
before.greeting = "flech visitors"
|
||||
webhook.setMode("reject")
|
||||
g.edit("/UserNicknameChange", "Flechazo", 9001)
|
||||
g.assertState(before)
|
||||
webhook.setMode("allow")
|
||||
g.edit("/UserNicknameChange", "Flechazo", 0)
|
||||
want := before
|
||||
want.name = "Flechazo"
|
||||
want.tickets--
|
||||
g.assertState(want)
|
||||
got := webhook.requests()
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("remote should evaluate both attempts despite the local exception: %+v", got)
|
||||
}
|
||||
for _, request := range got {
|
||||
assertModerationWebhookRequest(t, request, g.account, "nickname", "Flechazo")
|
||||
}
|
||||
g.reopen()
|
||||
g.assertState(want)
|
||||
}
|
||||
|
||||
func TestTextModerationHTTPDecisionsAndFailurePolicyPreserveAccount(t *testing.T) {
|
||||
for _, policy := range []string{"deny", "allow"} {
|
||||
t.Run(policy, func(t *testing.T) {
|
||||
webhook := newModerationWebhook(t)
|
||||
config := moderationHTTPConfig(webhook.server.URL, policy, []string{"nickname", "greeting"})
|
||||
g := newModerationGameplay(t, config, t.TempDir())
|
||||
g.edit("/UserNicknameChange", "InitialAlias", 0)
|
||||
g.edit("/UserGreetingChange", "Initial greeting", 0)
|
||||
for modeIndex, mode := range []string{"reject", "unavailable", "malformed", "timeout"} {
|
||||
for _, scope := range []string{"nickname", "greeting"} {
|
||||
t.Run(mode+"/"+scope, func(t *testing.T) {
|
||||
parent := g.t
|
||||
g.t = t
|
||||
defer func() { g.t = parent }()
|
||||
before := g.snapshot()
|
||||
path, candidate := "/UserNicknameChange", fmt.Sprintf("Candidate%d", modeIndex)
|
||||
if scope == "greeting" {
|
||||
path, candidate = "/UserGreetingChange", fmt.Sprintf("Candidate greeting %d", modeIndex)
|
||||
}
|
||||
webhook.setMode(mode)
|
||||
start := len(webhook.requests())
|
||||
wantError := 9002
|
||||
if mode == "reject" {
|
||||
wantError = 9001
|
||||
} else if policy == "allow" {
|
||||
wantError = 0
|
||||
}
|
||||
g.edit(path, candidate, wantError)
|
||||
want := before
|
||||
if wantError == 0 {
|
||||
if scope == "nickname" {
|
||||
want.name = candidate
|
||||
want.tickets--
|
||||
} else {
|
||||
want.greeting = candidate
|
||||
}
|
||||
}
|
||||
g.assertState(want)
|
||||
requests := webhook.requests()[start:]
|
||||
if len(requests) != 1 {
|
||||
t.Fatalf("profile edit produced %d provider requests", len(requests))
|
||||
}
|
||||
assertModerationWebhookRequest(t, requests[0], g.account, scope, candidate)
|
||||
if wantError != 0 {
|
||||
g.reopen()
|
||||
g.assertState(want)
|
||||
g.edit(path, candidate, wantError)
|
||||
g.assertState(want)
|
||||
}
|
||||
webhook.setMode("allow")
|
||||
valid := fmt.Sprintf("Recovery%d", modeIndex)
|
||||
if scope == "greeting" {
|
||||
valid = fmt.Sprintf("Recovery greeting %d", modeIndex)
|
||||
}
|
||||
g.edit(path, valid, 0)
|
||||
if scope == "nickname" {
|
||||
want.name = valid
|
||||
want.tickets--
|
||||
} else {
|
||||
want.greeting = valid
|
||||
}
|
||||
g.assertState(want)
|
||||
g.reopen()
|
||||
g.assertState(want)
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type moderationState struct {
|
||||
name, greeting string
|
||||
tickets uint64
|
||||
wallet assets.Currency
|
||||
}
|
||||
|
||||
type moderationGameplay struct {
|
||||
t *testing.T
|
||||
factory *PlayerFactory
|
||||
account string
|
||||
owner *playerInstance
|
||||
runtime *player.Runtime
|
||||
server *session.Server
|
||||
key []byte
|
||||
cookie string
|
||||
seq uint64
|
||||
index uint64
|
||||
}
|
||||
|
||||
func newModerationGameplay(t *testing.T, config gameconfig.TextModerationConfig, base string) *moderationGameplay {
|
||||
t.Helper()
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
moderator, err := textmoderation.New(config, base)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := moderator.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.options.textModerator = moderator
|
||||
g := &moderationGameplay{t: t, factory: factory, account: accounts[0]}
|
||||
identity, err := factory.profiles.GameIdentity(context.Background(), g.account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g.index = uint64(identity.OwnerIndex)
|
||||
owner := openNicknamePlayer(t, factory, g.account)
|
||||
seedNicknameTickets(t, owner, 20)
|
||||
closeNicknamePlayer(t, owner)
|
||||
g.open()
|
||||
t.Cleanup(func() { g.close() })
|
||||
return g
|
||||
}
|
||||
|
||||
func (g *moderationGameplay) Acquire(_ context.Context, account string) (*player.Runtime, func(), error) {
|
||||
if account != g.account {
|
||||
return nil, nil, fmt.Errorf("unexpected account %q", account)
|
||||
}
|
||||
return g.runtime, func() {}, nil
|
||||
}
|
||||
|
||||
func (g *moderationGameplay) open() {
|
||||
g.t.Helper()
|
||||
g.owner = openNicknamePlayer(g.t, g.factory, g.account)
|
||||
var err error
|
||||
g.runtime, err = player.New(g.account, g.owner, player.Limits{})
|
||||
if err != nil {
|
||||
closeNicknamePlayer(g.t, g.owner)
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
g.server, err = session.NewServer(g, nicknameAuthenticator{g.account})
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
fixed := []byte("abcdefghijkrstuv024680wxyzlmnopq")
|
||||
login, err := g.server.DispatchRaw(context.Background(), "/LoginUser", nicknameEncrypt(g.t, appScalar(1, 1), fixed), "")
|
||||
if err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
var envelope struct{ Data string }
|
||||
if err = json.Unmarshal(login.Body, &envelope); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
users := appRows(nicknameDecrypt(g.t, envelope.Data, fixed), 1)
|
||||
if len(users) != 1 {
|
||||
g.t.Fatal("missing login user")
|
||||
}
|
||||
g.key = []byte(nicknameField(g.t, users[0], 3))
|
||||
if len(g.key) != 32 || login.Cookie == "" {
|
||||
g.t.Fatal("missing active session key/cookie")
|
||||
}
|
||||
g.cookie, g.seq = "s="+login.Cookie, 1
|
||||
}
|
||||
|
||||
func (g *moderationGameplay) close() {
|
||||
g.t.Helper()
|
||||
if g.runtime != nil {
|
||||
if err := g.runtime.Close(context.Background()); err != nil {
|
||||
g.t.Error(err)
|
||||
}
|
||||
g.runtime = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (g *moderationGameplay) reopen() {
|
||||
g.t.Helper()
|
||||
g.close()
|
||||
g.open()
|
||||
}
|
||||
|
||||
func (g *moderationGameplay) call(path string, fields []byte, wantError int) []byte {
|
||||
g.t.Helper()
|
||||
g.seq++
|
||||
request := append(appScalar(1, g.seq), fields...)
|
||||
reply, err := g.server.DispatchRaw(context.Background(), path, nicknameEncrypt(g.t, request, g.key), g.cookie)
|
||||
if err != nil {
|
||||
g.t.Fatalf("%s invalidated active session or failed dispatch: %v", path, err)
|
||||
}
|
||||
var envelope struct {
|
||||
PacketCode int
|
||||
ErrorType int
|
||||
Data string
|
||||
}
|
||||
if err = json.Unmarshal(reply.Body, &envelope); err != nil {
|
||||
g.t.Fatal(err)
|
||||
}
|
||||
if envelope.ErrorType != wantError {
|
||||
g.t.Fatalf("%s ErrorType=%d, want %d: %s", path, envelope.ErrorType, wantError, reply.Body)
|
||||
}
|
||||
if path == "/UserNicknameChange" && envelope.PacketCode != 74 || path == "/UserGreetingChange" && envelope.PacketCode != 219 {
|
||||
g.t.Fatalf("%s wrong packet code: %s", path, reply.Body)
|
||||
}
|
||||
return nicknameDecrypt(g.t, envelope.Data, g.key)
|
||||
}
|
||||
|
||||
func (g *moderationGameplay) edit(path, text string, wantError int) {
|
||||
g.t.Helper()
|
||||
g.call(path, appMessage(2, []byte(text)), wantError)
|
||||
}
|
||||
|
||||
func (g *moderationGameplay) snapshot() moderationState {
|
||||
g.t.Helper()
|
||||
body := g.call("/UserContentsInfo", appScalar(2, g.index), 0)
|
||||
tickets, wallet := nicknameAssets(g.t, g.owner)
|
||||
return moderationState{name: nicknameField(g.t, body, 2), greeting: nicknameField(g.t, body, 5), tickets: tickets, wallet: wallet}
|
||||
}
|
||||
|
||||
func (g *moderationGameplay) assertState(want moderationState) {
|
||||
g.t.Helper()
|
||||
if got := g.snapshot(); got != want {
|
||||
g.t.Fatalf("account state=%+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func moderationRulesFile(t *testing.T, base, rules string) string {
|
||||
t.Helper()
|
||||
const name = "owner-rules.json"
|
||||
if err := os.WriteFile(filepath.Join(base, name), []byte(rules), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func moderationHTTPConfig(endpoint, failurePolicy string, scopes []string) gameconfig.TextModerationConfig {
|
||||
config := gameconfig.DefaultTextModeration()
|
||||
config.Provider.Type = "http_json"
|
||||
config.Provider.Endpoint = endpoint
|
||||
config.Provider.Scopes = scopes
|
||||
config.Provider.TimeoutMS = 80
|
||||
config.Provider.FailurePolicy = failurePolicy
|
||||
return config
|
||||
}
|
||||
|
||||
type moderationWebhookRequest struct {
|
||||
method, contentType string
|
||||
body map[string]string
|
||||
decodeError error
|
||||
}
|
||||
|
||||
type moderationWebhook struct {
|
||||
server *httptest.Server
|
||||
mu sync.Mutex
|
||||
mode string
|
||||
seen []moderationWebhookRequest
|
||||
check func()
|
||||
}
|
||||
|
||||
func newModerationWebhook(t *testing.T) *moderationWebhook {
|
||||
t.Helper()
|
||||
w := &moderationWebhook{mode: "allow"}
|
||||
w.server = httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
body := map[string]string{}
|
||||
err := json.NewDecoder(request.Body).Decode(&body)
|
||||
w.mu.Lock()
|
||||
w.seen = append(w.seen, moderationWebhookRequest{request.Method, request.Header.Get("Content-Type"), body, err})
|
||||
mode := w.mode
|
||||
w.mu.Unlock()
|
||||
if w.check != nil {
|
||||
w.check()
|
||||
}
|
||||
switch mode {
|
||||
case "unavailable":
|
||||
response.WriteHeader(http.StatusServiceUnavailable)
|
||||
case "malformed":
|
||||
_, _ = response.Write([]byte(`{"decision":`))
|
||||
case "timeout":
|
||||
<-request.Context().Done()
|
||||
default:
|
||||
response.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(response).Encode(map[string]string{"decision": mode})
|
||||
}
|
||||
}))
|
||||
t.Cleanup(w.server.Close)
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *moderationWebhook) setMode(mode string) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.mode = mode
|
||||
}
|
||||
|
||||
func (w *moderationWebhook) requests() []moderationWebhookRequest {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return slices.Clone(w.seen)
|
||||
}
|
||||
|
||||
func assertModerationWebhookRequest(t *testing.T, request moderationWebhookRequest, account, scope, text string) {
|
||||
t.Helper()
|
||||
if request.decodeError != nil || request.method != http.MethodPost || request.contentType != "application/json" || len(request.body) != 3 || request.body["scope"] != scope || request.body["account_id"] != account || request.body["text"] != text {
|
||||
t.Fatalf("wrong provider request: %+v", request)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/battle/monsterhunt"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/profile"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 2.36.7 UserInfoPacket consumes UserContentsInfo fields 1/2/4/17/26/28,
|
||||
// and then sends IdCardRecovery for an unsaved default card. Current GameData
|
||||
// 20261008155037: achievement 0/1/1 needs 500 progress, adds 3 EXP; cumulative
|
||||
// level requirements 2 and 15 make this level 2. Default background is 10001.
|
||||
func TestUserContentsInfoReflectsCommittedProfileAndRejectsOtherOwners(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
now := time.Now()
|
||||
presets, err := gamedata.LoadMonsterHuntPresetDesign(factory.options.gameData, factory.options.gameDataVersion)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factory.design.monsterHunt, err = monsterhunt.NewRules([]monsterhunt.Season{{ID: 81, Hunt: 75, Start: uint64(now.Add(-time.Hour).UnixMilli()), End: uint64(now.Add(time.Hour).UnixMilli())}}, factory.seeds.defaults, presets, factory.design.source.MonsterHunt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity, err := factory.profiles.GameIdentity(context.Background(), accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other, err := factory.profiles.GameIdentity(context.Background(), accounts[1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if owner != nil {
|
||||
if err := owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
var seq uint64
|
||||
request := func(path string, fields []byte) player.Command {
|
||||
seq++
|
||||
body := append(wire.AppendVarint(nil, 1, seq), fields...)
|
||||
return player.Command{
|
||||
Identity: command.Identity{AccountID: accounts[0], SessionID: "profile-client", RequestID: fmt.Sprintf("profile-%d", seq)},
|
||||
Digest: sha256.Sum256(append([]byte(path), body...)), Requests: []player.Request{{Path: path, Body: body}},
|
||||
}
|
||||
}
|
||||
call := func(c player.Command, code int) []byte {
|
||||
t.Helper()
|
||||
reply, err := owner.Execute(context.Background(), c)
|
||||
if err != nil || len(reply.Responses) != 1 {
|
||||
t.Fatalf("%s: %v, responses=%d", c.Requests[0].Path, err, len(reply.Responses))
|
||||
}
|
||||
if reply.Responses[0].PacketCode != code {
|
||||
t.Fatalf("%s packet code=%d want %d", c.Requests[0].Path, reply.Responses[0].PacketCode, code)
|
||||
}
|
||||
return reply.Responses[0].Body
|
||||
}
|
||||
self := func() []byte {
|
||||
return call(request("/UserContentsInfo", wire.AppendVarint(nil, 2, uint64(identity.OwnerIndex))), 215)
|
||||
}
|
||||
before := self()
|
||||
if got, _, _ := wire.Varint(before, 26); got != 1 {
|
||||
t.Fatalf("unearned profile achievement level=%d want 1", got)
|
||||
}
|
||||
var portrait uint64
|
||||
for _, costume := range owner.assembly.collection.Costumes() {
|
||||
if costume.ID != 0 && (portrait == 0 || costume.ID < portrait) {
|
||||
portrait = costume.ID
|
||||
}
|
||||
}
|
||||
if portrait == 0 {
|
||||
t.Fatal("integration starter has no real owned portrait costume")
|
||||
}
|
||||
call(request("/UserPortraitChange", wire.AppendVarint(nil, 2, portrait)), 75)
|
||||
call(request("/SaveTotalBattlePower", wire.AppendVarint(nil, 2, 12345)), 258)
|
||||
update := wire.AppendVarint(nil, 2, 1)
|
||||
update = wire.AppendVarint(update, 3, 500)
|
||||
call(request("/AchievementUpdate", update), 167)
|
||||
clear := wire.AppendVarint(nil, 1, 1)
|
||||
clear = wire.AppendVarint(clear, 2, 1)
|
||||
claim := request("/AchievementClear", wire.AppendBytes(nil, 3, clear))
|
||||
claimResponse := call(claim, 168)
|
||||
if retry := call(claim, 168); !bytes.Equal(claimResponse, retry) {
|
||||
t.Fatal("achievement reward retry changed response")
|
||||
}
|
||||
wantHuntRank := uint64(0)
|
||||
cardRecovered := false
|
||||
assertCard := func(card []byte) {
|
||||
t.Helper()
|
||||
for _, expected := range []struct {
|
||||
Field int
|
||||
ID uint64
|
||||
X, Y int32
|
||||
Scale float32
|
||||
Color string
|
||||
}{{1, 10001, 0, 0, 1, ""}, {4, 40001, -234, 52, 1, ""}, {5, 0, -218, 156, 0.75, "FFFFFF"}} {
|
||||
item, found, err := wire.Bytes(card, expected.Field)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("default card is missing layout component%d: %v", expected.Field, err)
|
||||
}
|
||||
index, _, err := wire.Varint(item, 1)
|
||||
if err != nil || (cardRecovered && expected.ID != 0) != (index > 0) {
|
||||
t.Fatalf("card component%d inventory index=%d recovered=%v: %v", expected.Field, index, cardRecovered, err)
|
||||
}
|
||||
for field, want := range map[int]uint64{2: expected.ID, 7: 0} {
|
||||
if got, _, err := wire.Varint(item, field); err != nil || got != want {
|
||||
t.Fatalf("card component%d field%d=%d want %d error=%v", expected.Field, field, got, want, err)
|
||||
}
|
||||
}
|
||||
for field, want := range map[int]int32{3: expected.X, 4: expected.Y} {
|
||||
if got, _, err := wire.Varint(item, field); err != nil || int32(got) != want {
|
||||
t.Fatalf("card component%d position%d=%d want %d error=%v", expected.Field, field, int32(got), want, err)
|
||||
}
|
||||
}
|
||||
values := map[int]float32{}
|
||||
if err := wire.Walk(item, func(f wire.Field) error {
|
||||
if f.Number == 5 || f.Number == 6 {
|
||||
if f.Type != 5 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
values[f.Number] = math.Float32frombits(binary.LittleEndian.Uint32(f.Value))
|
||||
}
|
||||
return nil
|
||||
}); err != nil || values[5] != 0 || values[6] != expected.Scale {
|
||||
t.Fatalf("card component%d rotate/scale=%v want 0/%g error=%v", expected.Field, values, expected.Scale, err)
|
||||
}
|
||||
color, _, err := wire.Bytes(item, 8)
|
||||
if err != nil || string(color) != expected.Color {
|
||||
t.Fatalf("card component%d color=%q want %q error=%v", expected.Field, color, expected.Color, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
assertProfile := func(body []byte) {
|
||||
t.Helper()
|
||||
for field, want := range map[int]uint64{1: uint64(identity.OwnerIndex), 4: portrait, 9: wantHuntRank, 16: 12345, 26: 2} {
|
||||
if got, _, err := wire.Varint(body, field); err != nil || got != want {
|
||||
t.Fatalf("profile field%d=%d want %d error=%v", field, got, want, err)
|
||||
}
|
||||
}
|
||||
name, _, err := wire.Bytes(body, 2)
|
||||
if err != nil || string(name) != identity.UserID {
|
||||
t.Fatalf("profile name=%q want %q error=%v", name, identity.UserID, err)
|
||||
}
|
||||
guild, found, err := wire.Bytes(body, 17)
|
||||
if err != nil || !found {
|
||||
t.Fatal("guildless profile must send the non-null GuildBaseInfo used by the client")
|
||||
}
|
||||
if got, _, err := wire.Varint(guild, 1); err != nil || got != 0 {
|
||||
t.Fatalf("guildless profile guild ID=%d want 0 error=%v", got, err)
|
||||
}
|
||||
room, found, err := wire.Bytes(body, 14)
|
||||
if err != nil || !found {
|
||||
t.Fatal("profile room callback has no owner identity")
|
||||
}
|
||||
if got, _, _ := wire.Varint(room, 1); got != uint64(identity.OwnerIndex) {
|
||||
t.Fatal("room identity differs from queried owner")
|
||||
}
|
||||
for _, field := range []int{6, 7, 8, 10, 15, 20, 21, 22, 23, 24, 25, 31, 32, 33} {
|
||||
if got, _, _ := wire.Varint(body, field); got != 0 {
|
||||
t.Fatalf("profile invented unearned progress field%d=%d", field, got)
|
||||
}
|
||||
}
|
||||
card, found, err := wire.Bytes(body, 28)
|
||||
if err != nil || !found {
|
||||
t.Fatal("profile omitted ID card layout required by its UI")
|
||||
}
|
||||
assertCard(card)
|
||||
}
|
||||
after := self()
|
||||
assertProfile(after)
|
||||
recovery := call(request("/IdCardRecovery", nil), 452)
|
||||
cardRecovered = true
|
||||
recovered, found, err := wire.Bytes(recovery, 2)
|
||||
if err != nil || !found {
|
||||
t.Fatal("self-profile's ID card recovery did not complete with a layout")
|
||||
}
|
||||
assertCard(recovered)
|
||||
if bundle, found, _ := wire.Bytes(recovery, 1); !found || len(bundle) == 0 {
|
||||
t.Fatal("initial ID card recovery did not return the actual default item grant")
|
||||
}
|
||||
if bundle, found, _ := wire.Bytes(call(request("/IdCardRecovery", nil), 452), 1); found && len(bundle) != 0 {
|
||||
t.Fatal("second ID card recovery granted default items again")
|
||||
}
|
||||
hunt, err := factory.design.source.MonsterHunt(75)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
combat := func(action func(command.Context) ([]byte, error)) {
|
||||
t.Helper()
|
||||
tx, err := owner.repository.BeginCommand(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if _, err := action(command.Context{Identity: command.Identity{AccountID: accounts[0], SessionID: "profile-combat"}, State: tx}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
entry := wire.AppendVarint(nil, 4, hunt.DeckID)
|
||||
entry = wire.AppendVarint(entry, 5, monsterhunt.BattleMode)
|
||||
entry = wire.AppendVarint(entry, 6, hunt.ID)
|
||||
entry = wire.AppendVarint(entry, 10, 1)
|
||||
combat(func(ctx command.Context) ([]byte, error) {
|
||||
return owner.assembly.monsterHuntService.EnterBattle(ctx, entry, "profile-hunt-clear")
|
||||
})
|
||||
attack := wire.AppendVarint(nil, 1, 1)
|
||||
attack = wire.AppendVarint(attack, 2, 1000)
|
||||
end := wire.AppendVarint(nil, 7, 0)
|
||||
end = wire.AppendBytes(end, 10, wire.AppendBytes(nil, 1, attack))
|
||||
combat(func(ctx command.Context) ([]byte, error) {
|
||||
return owner.assembly.monsterHuntService.CompleteBattle(ctx, end, "profile-hunt-clear")
|
||||
})
|
||||
wantHuntRank = 1
|
||||
assertProfile(self())
|
||||
if err := owner.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner = nil
|
||||
owner, err = factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertProfile(self())
|
||||
for _, target := range []uint64{uint64(other.OwnerIndex), math.MaxInt64, math.MaxUint64, 0} {
|
||||
c := request("/UserContentsInfo", wire.AppendVarint(nil, 2, target))
|
||||
reply, err := owner.Execute(context.Background(), c)
|
||||
if !errors.Is(err, profile.ErrNotFound) || len(reply.Responses) != 0 {
|
||||
t.Fatalf("target%d received a self-profile or leaked another account: response=%v error=%v", target, reply.Responses, err)
|
||||
}
|
||||
}
|
||||
assertProfile(self())
|
||||
}
|
||||
@@ -17,10 +17,85 @@ import (
|
||||
const FileName = "game.json"
|
||||
|
||||
type Config struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Gacha GachaConfig `json:"gacha"`
|
||||
Story StoryConfig `json:"story"`
|
||||
Purchases PurchasesConfig `json:"purchases"`
|
||||
Realtime RealtimeConfig `json:"realtime"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Gacha GachaConfig `json:"gacha"`
|
||||
Story StoryConfig `json:"story"`
|
||||
Purchases PurchasesConfig `json:"purchases"`
|
||||
TextModeration TextModerationConfig `json:"text_moderation"`
|
||||
}
|
||||
|
||||
type TextModerationConfig struct {
|
||||
RuleFiles []string `json:"rule_files"`
|
||||
Provider TextModerationProviderConfig `json:"provider"`
|
||||
}
|
||||
|
||||
type TextModerationProviderConfig struct {
|
||||
Type string `json:"type"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
APIKeyEnv string `json:"api_key_env"`
|
||||
APIKeyHeader string `json:"api_key_header"`
|
||||
Scopes []string `json:"scopes"`
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
FailurePolicy string `json:"failure_policy"`
|
||||
SeverityThreshold int `json:"severity_threshold"`
|
||||
}
|
||||
|
||||
func DefaultTextModeration() TextModerationConfig {
|
||||
return TextModerationConfig{RuleFiles: []string{}, Provider: TextModerationProviderConfig{
|
||||
Type: "off", APIKeyHeader: "Authorization", Scopes: []string{
|
||||
"nickname", "greeting", "master_title", "preset_name", "equipment_preset_name", "equipment_mark",
|
||||
"monster_hunt_preset_name", "guild_raid_preset_name", "colosseum_preset_name",
|
||||
"guild_name", "guild_message", "guild_notice", "chat",
|
||||
},
|
||||
TimeoutMS: 1500, FailurePolicy: "deny", SeverityThreshold: 4,
|
||||
}}
|
||||
}
|
||||
|
||||
func (c TextModerationConfig) Validate() error {
|
||||
if slices.Contains(c.RuleFiles, "") {
|
||||
return fmt.Errorf("text_moderation.rule_files must contain nonempty paths")
|
||||
}
|
||||
p := c.Provider
|
||||
if p.Type != "off" && p.Type != "http_json" && p.Type != "azure_content_safety" {
|
||||
return fmt.Errorf("text_moderation.provider.type must be off, http_json, or azure_content_safety")
|
||||
}
|
||||
if p.TimeoutMS < 10 || p.TimeoutMS > 30000 {
|
||||
return fmt.Errorf("text_moderation.provider.timeout_ms must be between 10 and 30000")
|
||||
}
|
||||
if p.FailurePolicy != "allow" && p.FailurePolicy != "deny" {
|
||||
return fmt.Errorf("text_moderation.provider.failure_policy must be allow or deny")
|
||||
}
|
||||
if p.SeverityThreshold < 0 || p.SeverityThreshold > 7 {
|
||||
return fmt.Errorf("text_moderation.provider.severity_threshold must be between 0 and 7")
|
||||
}
|
||||
if p.Type != "off" && (p.Endpoint == "" || len(p.Scopes) == 0) {
|
||||
return fmt.Errorf("text_moderation active provider requires endpoint and scopes")
|
||||
}
|
||||
if p.Type == "azure_content_safety" && p.APIKeyEnv == "" {
|
||||
return fmt.Errorf("text_moderation Azure provider requires api_key_env")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, scope := range p.Scopes {
|
||||
if !ValidTextScope(scope) || seen[scope] {
|
||||
return fmt.Errorf("text_moderation.provider.scopes must contain unique lowercase identifiers")
|
||||
}
|
||||
seen[scope] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidTextScope(scope string) bool {
|
||||
if len(scope) == 0 || len(scope) > 64 || scope[0] < 'a' || scope[0] > 'z' {
|
||||
return false
|
||||
}
|
||||
for _, r := range scope {
|
||||
allowed := r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_'
|
||||
if !allowed {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type PurchasesConfig struct {
|
||||
@@ -48,7 +123,7 @@ type GachaConfig struct {
|
||||
}
|
||||
|
||||
func Default() Config {
|
||||
return Config{SchemaVersion: 1, Story: StoryConfig{StartPackID: 21}, Purchases: PurchasesConfig{DiamondRecharge: DiamondRechargeConfig{Currency: "free", GoldPerPaidDiamond: 1000, DiamondsPerPaidDiamond: 1}}}
|
||||
return Config{SchemaVersion: 1, Story: StoryConfig{StartPackID: 21}, Purchases: PurchasesConfig{DiamondRecharge: DiamondRechargeConfig{Currency: "free", GoldPerPaidDiamond: 1000, DiamondsPerPaidDiamond: 1}}, TextModeration: DefaultTextModeration()}
|
||||
}
|
||||
|
||||
// Load generates defaults when missing and strictly validates existing files.
|
||||
@@ -104,6 +179,9 @@ func containsNull(value any) bool {
|
||||
}
|
||||
|
||||
func (c Config) Validate() error {
|
||||
if err := c.Realtime.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.SchemaVersion != 1 {
|
||||
return fmt.Errorf("unsupported schema_version %d (expected 1)", c.SchemaVersion)
|
||||
}
|
||||
@@ -119,7 +197,7 @@ func (c Config) Validate() error {
|
||||
if r.GoldPerPaidDiamond < 1 || r.GoldPerPaidDiamond > 1_000_000_000 || r.DiamondsPerPaidDiamond < 1 || r.DiamondsPerPaidDiamond > 1_000_000_000 {
|
||||
return fmt.Errorf("purchases.diamond_recharge conversion rates must be integers between 1 and 1000000000")
|
||||
}
|
||||
return nil
|
||||
return c.TextModeration.Validate()
|
||||
}
|
||||
|
||||
func BesideExecutable() (string, error) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package gameconfig
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type RealtimeConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
TCPListen string `json:"tcp_listen"`
|
||||
UDPListen string `json:"udp_listen"`
|
||||
PublicHost string `json:"public_host"`
|
||||
TCPPort int `json:"tcp_port"`
|
||||
UDPPort int `json:"udp_port"`
|
||||
TLSCertFile string `json:"tls_cert_file"`
|
||||
TLSKeyFile string `json:"tls_key_file"`
|
||||
DevelopmentPlainLoopback bool `json:"development_plain_loopback"`
|
||||
}
|
||||
|
||||
func (c RealtimeConfig) Validate() error {
|
||||
if !c.Enabled {
|
||||
return nil
|
||||
}
|
||||
if c.PublicHost == "" || strings.ContainsAny(c.PublicHost, "/\\@?# \t\r\n") || c.TCPPort < 1 || c.TCPPort > 65535 || c.UDPPort < 1 || c.UDPPort > 65535 {
|
||||
return errors.New("realtime requires a public host and valid TCP/UDP ports")
|
||||
}
|
||||
for _, address := range []string{c.TCPListen, c.UDPListen} {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil || port == "" {
|
||||
return errors.New("realtime listener must be host:port")
|
||||
}
|
||||
if c.DevelopmentPlainLoopback && !net.ParseIP(host).IsLoopback() {
|
||||
return errors.New("plaintext realtime listeners must bind loopback")
|
||||
}
|
||||
}
|
||||
if c.DevelopmentPlainLoopback {
|
||||
if !net.ParseIP(c.PublicHost).IsLoopback() {
|
||||
return errors.New("plaintext realtime public host must be loopback")
|
||||
}
|
||||
} else if c.TLSCertFile == "" || c.TLSKeyFile == "" {
|
||||
return errors.New("realtime TLS certificate and private key paths are required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -34,7 +34,7 @@ type CharAwakeCharacterStage struct {
|
||||
MaximumLevel uint64
|
||||
}
|
||||
|
||||
// CharAwakeDesign is immutable 2.35.10 design data. Account progress remains
|
||||
// CharAwakeDesign is immutable 2.36.7 design data. Account progress remains
|
||||
// in CollectionStore and is indexed by UniqueCharId, as CharAwakeDBInfo is.
|
||||
type CharAwakeDesign struct {
|
||||
Characters map[uint64]CharAwakeCharacter
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type ChatDesign struct {
|
||||
ReportLimit uint64
|
||||
ReportIDs map[uint64]bool
|
||||
GuildHistoryCount, GuildHistoryHours uint64
|
||||
Emojis map[uint64]bool
|
||||
}
|
||||
|
||||
func LoadChatDesign(root, version string) (result *ChatDesign, resultErr error) {
|
||||
db, done, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer done()
|
||||
var raw []byte
|
||||
if err := db.QueryRow("SELECT ProtoBuf FROM RoomChatDefaultTable WHERE id=0").Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := cashScalars(raw, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if v[0] == 0 {
|
||||
return nil, fmt.Errorf("gamedata: missing chat report limit")
|
||||
}
|
||||
d := &ChatDesign{ReportLimit: v[0], ReportIDs: map[uint64]bool{}}
|
||||
rows, err := db.Query("SELECT id FROM RoomChatReportTable")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { resultErr = errors.Join(resultErr, rows.Close()) }()
|
||||
for rows.Next() {
|
||||
var id uint64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.ReportIDs[id] = true
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(d.ReportIDs) == 0 {
|
||||
return nil, fmt.Errorf("gamedata: missing chat report reasons")
|
||||
}
|
||||
if err := db.QueryRow("SELECT ProtoBuf FROM GuildDefaultTable WHERE id=0").Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
history, err := cashScalars(raw, 1, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.GuildHistoryCount, d.GuildHistoryHours = history[0], history[1]
|
||||
d.Emojis = map[uint64]bool{}
|
||||
emojis, err := db.Query("SELECT id FROM ChatResourceTable WHERE chatResourceType=1")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { resultErr = errors.Join(resultErr, emojis.Close()) }()
|
||||
for emojis.Next() {
|
||||
var id uint64
|
||||
if err := emojis.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.Emojis[id] = true
|
||||
}
|
||||
if err := emojis.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
// DatabaseName maps a logical client DB name to its GameData archive entry.
|
||||
// Version 1 is the current 2.35.10 DB schema generation.
|
||||
// Version 1 is the current 2.36.7 DB schema generation.
|
||||
func DatabaseName(logical string) (string, error) {
|
||||
if logical == "" || strings.ContainsAny(logical, `/\\.`) {
|
||||
return "", fmt.Errorf("gamedata: invalid logical database name %q", logical)
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"math"
|
||||
)
|
||||
|
||||
// EquipmentSmeltingDesign contains only static 2.35.10 GameData facts. It does
|
||||
// EquipmentSmeltingDesign contains only static 2.36.7 GameData facts. It does
|
||||
// not decide whether a lower-score result is applied or how mileage is paid:
|
||||
// those are server transactions and require an official response capture.
|
||||
type EquipmentSmeltingDesign struct {
|
||||
|
||||
@@ -25,6 +25,10 @@ func LoadEventPlayCatalog(root, version string) (*EventPlayCatalog, error) {
|
||||
}
|
||||
names := []string{"PackEventHubTable", "PackEventListTable", "PackEventStoryGroupTable", "PackEventStoryTable", "PackEventBattleGroupTable", "PackEventBattleTable", "PackEventMiniGameTable", "FieldMiniGameRewardTable", "FieldMiniGameSpeedTable", "RhythmGameMusicTable", "RhythmGameGradeTable", "SichuanStageTable", "SichuanEventTable", "SichuanRewardTable", "HopscotchStageTable", "HopscotchRewardTable", "HopscotchDefaultTable", "FieldMiniGameSurvivalTable", "ActionGameDefaultTable", "ActionGameMissionTable", "ActionGameStageTable", "FieldMiniGameCharTable", "FieldMiniGameMapTable", "FieldMiniGameUpgradeTable", "FieldMiniGameUpgradeGroupTable", "FieldMiniGameSkillGroupTable", "FieldMiniGameSkillTable", "FieldMiniGameCharLevelTable", "FieldMiniGameMonsterTable", "FieldMiniGameSurvivalItemTable", "FieldMiniGameSurvivalBoxTable", "MGDRewardTable", "MGDWaveTable", "MGDDefaultTable"}
|
||||
names = append(names, "EventLostCoinTable")
|
||||
names = append(names, "ActionGameTable", "ActionGameCharTable")
|
||||
names = append(names, "FishingDefaultTable", "FishingMapTable", "FishingMapGroupTable", "FishingBoatTable", "FishingBoatDesignTable", "FishingRodTable", "FishingItemTable", "FishingCharTable", "FishingFishTable", "FishingFishPoolTable", "FishingFishSizePoolTable", "FishingGradePoolTable", "FishingCastingTable", "FishingBuffTable", "FishingBoatBuffTable", "FishingFishSkillTable", "FishingTimeTable")
|
||||
names = append(names, "FishingBuyItemTable", "FishingSellItemTable", "FishingShopTable", "FishingPricePremiumDefaultTable")
|
||||
names = append(names, "GameDefaultTable", "FishingInventoryBuyTable")
|
||||
for _, name := range names {
|
||||
rows, e := db.Query("SELECT ProtoBuf FROM " + name)
|
||||
if e != nil {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package gamedata
|
||||
|
||||
import "fmt"
|
||||
|
||||
type FriendRules struct{ Friends, Sent, Received, Recommended, ExpireDays uint64 }
|
||||
|
||||
func LoadFriendRules(root, version string) (FriendRules, error) {
|
||||
db, done, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
return FriendRules{}, err
|
||||
}
|
||||
defer done()
|
||||
var raw []byte
|
||||
if err := db.QueryRow("SELECT ProtoBuf FROM CommunityDefineTable WHERE id=0").Scan(&raw); err != nil {
|
||||
return FriendRules{}, err
|
||||
}
|
||||
v, err := cashScalars(raw, 3, 6, 5, 4, 1)
|
||||
if err != nil {
|
||||
return FriendRules{}, err
|
||||
}
|
||||
for _, n := range v {
|
||||
if n == 0 || n > 256 {
|
||||
return FriendRules{}, fmt.Errorf("gamedata: invalid friend limits")
|
||||
}
|
||||
}
|
||||
return FriendRules{Friends: v[0], Sent: v[1], Received: v[2], Recommended: v[3], ExpireDays: v[4]}, nil
|
||||
}
|
||||
@@ -1579,6 +1579,9 @@ func LoadInfiniteGachaForSchedules(root, version string, groups []uint64) (*Infi
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if infiniteGroupID == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var gacha []byte
|
||||
if err := db.QueryRow("SELECT ProtoBuf FROM GachaTable WHERE id=?", infiniteGachaID).Scan(&gacha); err != nil {
|
||||
return nil, fmt.Errorf("gamedata: infinite gacha: %w", err)
|
||||
|
||||
@@ -46,8 +46,8 @@ func loadInfiniteGachaIdentity(db *sql.DB, selectedGroups []uint64) (groupID, ga
|
||||
if err = rows.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
if groupID == 0 || gachaID == 0 {
|
||||
err = fmt.Errorf("gamedata: infinite gacha group missing")
|
||||
if groupID != 0 && gachaID == 0 {
|
||||
err = fmt.Errorf("gamedata: infinite gacha group %d has no draw", groupID)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type GuildRules struct {
|
||||
RenameCost Reward
|
||||
Flags, Emblems map[uint64]bool
|
||||
MaxMembers, ApplicationLimit, ApplicationHours, LeaveDelayHours, DeleteDelayHours, ListCount uint64
|
||||
CreateCost, Attendance Reward
|
||||
}
|
||||
|
||||
type GuildRaidRules struct {
|
||||
FlagVersions []GuildRaidFlagVersion
|
||||
TurnAddScore, TurnScoreValue, SupportScore float64
|
||||
DailySupporterUses, BasicSupportReward, RentalSupportReward, RewardMailID uint64
|
||||
Bosses map[uint64]map[uint64]GuildRaidBoss
|
||||
ScoreRewards []GuildRaidScoreReward
|
||||
RankRewards []GuildRaidRankReward
|
||||
}
|
||||
|
||||
type GuildRaidFlagVersion struct{ GroupID, MinSeason, MaxSeason uint64 }
|
||||
|
||||
type GuildRaidBoss struct {
|
||||
PackID, CharID uint64
|
||||
healthRate, healthSlope float64
|
||||
GroupID, Level, AddScore, DeckID, MonsterID, PartsGroupID uint64
|
||||
BattleMap, ReadyMap string
|
||||
MaxHP uint64
|
||||
Rewards []Reward
|
||||
}
|
||||
|
||||
type GuildRaidScoreReward struct {
|
||||
ID, Score uint64
|
||||
Rewards []Reward
|
||||
}
|
||||
type GuildRaidRankReward struct {
|
||||
ID uint64
|
||||
TopPercent float64
|
||||
Rewards []Reward
|
||||
}
|
||||
type SupporterRules struct {
|
||||
DailyUses, DailyRecommendedUses, DailyRewardClaims uint64
|
||||
Reward Reward
|
||||
}
|
||||
type GuildDesign struct {
|
||||
Open ContentOpenRule
|
||||
Guild GuildRules
|
||||
Raid GuildRaidRules
|
||||
Supporters SupporterRules
|
||||
}
|
||||
|
||||
func LoadGuildDesign(root, version string) (*GuildDesign, error) {
|
||||
db, done, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer done()
|
||||
d := &GuildDesign{Raid: GuildRaidRules{Bosses: map[uint64]map[uint64]GuildRaidBoss{}}}
|
||||
var raw []byte
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM ContentOpenTable WHERE groupId=17 AND id=1").Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opening, err := cashScalars(raw, 4, 5, 6)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.Open = ContentOpenRule{TutorialID: opening[0], SquadLevel: opening[1], TicketID: opening[2]}
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM GuildDefaultTable WHERE id=0").Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := cashScalars(raw, 12, 14, 15, 13, 9, 8, 7, 6, 5, 4, 3, 11)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.Guild = GuildRules{MaxMembers: v[0], ApplicationLimit: v[1], ApplicationHours: v[2], LeaveDelayHours: v[3], DeleteDelayHours: v[4], CreateCost: Reward{Type: v[5], ID: v[6], Count: v[7]}, Attendance: Reward{Type: v[8], ID: v[9], Count: v[10]}}
|
||||
d.Guild.ListCount = v[11]
|
||||
d.Guild.Flags, d.Guild.Emblems = map[uint64]bool{}, map[uint64]bool{}
|
||||
for _, entry := range []struct {
|
||||
table string
|
||||
out map[uint64]bool
|
||||
}{{"GuildFlagResourceTable", d.Guild.Flags}, {"GuildEmblemResourceTable", d.Guild.Emblems}} {
|
||||
if err = readCashMetadata(db, entry.table, func(raw []byte) error {
|
||||
id, e := optionalScalar(raw, 2)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if id > math.MaxInt32 {
|
||||
return fmt.Errorf("gamedata: invalid guild icon")
|
||||
}
|
||||
entry.out[id] = true
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err = readCashMetadata(db, "UseItemTable", func(raw []byte) error {
|
||||
kind, e := optionalScalar(raw, 11)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if kind != 2 {
|
||||
return nil
|
||||
}
|
||||
id, e := optionalScalar(raw, 3)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if id == 0 || d.Guild.RenameCost.ID != 0 {
|
||||
return fmt.Errorf("gamedata: ambiguous guild rename ticket")
|
||||
}
|
||||
d.Guild.RenameCost = Reward{Type: 14, ID: id, Count: 1}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.Guild.RenameCost.ID == 0 || len(d.Guild.Flags) == 0 || len(d.Guild.Emblems) == 0 {
|
||||
return nil, fmt.Errorf("gamedata: incomplete guild customization")
|
||||
}
|
||||
if d.Guild.MaxMembers == 0 || d.Guild.ListCount == 0 || d.Guild.ApplicationLimit == 0 || d.Guild.ApplicationHours == 0 || d.Guild.LeaveDelayHours == 0 || d.Guild.DeleteDelayHours == 0 || d.Guild.CreateCost.Type == 0 || d.Guild.CreateCost.Count == 0 {
|
||||
return nil, fmt.Errorf("gamedata: invalid guild defaults")
|
||||
}
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM GuildRaidDefaultTable WHERE id=0").Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err = cashScalars(raw, 3, 21, 22, 15)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.Raid.DailySupporterUses, d.Raid.BasicSupportReward, d.Raid.RentalSupportReward, d.Raid.RewardMailID = v[0], v[1], v[2], v[3]
|
||||
if d.Raid.TurnAddScore, err = optionalDouble(raw, 24); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.Raid.TurnScoreValue, err = optionalDouble(raw, 25); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.Raid.SupportScore, err = optionalDouble(raw, 23); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM SupportCharacterDefaultTable WHERE id=0").Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err = cashScalars(raw, 3, 2, 1, 7, 6, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.Supporters = SupporterRules{DailyUses: v[0], DailyRecommendedUses: v[1], DailyRewardClaims: v[2], Reward: Reward{Type: v[3], ID: v[4], Count: v[5]}}
|
||||
if err = readCashMetadata(db, "GuildRaidBossTable", func(raw []byte) error {
|
||||
v, e := cashScalars(raw, 6, 7, 1, 15, 12, 13)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
r := GuildRaidBoss{GroupID: v[0], Level: v[1], AddScore: v[2], DeckID: v[3], MonsterID: v[4], PartsGroupID: v[5]}
|
||||
battleMap, _, e := wire.Bytes(raw, 2)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
readyMap, _, e := wire.Bytes(raw, 16)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
r.BattleMap, r.ReadyMap = string(battleMap), string(readyMap)
|
||||
healthRate, e := optionalDouble(raw, 10)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
healthSlope, e := optionalDouble(raw, 11)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
r.healthRate, r.healthSlope = healthRate, healthSlope
|
||||
|
||||
if r.GroupID == 0 || r.Level == 0 || r.DeckID == 0 {
|
||||
return fmt.Errorf("gamedata: invalid guild raid boss")
|
||||
}
|
||||
if r.Rewards, e = parallelRewards(raw, 19, 18, 17); e != nil {
|
||||
return e
|
||||
}
|
||||
if d.Raid.Bosses[r.GroupID] == nil {
|
||||
d.Raid.Bosses[r.GroupID] = map[uint64]GuildRaidBoss{}
|
||||
}
|
||||
if _, exists := d.Raid.Bosses[r.GroupID][r.Level]; exists {
|
||||
return fmt.Errorf("gamedata: duplicate guild raid boss")
|
||||
}
|
||||
d.Raid.Bosses[r.GroupID][r.Level] = r
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packDBs := map[uint64]*sql.DB{}
|
||||
for group, bosses := range d.Raid.Bosses {
|
||||
for level, r := range bosses {
|
||||
mapName, _, ok := strings.Cut(strings.TrimPrefix(r.BattleMap, "Map"), "_")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("gamedata: invalid guild raid map %q", r.BattleMap)
|
||||
}
|
||||
pack, e := strconv.ParseUint(mapName, 10, 32)
|
||||
if e != nil || pack == 0 {
|
||||
return nil, fmt.Errorf("gamedata: invalid guild raid map %q", r.BattleMap)
|
||||
}
|
||||
r.PackID = pack
|
||||
packDB := packDBs[pack]
|
||||
if packDB == nil {
|
||||
var release func()
|
||||
packDB, release, e = OpenDatabase(root, version, fmt.Sprintf("pack%d", pack))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer release()
|
||||
packDBs[pack] = packDB
|
||||
}
|
||||
var deckRaw []byte
|
||||
if e = packDB.QueryRow("SELECT ProtoBuf FROM BattleDeckTable WHERE id=?", r.DeckID).Scan(&deckRaw); e != nil {
|
||||
return nil, fmt.Errorf("guild boss %d/%d deck %d: %w", group, level, r.DeckID, e)
|
||||
}
|
||||
chars, e := packedInts(deckRaw, 14)
|
||||
if e != nil || len(chars) == 0 {
|
||||
return nil, fmt.Errorf("guild boss %d/%d has no main character", group, level)
|
||||
}
|
||||
r.CharID = chars[0]
|
||||
var charRaw []byte
|
||||
if e := db.QueryRow("SELECT ProtoBuf FROM CharTable WHERE id=?", r.CharID).Scan(&charRaw); e != nil {
|
||||
return nil, fmt.Errorf("guild boss %d/%d: %w", group, level, e)
|
||||
}
|
||||
baseHP, e := optionalDouble(charRaw, 11)
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("guild boss %d/%d: %w", group, level, e)
|
||||
}
|
||||
growth, e := optionalScalar(charRaw, 1)
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("guild boss %d/%d: %w", group, level, e)
|
||||
}
|
||||
var growthRaw []byte
|
||||
if e = db.QueryRow("SELECT ProtoBuf FROM CharGrowthTable WHERE id=?", growth).Scan(&growthRaw); e != nil {
|
||||
return nil, fmt.Errorf("guild boss %d/%d: %w", group, level, e)
|
||||
}
|
||||
levelGroup, e := optionalScalar(growthRaw, 1)
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("guild boss %d/%d: %w", group, level, e)
|
||||
}
|
||||
var levelRaw []byte
|
||||
if e = db.QueryRow("SELECT ProtoBuf FROM CharLevelTable WHERE groupId=? AND id=?", levelGroup, r.Level).Scan(&levelRaw); e != nil {
|
||||
return nil, fmt.Errorf("guild boss %d/%d: %w", group, level, e)
|
||||
}
|
||||
levelHP, e := optionalDouble(levelRaw, 6)
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("guild boss %d/%d: %w", group, level, e)
|
||||
}
|
||||
hp := math.Floor(baseHP + (1+levelHP)*math.Pow(float64(r.Level-1), 2)*r.healthRate*r.healthSlope)
|
||||
if math.IsNaN(hp) || math.IsInf(hp, 0) || hp < 1 || hp >= float64(math.MaxInt64) {
|
||||
return nil, fmt.Errorf("gamedata: invalid guild boss health")
|
||||
}
|
||||
r.MaxHP = uint64(hp)
|
||||
d.Raid.Bosses[group][level] = r
|
||||
}
|
||||
}
|
||||
if err = readCashMetadata(db, "GuildRaidRewardTable", func(raw []byte) error {
|
||||
v, e := cashScalars(raw, 1, 5)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
r := GuildRaidScoreReward{ID: v[0], Score: v[1]}
|
||||
if r.Rewards, e = parallelRewards(raw, 4, 3, 2); e != nil {
|
||||
return e
|
||||
}
|
||||
if r.ID == 0 || r.Score == 0 || len(r.Rewards) == 0 {
|
||||
return fmt.Errorf("gamedata: invalid guild raid score reward")
|
||||
}
|
||||
d.Raid.ScoreRewards = append(d.Raid.ScoreRewards, r)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = readCashMetadata(db, "GuildRaidRankTable", func(raw []byte) error {
|
||||
id, e := optionalScalar(raw, 1)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
percent, e := optionalDouble(raw, 2)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
r := GuildRaidRankReward{ID: id, TopPercent: percent}
|
||||
if r.Rewards, e = parallelRewards(raw, 6, 5, 4); e != nil {
|
||||
return e
|
||||
}
|
||||
if id == 0 || math.IsNaN(percent) || math.IsInf(percent, 0) || percent <= 0 || percent > 100 || len(r.Rewards) == 0 {
|
||||
return fmt.Errorf("gamedata: invalid guild raid rank reward")
|
||||
}
|
||||
d.Raid.RankRewards = append(d.Raid.RankRewards, r)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
slices.SortFunc(d.Raid.ScoreRewards, func(a, b GuildRaidScoreReward) int {
|
||||
if a.Score < b.Score {
|
||||
return -1
|
||||
}
|
||||
if a.Score > b.Score {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
slices.SortFunc(d.Raid.RankRewards, func(a, b GuildRaidRankReward) int {
|
||||
if a.TopPercent < b.TopPercent {
|
||||
return -1
|
||||
}
|
||||
if a.TopPercent > b.TopPercent {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
if len(d.Raid.Bosses) == 0 || len(d.Raid.ScoreRewards) == 0 || len(d.Raid.RankRewards) == 0 || d.Raid.DailySupporterUses == 0 {
|
||||
return nil, fmt.Errorf("gamedata: incomplete guild raid design")
|
||||
}
|
||||
flagGroups := map[uint64]bool{}
|
||||
if err = readCashMetadata(db, "GuildRaidFlagTable", func(raw []byte) error {
|
||||
group, e := optionalScalar(raw, 1)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if group == 0 {
|
||||
return fmt.Errorf("gamedata: invalid guild raid flag group")
|
||||
}
|
||||
flagGroups[group] = true
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(flagGroups) != 1 {
|
||||
return nil, fmt.Errorf("gamedata: guild raid flag groups require an explicit season mapping")
|
||||
}
|
||||
minimum, maximum := uint64(math.MaxUint64), uint64(0)
|
||||
for season := range d.Raid.Bosses {
|
||||
minimum = min(minimum, season)
|
||||
maximum = max(maximum, season)
|
||||
}
|
||||
for group := range flagGroups {
|
||||
d.Raid.FlagVersions = []GuildRaidFlagVersion{{GroupID: group, MinSeason: minimum, MaxSeason: maximum}}
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
type MissionWindow struct{ Start, End time.Time }
|
||||
|
||||
func loadMissionWindows(db *sql.DB, design *MissionDesign) error {
|
||||
rows, err := db.Query("SELECT groupId,id,ProtoBuf FROM ChangeMissionTable")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
design.Windows = map[[2]uint64]MissionWindow{}
|
||||
for rows.Next() {
|
||||
var group, id uint64
|
||||
var raw []byte
|
||||
if err := rows.Scan(&group, &id, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
var window MissionWindow
|
||||
for field, target := range map[int]*time.Time{1: &window.End, 4: &window.Start} {
|
||||
text, found, err := wire.Bytes(raw, field)
|
||||
if err != nil || !found {
|
||||
return fmt.Errorf("gamedata: missing mission window %d/%d", group, id)
|
||||
}
|
||||
*target, err = time.Parse("2006-01-02", string(text))
|
||||
if err != nil {
|
||||
return fmt.Errorf("gamedata: invalid mission window %d/%d: %w", group, id, err)
|
||||
}
|
||||
}
|
||||
key := [2]uint64{group, id}
|
||||
if _, exists := design.Windows[key]; exists {
|
||||
return fmt.Errorf("gamedata: duplicate mission window %d/%d", group, id)
|
||||
}
|
||||
design.Windows[key] = window
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
@@ -24,6 +24,7 @@ type AchievementKey struct{ ContentsGroup, GroupID, ID uint64 }
|
||||
type MissionDesign struct {
|
||||
Missions map[MissionKey][]Reward
|
||||
Conditions map[MissionKey]MissionCondition
|
||||
Windows map[[2]uint64]MissionWindow
|
||||
Sections map[SectionRewardKey]SectionRewardDesign
|
||||
Achievements map[AchievementKey]AchievementDesign
|
||||
}
|
||||
@@ -73,6 +74,9 @@ func loadMissionDesignDB(db *sql.DB) (*MissionDesign, error) {
|
||||
if err := loadMissionRows(db, design); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := loadMissionWindows(db, design); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := loadSectionRows(db, design); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -20,10 +20,17 @@ type MonsterHunt struct {
|
||||
TeamOpenLevels []uint64
|
||||
Rewards map[uint64]MonsterHuntRewards
|
||||
Ranks map[uint64][]MonsterHuntRankReward
|
||||
RankingVersion uint64
|
||||
BattleLevels map[uint64]MonsterHuntBattleLevel
|
||||
baseHP, healthRate, healthSlope, stage2Ratio, stage3Ratio float64
|
||||
stage2Level, stage3Level uint64
|
||||
}
|
||||
|
||||
type MonsterHuntBattleLevel struct {
|
||||
DamageAdd uint64
|
||||
HealthAdd float64
|
||||
}
|
||||
|
||||
func LoadMonsterHunt(root, version string, id uint64) (*MonsterHunt, error) {
|
||||
db, done, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
@@ -40,15 +47,15 @@ func loadMonsterHunt(db *sql.DB, id uint64) (*MonsterHunt, error) {
|
||||
if err := db.QueryRow("SELECT ProtoBuf FROM MonsterHuntTable WHERE id=?", id).Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d := &MonsterHunt{Rewards: map[uint64]MonsterHuntRewards{}, Ranks: map[uint64][]MonsterHuntRankReward{}}
|
||||
for n, p := range map[int]*uint64{8: &d.ID, 18: &d.PackID, 16: &d.MonsterID, 1: &d.DeckID, 22: &d.RewardGroupID, 23: &d.RewardLevel, 14: &d.ChallengeableLevel, 26: &d.stage2Level, 28: &d.stage3Level} {
|
||||
d := &MonsterHunt{Rewards: map[uint64]MonsterHuntRewards{}, Ranks: map[uint64][]MonsterHuntRankReward{}, BattleLevels: map[uint64]MonsterHuntBattleLevel{}}
|
||||
for n, p := range map[int]*uint64{8: &d.ID, 19: &d.PackID, 17: &d.MonsterID, 1: &d.DeckID, 23: &d.RewardGroupID, 24: &d.RewardLevel, 14: &d.ChallengeableLevel, 27: &d.stage2Level, 29: &d.stage3Level, 16: &d.RankingVersion} {
|
||||
v, e := optionalScalar(raw, n)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
*p = v
|
||||
}
|
||||
for n, p := range map[int]*float64{11: &d.healthRate, 12: &d.healthSlope, 27: &d.stage2Ratio, 29: &d.stage3Ratio} {
|
||||
for n, p := range map[int]*float64{11: &d.healthRate, 12: &d.healthSlope, 28: &d.stage2Ratio, 30: &d.stage3Ratio} {
|
||||
v, _, e := fixed64Double(raw, n)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
@@ -56,11 +63,11 @@ func loadMonsterHunt(db *sql.DB, id uint64) (*MonsterHunt, error) {
|
||||
*p = v
|
||||
}
|
||||
var err error
|
||||
d.TeamOpenLevels, err = packedInts(raw, 32)
|
||||
d.TeamOpenLevels, err = packedInts(raw, 33)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
group, err := optionalScalar(raw, 19)
|
||||
group, err := optionalScalar(raw, 20)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -127,6 +134,37 @@ func loadMonsterHunt(db *sql.DB, id uint64) (*MonsterHunt, error) {
|
||||
return nil, err
|
||||
}
|
||||
d.baseHP = math.Trunc(base.Health*deckRate*100) / 100
|
||||
rows, err = db.Query("SELECT id,ProtoBuf FROM MonsterHuntBattleTable WHERE groupId=? ORDER BY id", id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var level uint64
|
||||
var raw []byte
|
||||
if err = rows.Scan(&level, &raw); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
var design MonsterHuntBattleLevel
|
||||
design.DamageAdd, err = optionalScalar(raw, 4)
|
||||
if err == nil {
|
||||
design.HealthAdd, _, err = fixed64Double(raw, 5)
|
||||
}
|
||||
if err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
if level == 0 || design.DamageAdd > math.MaxInt32 || math.IsNaN(design.HealthAdd) || math.IsInf(design.HealthAdd, 0) || design.HealthAdd < 0 || design.HealthAdd >= float64(math.MaxInt64) {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("gamedata: invalid hunt battle level %d", level)
|
||||
}
|
||||
d.BattleLevels[level] = design
|
||||
}
|
||||
err = rows.Err()
|
||||
_ = rows.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err = db.Query("SELECT level, ProtoBuf FROM MonsterHuntRewardTable WHERE groupId=? ORDER BY level", d.RewardGroupID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -192,7 +230,7 @@ func loadMonsterHunt(db *sql.DB, id uint64) (*MonsterHunt, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.ID != id || d.PackID == 0 || d.DeckID == 0 || d.MaxLevel == 0 || d.baseHP <= 0 {
|
||||
if d.ID != id || d.PackID == 0 || d.MonsterID == 0 || d.DeckID == 0 || d.MaxLevel == 0 || d.baseHP <= 0 || d.RankingVersion > 1 {
|
||||
return nil, fmt.Errorf("gamedata: invalid hunt %d design", id)
|
||||
}
|
||||
return d, nil
|
||||
@@ -221,8 +259,14 @@ func (d *MonsterHunt) HP(level uint64) (uint64, error) {
|
||||
for value/scale >= 1000 {
|
||||
scale *= 10
|
||||
}
|
||||
return value / scale * scale, nil
|
||||
value = value / scale * scale
|
||||
addition := uint64(d.BattleLevels[level].HealthAdd)
|
||||
if addition > math.MaxInt64-value {
|
||||
return 0, fmt.Errorf("gamedata: hunt HP addition overflow")
|
||||
}
|
||||
return value + addition, nil
|
||||
}
|
||||
|
||||
func monsterHuntRewardArrays(raw []byte, typeField, idField, countField int) ([]BattleReward, error) {
|
||||
types, e := packedInts(raw, typeField)
|
||||
if e != nil {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type NativeFishing struct {
|
||||
Capacity int
|
||||
LoadingLimit, ReconnectWindow, Duration time.Duration
|
||||
}
|
||||
|
||||
func (c *EventPlayCatalog) NativeFishingRules(mapID, boatLevel, skin uint64) (NativeFishing, error) {
|
||||
var out NativeFishing
|
||||
if _, err := c.Row("FishingMapGroupTable", 5, mapID); err != nil {
|
||||
return out, err
|
||||
}
|
||||
b, err := c.Row("FishingBoatTable", 8, boatLevel)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
capacity, _ := optionalScalar(b, 9)
|
||||
if capacity == 0 || capacity > 5 {
|
||||
return out, fmt.Errorf("gamedata: boat does not support multiplayer")
|
||||
}
|
||||
skins, err := packedInts(b, 5)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
found := false
|
||||
for _, id := range skins {
|
||||
found = found || id == skin
|
||||
}
|
||||
if !found {
|
||||
return out, fmt.Errorf("gamedata: boat skin incompatible")
|
||||
}
|
||||
d, err := c.Row("FishingDefaultTable", 25, 0)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
load, _ := optionalScalar(d, 26)
|
||||
out.Capacity = int(capacity)
|
||||
out.LoadingLimit = time.Duration(load) * time.Millisecond
|
||||
out.ReconnectWindow = time.Duration(fishingDouble(d, 41) * float64(time.Second))
|
||||
out.Duration = time.Duration(fishingDouble(d, 42) * float64(time.Second))
|
||||
if out.LoadingLimit <= 0 || out.ReconnectWindow <= 0 || out.Duration <= 0 {
|
||||
return out, fmt.Errorf("gamedata: invalid fishing room limits")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func fishingDouble(b []byte, field int) float64 {
|
||||
v, _ := optionalDouble(b, field)
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type NativeMinigame struct {
|
||||
GroupID, StageID, CharacterID, MonsterID, LastWave uint64
|
||||
Capacity int
|
||||
LoadingLimit, Duration time.Duration
|
||||
}
|
||||
|
||||
// NativeMinigameRules validates the selected event and client character/monster
|
||||
// against installed design rows. Party limits come from the current client UI.
|
||||
func (c *EventPlayCatalog) NativeMinigameRules(family string, eventID, character, monster uint64, solo bool) (NativeMinigame, error) {
|
||||
event, err := c.Row("PackEventMiniGameTable", 8, eventID)
|
||||
if err != nil {
|
||||
return NativeMinigame{}, err
|
||||
}
|
||||
kind, _ := optionalScalar(event, 3)
|
||||
group, _ := optionalScalar(event, 4)
|
||||
r := NativeMinigame{}
|
||||
switch family {
|
||||
case "Action":
|
||||
if kind != 8 {
|
||||
return r, fmt.Errorf("gamedata: event is not action")
|
||||
}
|
||||
game, e := c.Row("ActionGameTable", 3, group)
|
||||
if e != nil {
|
||||
return r, e
|
||||
}
|
||||
r.GroupID, _ = optionalScalar(game, 4)
|
||||
for _, row := range c.Rows("ActionGameCharTable", 14, character) {
|
||||
g, _ := optionalScalar(row, 12)
|
||||
t, _ := optionalScalar(row, 16)
|
||||
if g == 1 && t == 0 {
|
||||
r.CharacterID = character
|
||||
}
|
||||
}
|
||||
if r.CharacterID == 0 {
|
||||
return r, fmt.Errorf("gamedata: action character unavailable")
|
||||
}
|
||||
for _, stage := range c.Rows("ActionGameStageTable", 3, r.GroupID) {
|
||||
m, _ := optionalScalar(stage, 1)
|
||||
typ, _ := optionalScalar(stage, 11)
|
||||
if m != monster || solo && typ != 1 || !solo && typ != 2 {
|
||||
continue
|
||||
}
|
||||
r.MonsterID = m
|
||||
r.StageID, _ = optionalScalar(stage, 4)
|
||||
limit, _ := optionalScalar(stage, 12)
|
||||
r.Duration = time.Duration(limit) * time.Second
|
||||
}
|
||||
if r.StageID == 0 || r.Duration <= 0 {
|
||||
return r, fmt.Errorf("gamedata: action stage unavailable")
|
||||
}
|
||||
d, e := c.Row("ActionGameDefaultTable", 10, 0)
|
||||
if e != nil {
|
||||
return r, e
|
||||
}
|
||||
loading, _ := optionalScalar(d, 13)
|
||||
r.LoadingLimit = time.Duration(loading) * time.Millisecond
|
||||
r.Capacity = 2
|
||||
case "Defense":
|
||||
if kind != 7 {
|
||||
return r, fmt.Errorf("gamedata: event is not defense")
|
||||
}
|
||||
for _, row := range c.Tables["MGDWaveTable"] {
|
||||
id, _ := optionalScalar(row, 2)
|
||||
if id > r.LastWave {
|
||||
r.LastWave = id
|
||||
}
|
||||
}
|
||||
if r.LastWave == 0 {
|
||||
return r, fmt.Errorf("gamedata: defense waves unavailable")
|
||||
}
|
||||
d, e := c.Row("MGDDefaultTable", 9, 0)
|
||||
if e != nil {
|
||||
return r, e
|
||||
}
|
||||
loading, _ := optionalScalar(d, 10)
|
||||
r.LoadingLimit = time.Duration(loading) * time.Millisecond
|
||||
r.Capacity = 4
|
||||
default:
|
||||
return r, fmt.Errorf("gamedata: unknown native minigame")
|
||||
}
|
||||
if solo {
|
||||
r.Capacity = 1
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func LoadNicknameTicketID(root, version string) (uint64, error) {
|
||||
db, release, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer release()
|
||||
rows, err := db.Query("SELECT ProtoBuf FROM UseItemTable")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
var ticket uint64
|
||||
for rows.Next() {
|
||||
var raw []byte
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
kind, err := optionalScalar(raw, 11)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if kind != 1 {
|
||||
continue
|
||||
}
|
||||
id, err := optionalScalar(raw, 3)
|
||||
if err != nil || id == 0 || ticket != 0 {
|
||||
return 0, fmt.Errorf("gamedata: ambiguous nickname change ticket")
|
||||
}
|
||||
ticket = id
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if ticket == 0 {
|
||||
return 0, fmt.Errorf("gamedata: nickname change ticket missing")
|
||||
}
|
||||
return ticket, nil
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
// LoadPackSummaryTargets follows PackMapRewardInfo.IsSummaryTargetPackType in
|
||||
// the 2.35.10 client. Pack identities and types come from the installed tables.
|
||||
// the 2.36.7 client. Pack identities and types come from the installed tables.
|
||||
func LoadPackSummaryTargets(root, version string) (map[int]bool, error) {
|
||||
db, closeDB, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
|
||||
@@ -71,7 +71,7 @@ type CharacterPictorialMeta struct {
|
||||
UsePackTemporary bool
|
||||
}
|
||||
|
||||
// PictorialDesign is immutable 2.35.10 design data. Dynamic account state is
|
||||
// PictorialDesign is immutable 2.36.7 design data. Dynamic account state is
|
||||
// deliberately not copied here: callers match their current ownership against
|
||||
// these rows each time they build PictorialBookInfo or AllCharRefresh.
|
||||
type PictorialDesign struct {
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ProfileCardItem struct {
|
||||
ID, Kind, MaxCount, Unlock uint64
|
||||
Magic []uint64
|
||||
}
|
||||
|
||||
type ProfileCardShop struct {
|
||||
MaxCount uint64
|
||||
Costs []Reward
|
||||
}
|
||||
|
||||
type ProfileDesign struct {
|
||||
Defaults []IdCardDefault
|
||||
CardItems map[uint64]ProfileCardItem
|
||||
Shop map[uint64]ProfileCardShop
|
||||
Titles map[uint64]bool
|
||||
Colors map[string]bool
|
||||
KindLimits map[uint64]uint64
|
||||
PresetLimit, PlacementLimit uint64
|
||||
DefaultReward Reward
|
||||
DefaultPortraitCostumeID uint64
|
||||
}
|
||||
|
||||
func LoadProfileDesign(root, version string) (*ProfileDesign, error) {
|
||||
defaults, err := LoadIdCardDefaults(root, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, done, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer done()
|
||||
d := &ProfileDesign{Defaults: defaults, CardItems: map[uint64]ProfileCardItem{}, Shop: map[uint64]ProfileCardShop{}, Titles: map[uint64]bool{}, Colors: map[string]bool{}, KindLimits: map[uint64]uint64{}}
|
||||
var raw []byte
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.DefaultPortraitCostumeID, err = optionalScalar(raw, 29)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.DefaultPortraitCostumeID == 0 || d.DefaultPortraitCostumeID > math.MaxInt32 {
|
||||
return nil, fmt.Errorf("gamedata: invalid default portrait costume")
|
||||
}
|
||||
if err := readCashMetadata(db, "IdCardItemTable", func(raw []byte) error {
|
||||
v, err := cashScalars(raw, 3, 13, 10, 14)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
magic, err := packedInts(raw, 9)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if v[0] == 0 || v[1] > 6 || v[2] == 0 {
|
||||
return fmt.Errorf("gamedata: invalid ID card item")
|
||||
}
|
||||
d.CardItems[v[0]] = ProfileCardItem{ID: v[0], Kind: v[1], MaxCount: v[2], Unlock: v[3], Magic: magic}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := readCashMetadata(db, "IdCardItemtShopTable", func(raw []byte) error {
|
||||
v, err := cashScalars(raw, 2, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
costs, err := parallelRewards(raw, 5, 4, 3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if v[0] == 0 || v[1] == 0 || len(costs) == 0 {
|
||||
return fmt.Errorf("gamedata: invalid ID card shop")
|
||||
}
|
||||
d.Shop[v[0]] = ProfileCardShop{MaxCount: v[1], Costs: costs}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := readCashMetadata(db, "TitleItemTable", func(raw []byte) error {
|
||||
id, err := optionalScalar(raw, 2)
|
||||
if err == nil {
|
||||
d.Titles[id] = true
|
||||
}
|
||||
return err
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := readCashMetadata(db, "IdCardItemEnumTable", func(raw []byte) error {
|
||||
v, err := cashScalars(raw, 1, 2)
|
||||
if err == nil {
|
||||
d.KindLimits[v[0]] = v[1]
|
||||
}
|
||||
return err
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for table, field := range map[string]int{"IdCardTextColortTable": 2, "IdCardBgEffectColortTable": 1} {
|
||||
if err := readCashMetadata(db, table, func(raw []byte) error {
|
||||
color, _, err := wire.Bytes(raw, field)
|
||||
if err == nil {
|
||||
d.Colors[strings.ToUpper(string(color))] = true
|
||||
}
|
||||
return err
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := readCashMetadata(db, "IdCardDefaultTable", func(raw []byte) error {
|
||||
v, err := cashScalars(raw, 5, 6, 7, 9, 10)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.DefaultReward = Reward{Type: v[2], ID: v[1], Count: v[0]}
|
||||
d.PresetLimit, d.PlacementLimit = v[3], v[4]
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.PresetLimit == 0 || d.PlacementLimit == 0 || d.DefaultReward.Count == 0 {
|
||||
return nil, fmt.Errorf("gamedata: invalid ID card defaults")
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
type IdCardDefault struct {
|
||||
Kind, ID, Layer uint64
|
||||
X, Y int32
|
||||
Rotate, Scale float32
|
||||
Color string
|
||||
}
|
||||
|
||||
func LoadIdCardDefaults(root, version string) ([]IdCardDefault, error) {
|
||||
db, done, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer done()
|
||||
rows, err := db.Query("SELECT ProtoBuf FROM DefaultIdCardSettingTable ORDER BY id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
var out []IdCardDefault
|
||||
for rows.Next() {
|
||||
var raw []byte
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := cashScalars(raw, 1, 4, 5, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
color, _, err := wire.Bytes(raw, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x, err := optionalDouble(raw, 6)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
y, err := optionalDouble(raw, 7)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scale, err := optionalDouble(raw, 9)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if v[0] < 1 || v[0] > 6 || v[1] > math.MaxInt32 || v[2] > math.MaxInt32 || v[3] > math.MaxInt32 || math.IsNaN(x) || math.IsNaN(y) || math.IsNaN(scale) || x < math.MinInt32 || x > math.MaxInt32 || y < math.MinInt32 || y > math.MaxInt32 || scale <= 0 || scale > math.MaxFloat32 {
|
||||
return nil, fmt.Errorf("gamedata: invalid default ID card layout")
|
||||
}
|
||||
out = append(out, IdCardDefault{Kind: v[0], ID: v[1], Layer: v[2], X: int32(x), Y: int32(y), Rotate: float32(v[3]), Scale: float32(scale), Color: string(color)})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, fmt.Errorf("gamedata: missing default ID card layout")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package gamedata
|
||||
|
||||
import "fmt"
|
||||
|
||||
type AvatarPartRule struct{ Category, Character, Maximum uint64 }
|
||||
type AvatarCharacterRule struct {
|
||||
Maximum uint64
|
||||
Collaboration bool
|
||||
Defaults, Banned []uint64
|
||||
Rewards []Reward
|
||||
}
|
||||
type AvatarProduct struct {
|
||||
Reward, Price, Premium Reward
|
||||
Initial, Purchasable bool
|
||||
Visibility, UnlockType, UnlockValue, UnlockSub uint64
|
||||
}
|
||||
type AvatarProfileDesign struct {
|
||||
Characters map[uint64]AvatarCharacterRule
|
||||
Parts map[uint64]AvatarPartRule
|
||||
MotionMaximum map[uint64]uint64
|
||||
Shop, MotionShop map[uint64]AvatarProduct
|
||||
Bundles *AvatarRewardDesign
|
||||
}
|
||||
|
||||
func LoadAvatarProfileDesign(root, version string) (*AvatarProfileDesign, error) {
|
||||
db, done, err := openStatDatabase(root, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer done()
|
||||
d := &AvatarProfileDesign{Characters: map[uint64]AvatarCharacterRule{}, Parts: map[uint64]AvatarPartRule{}, MotionMaximum: map[uint64]uint64{}, Shop: map[uint64]AvatarProduct{}, MotionShop: map[uint64]AvatarProduct{}}
|
||||
d.Bundles, err = loadAvatarRewardDesign(db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = readCashMetadata(db, "AvatarCharTable", func(raw []byte) error {
|
||||
id, err := optionalScalar(raw, 6)
|
||||
if err != nil || id == 0 {
|
||||
return fmt.Errorf("gamedata: invalid avatar character")
|
||||
}
|
||||
maximum, err := optionalScalar(raw, 11)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defaults, err := packedInts(raw, 5)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
banned, err := packedInts(raw, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
collaboration, err := optionalScalar(raw, 7)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bonuses, err := eventGameRewards(raw, 14, 13, 12)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var rewards []Reward
|
||||
for _, bonus := range bonuses {
|
||||
rewards = append(rewards, Reward(bonus))
|
||||
}
|
||||
d.Characters[id] = AvatarCharacterRule{Maximum: maximum, Collaboration: collaboration == 1, Defaults: defaults, Banned: banned, Rewards: rewards}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = readCashMetadata(db, "AvatarItemTable", func(raw []byte) error {
|
||||
id, err := optionalScalar(raw, 3)
|
||||
if err != nil || id == 0 {
|
||||
return fmt.Errorf("gamedata: invalid avatar part")
|
||||
}
|
||||
category, err := optionalScalar(raw, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
character, err := optionalScalar(raw, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
maximum, err := optionalScalar(raw, 9)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.Parts[id] = AvatarPartRule{category, character, maximum}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = readCashMetadata(db, "AvatarMotionTable", func(raw []byte) error {
|
||||
id, err := optionalScalar(raw, 5)
|
||||
if err != nil || id == 0 {
|
||||
return fmt.Errorf("gamedata: invalid avatar motion")
|
||||
}
|
||||
maximum, err := optionalScalar(raw, 8)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.MotionMaximum[id] = maximum
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, table := range []string{"AvatarShopTable", "AvatarMotionShopTable"} {
|
||||
err = readCashMetadata(db, table, func(raw []byte) error {
|
||||
values := make(map[int]uint64)
|
||||
for field := 1; field <= 18; field++ {
|
||||
n, err := optionalScalar(raw, field)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
values[field] = n
|
||||
}
|
||||
if table == "AvatarMotionShopTable" {
|
||||
if values[4] == 0 || values[3] != 50 || values[1] == 0 {
|
||||
return fmt.Errorf("gamedata: invalid motion product")
|
||||
}
|
||||
d.MotionShop[values[4]] = AvatarProduct{Reward: Reward{values[3], values[2], values[1]}, Price: Reward{values[7], values[6], values[5]}, Purchasable: true}
|
||||
return nil
|
||||
}
|
||||
if values[5] == 0 {
|
||||
return fmt.Errorf("gamedata: invalid avatar product")
|
||||
}
|
||||
d.Shop[values[5]] = AvatarProduct{Reward: Reward{values[4], values[3], values[2]}, Price: Reward{values[16], values[15], values[14]}, Premium: Reward{values[13], values[12], values[11]}, Initial: values[6] == 1, Purchasable: values[7] == 1, Visibility: values[17], UnlockType: values[9], UnlockValue: values[10], UnlockSub: values[8]}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type PvpDefaults struct {
|
||||
MinimumVP, StartVP, BoostMaximum, TicketCost, HistoryHours, HistoryLimit, CorrectionFactor uint64
|
||||
MatchExclude, CandidateCount uint64
|
||||
MatchRanges []uint64
|
||||
}
|
||||
|
||||
type PvpRank struct {
|
||||
Group, ID, VP, Ranking, WinPoint, LosePoint, StartVP, PromotionBox uint64
|
||||
ELO bool
|
||||
WinRewards, LoseRewards, SeasonRewards []BattleReward
|
||||
}
|
||||
|
||||
type ColosseumDefaults struct {
|
||||
MinimumVP, DefaultChange, MaximumChange, MinimumChange, VariableChange uint64
|
||||
HistoryHours, HistoryLimit, TicketBuyType, TicketBuyID, TicketBuyCost uint64
|
||||
MatchExclude, CandidateCount uint64
|
||||
MatchRanges []uint64
|
||||
}
|
||||
|
||||
type ColosseumRank struct {
|
||||
Group, ID uint64
|
||||
TopPercent float64
|
||||
Rewards []BattleReward
|
||||
}
|
||||
|
||||
type ColosseumBless struct{ ID, Type, Points uint64 }
|
||||
|
||||
type PvpDesign struct {
|
||||
DailyResetSeconds int64
|
||||
FreeMirrorTickets uint64
|
||||
Version string
|
||||
Mirror PvpDefaults
|
||||
Colosseum ColosseumDefaults
|
||||
MirrorRanks map[uint64][]PvpRank
|
||||
MirrorSeasons map[uint64]uint64
|
||||
ColosseumSeasons map[uint64]uint64
|
||||
ColosseumRankGroups map[uint64]uint64
|
||||
ColosseumRanks map[uint64][]ColosseumRank
|
||||
ColosseumRules map[uint64]map[uint64][]uint64
|
||||
Blesses map[uint64]ColosseumBless
|
||||
Presets *PresetDesign
|
||||
}
|
||||
|
||||
func pvpTableRows(db *sql.DB, table string, visit func([]byte) error) (err error) {
|
||||
rows, err := db.Query("SELECT ProtoBuf FROM " + table)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { err = errors.Join(err, rows.Close()) }()
|
||||
for rows.Next() {
|
||||
var raw []byte
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := visit(raw); err != nil {
|
||||
return fmt.Errorf("gamedata: %s: %w", table, err)
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func pvpScalars(raw []byte, fields map[int]*uint64) error {
|
||||
for field, target := range fields {
|
||||
value, err := optionalScalar(raw, field)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*target = value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pvpRewards(raw []byte, typ, id, count int) ([]BattleReward, error) {
|
||||
rows, err := parallelRewards(raw, typ, id, count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]BattleReward, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = BattleReward(r)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func LoadPvpDesign(root, version string) (*PvpDesign, error) {
|
||||
db, release, err := OpenDatabase(root, version, "common")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
presets, err := loadPresetDesign(db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var defaults []byte
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&defaults); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = pvpScalars(defaults, map[int]*uint64{20: &presets.BaseCount, 21: &presets.Maximum}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = presets.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reset, err := LoadHuntingAPDesign(root, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var freeTickets uint64
|
||||
if err = pvpScalars(defaults, map[int]*uint64{77: &freeTickets}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d := &PvpDesign{DailyResetSeconds: reset.ResetSeconds, FreeMirrorTickets: freeTickets, Version: version, Presets: presets, MirrorRanks: map[uint64][]PvpRank{}, MirrorSeasons: map[uint64]uint64{}, ColosseumSeasons: map[uint64]uint64{}, ColosseumRankGroups: map[uint64]uint64{}, ColosseumRanks: map[uint64][]ColosseumRank{}, ColosseumRules: map[uint64]map[uint64][]uint64{}, Blesses: map[uint64]ColosseumBless{}}
|
||||
loaders := []struct {
|
||||
table string
|
||||
visit func([]byte) error
|
||||
}{
|
||||
{"PvpDefaultTable", func(raw []byte) error {
|
||||
m := &d.Mirror
|
||||
if err := pvpScalars(raw, map[int]*uint64{2: &m.MinimumVP, 3: &m.BoostMaximum, 5: &m.HistoryHours, 6: &m.HistoryLimit, 16: &m.CorrectionFactor, 19: &m.MatchExclude, 23: &m.TicketCost, 25: &m.CandidateCount, 26: &m.StartVP}); err != nil {
|
||||
return err
|
||||
}
|
||||
m.MatchRanges, err = packedInts(raw, 20)
|
||||
return err
|
||||
}},
|
||||
{"PvpSeasonTable", func(raw []byte) error {
|
||||
var id, season uint64
|
||||
if err := pvpScalars(raw, map[int]*uint64{1: &id, 2: &season}); err != nil {
|
||||
return err
|
||||
}
|
||||
d.MirrorSeasons[season] = id
|
||||
return nil
|
||||
}},
|
||||
{"PvpRankTable", func(raw []byte) error {
|
||||
var r PvpRank
|
||||
var elo uint64
|
||||
if err := pvpScalars(raw, map[int]*uint64{7: &r.Group, 9: &r.ID, 10: &elo, 11: &r.LosePoint, 12: &r.PromotionBox, 13: &r.Ranking, 20: &r.StartVP, 21: &r.VP, 22: &r.WinPoint}); err != nil {
|
||||
return err
|
||||
}
|
||||
r.ELO = elo != 0
|
||||
if r.WinRewards, err = pvpRewards(raw, 6, 5, 4); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.LoseRewards, err = pvpRewards(raw, 3, 2, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.SeasonRewards, err = pvpRewards(raw, 19, 18, 17); err != nil {
|
||||
return err
|
||||
}
|
||||
d.MirrorRanks[r.Group] = append(d.MirrorRanks[r.Group], r)
|
||||
return nil
|
||||
}},
|
||||
{"ColosseumDefaultTable", func(raw []byte) error {
|
||||
m := &d.Colosseum
|
||||
if err := pvpScalars(raw, map[int]*uint64{3: &m.MinimumVP, 4: &m.TicketBuyCost, 5: &m.TicketBuyID, 6: &m.TicketBuyType, 8: &m.HistoryHours, 9: &m.HistoryLimit, 16: &m.DefaultChange, 17: &m.MaximumChange, 18: &m.MinimumChange, 19: &m.VariableChange, 22: &m.MatchExclude, 30: &m.CandidateCount}); err != nil {
|
||||
return err
|
||||
}
|
||||
m.MatchRanges, err = packedInts(raw, 23)
|
||||
return err
|
||||
}},
|
||||
{"ColosseumSeasonTable", func(raw []byte) error {
|
||||
var id, group uint64
|
||||
if err := pvpScalars(raw, map[int]*uint64{1: &id, 2: &group}); err != nil {
|
||||
return err
|
||||
}
|
||||
d.ColosseumSeasons[id] = group
|
||||
return nil
|
||||
}},
|
||||
{"ColosseumSeasonLinkTable", func(raw []byte) error {
|
||||
var id, group uint64
|
||||
if err := pvpScalars(raw, map[int]*uint64{1: &id, 2: &group}); err != nil {
|
||||
return err
|
||||
}
|
||||
d.ColosseumRankGroups[id] = group
|
||||
return nil
|
||||
}},
|
||||
{"ColosseumRuleGroupTable", func(raw []byte) error {
|
||||
var group, kind uint64
|
||||
if err := pvpScalars(raw, map[int]*uint64{1: &group, 8: &kind}); err != nil {
|
||||
return err
|
||||
}
|
||||
values, e := packedInts(raw, 9)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if d.ColosseumRules[group] == nil {
|
||||
d.ColosseumRules[group] = map[uint64][]uint64{}
|
||||
}
|
||||
d.ColosseumRules[group][kind] = values
|
||||
return nil
|
||||
}},
|
||||
{"ColosseumRankTable", func(raw []byte) error {
|
||||
var r ColosseumRank
|
||||
if err := pvpScalars(raw, map[int]*uint64{1: &r.Group, 3: &r.ID}); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.TopPercent, err = optionalDouble(raw, 10); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Rewards, err = pvpRewards(raw, 9, 8, 7); err != nil {
|
||||
return err
|
||||
}
|
||||
d.ColosseumRanks[r.Group] = append(d.ColosseumRanks[r.Group], r)
|
||||
return nil
|
||||
}},
|
||||
{"ColosseumBlessTable", func(raw []byte) error {
|
||||
var b ColosseumBless
|
||||
if err := pvpScalars(raw, map[int]*uint64{1: &b.Type, 2: &b.ID, 4: &b.Points}); err != nil {
|
||||
return err
|
||||
}
|
||||
d.Blesses[b.ID] = b
|
||||
return nil
|
||||
}},
|
||||
}
|
||||
for _, loader := range loaders {
|
||||
if err := pvpTableRows(db, loader.table, loader.visit); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if d.Mirror.StartVP == 0 || d.Mirror.TicketCost == 0 || len(d.MirrorRanks) == 0 || len(d.ColosseumRules) == 0 {
|
||||
return nil, fmt.Errorf("gamedata: incomplete PVP design")
|
||||
}
|
||||
for group := range d.MirrorRanks {
|
||||
sort.Slice(d.MirrorRanks[group], func(i, j int) bool { return d.MirrorRanks[group][i].ID < d.MirrorRanks[group][j].ID })
|
||||
}
|
||||
for group := range d.ColosseumRanks {
|
||||
sort.Slice(d.ColosseumRanks[group], func(i, j int) bool {
|
||||
return d.ColosseumRanks[group][i].TopPercent < d.ColosseumRanks[group][j].TopPercent
|
||||
})
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *PvpDesign) MirrorGroup(season uint64) uint64 {
|
||||
var selected uint64
|
||||
group := uint64(1)
|
||||
for start, id := range d.MirrorSeasons {
|
||||
if start <= season && start >= selected {
|
||||
selected, group = start, id
|
||||
}
|
||||
}
|
||||
return group
|
||||
}
|
||||
|
||||
func (d *PvpDesign) MirrorRank(season, vp, ranking uint64) (PvpRank, error) {
|
||||
rows := d.MirrorRanks[d.MirrorGroup(season)]
|
||||
if len(rows) == 0 {
|
||||
return PvpRank{}, fmt.Errorf("gamedata: no mirror rank group for season %d", season)
|
||||
}
|
||||
var top []PvpRank
|
||||
for _, r := range rows {
|
||||
if r.Ranking > 0 {
|
||||
top = append(top, r)
|
||||
}
|
||||
}
|
||||
if len(top) > 0 && ranking > 0 && ranking <= top[len(top)-1].Ranking && vp >= top[len(top)-1].VP {
|
||||
for _, r := range top {
|
||||
if ranking <= r.Ranking {
|
||||
return r, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, r := range rows {
|
||||
if r.Ranking == 0 && vp >= r.VP {
|
||||
return r, nil
|
||||
}
|
||||
}
|
||||
return rows[len(rows)-1], nil
|
||||
}
|
||||
|
||||
func (d *PvpDesign) ColosseumRule(season, kind uint64) ([]uint64, error) {
|
||||
group, ok := d.ColosseumSeasons[season]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("gamedata: unknown colosseum season %d", season)
|
||||
}
|
||||
values, ok := d.ColosseumRules[group][kind]
|
||||
if !ok {
|
||||
if kind == 30 || kind == 31 {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("gamedata: missing colosseum rule %d", kind)
|
||||
}
|
||||
return append([]uint64(nil), values...), nil
|
||||
}
|
||||
|
||||
func (d *PvpDesign) ColosseumRank(season uint64, percent float64) (ColosseumRank, error) {
|
||||
rows := d.ColosseumRanks[d.ColosseumRankGroups[season]]
|
||||
for _, r := range rows {
|
||||
if percent <= r.TopPercent {
|
||||
return r, nil
|
||||
}
|
||||
}
|
||||
return ColosseumRank{}, fmt.Errorf("gamedata: no colosseum rank for season %d top %g", season, percent)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
@@ -11,13 +12,16 @@ import (
|
||||
// Reward slot zero is normal story difficulty; later slots are separate
|
||||
// difficulty tiers and must never be added to the same clear.
|
||||
type QuestDesign struct {
|
||||
ID int
|
||||
Type int
|
||||
PriorQuestID int
|
||||
NextQuestID int
|
||||
GiveQuestItemIDs []uint64
|
||||
CollectionRewards []Reward
|
||||
Rewards [5][]Reward
|
||||
ID int
|
||||
Type int
|
||||
PriorQuestID int
|
||||
NextQuestID int
|
||||
AcceptCinemaName string
|
||||
CompleteCinemaName string
|
||||
TimelineStartMapID int
|
||||
GiveQuestItemIDs []uint64
|
||||
CollectionRewards []Reward
|
||||
Rewards [5][]Reward
|
||||
}
|
||||
|
||||
func LoadQuestDesign(root, version string, packID int) (map[int]QuestDesign, error) {
|
||||
@@ -68,6 +72,13 @@ func loadQuestDesignDB(db *sql.DB, packID int) (map[int]QuestDesign, error) {
|
||||
continue
|
||||
}
|
||||
entry := QuestDesign{ID: id}
|
||||
for field, dst := range map[int]*string{1: &entry.AcceptCinemaName, 7: &entry.CompleteCinemaName} {
|
||||
value, _, err := wire.Bytes(proto, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*dst = string(value)
|
||||
}
|
||||
collectionIDs, err := packedInts(proto, 6)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gamedata: quest%d collections: %w", id, err)
|
||||
@@ -90,7 +101,7 @@ func loadQuestDesignDB(db *sql.DB, packID int) (map[int]QuestDesign, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gamedata: quest%d give items: %w", id, err)
|
||||
}
|
||||
for field, dst := range map[int]*int{63: &entry.Type, 37: &entry.PriorQuestID, 35: &entry.NextQuestID} {
|
||||
for field, dst := range map[int]*int{63: &entry.Type, 37: &entry.PriorQuestID, 35: &entry.NextQuestID, 62: &entry.TimelineStartMapID} {
|
||||
values, err := packedInts(proto, field)
|
||||
if err != nil || len(values) > 1 || (len(values) == 1 && values[0] > uint64(^uint32(0)>>1)) {
|
||||
return nil, fmt.Errorf("gamedata: invalid quest %d field%d", id, field)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type StoryInteraction struct {
|
||||
Timeline string
|
||||
SimpleTalkGroupID uint64
|
||||
QuestIDs []uint64
|
||||
}
|
||||
|
||||
func (s *Source) StoryInteraction(pack, object int) (StoryInteraction, error) {
|
||||
db, release, err := OpenDatabase(s.root, s.version, fmt.Sprintf("pack%d", pack))
|
||||
if err != nil {
|
||||
return StoryInteraction{}, err
|
||||
}
|
||||
defer release()
|
||||
var raw []byte
|
||||
if err = db.QueryRow("SELECT ProtoBuf FROM FieldQuestObjectTable WHERE id=?", object).Scan(&raw); err != nil {
|
||||
return StoryInteraction{}, err
|
||||
}
|
||||
var out StoryInteraction
|
||||
value, _, err := wire.Bytes(raw, 14)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Timeline = string(value)
|
||||
out.SimpleTalkGroupID, err = optionalScalar(raw, 13)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.QuestIDs, err = packedInts(raw, 12)
|
||||
return out, err
|
||||
}
|
||||
Loaded 100 of 295 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user