diff --git a/docs/FEATURE-NATIVE-SYSTEMS.md b/docs/FEATURE-NATIVE-SYSTEMS.md new file mode 100644 index 00000000..0459e718 --- /dev/null +++ b/docs/FEATURE-NATIVE-SYSTEMS.md @@ -0,0 +1,15 @@ +# AVA2 原生战令、百科查询与活动日历 + +使用原生 `uiBattlePassEx`、`uiWiki` / `WikiUI`、Worldard `uiDropItem` 与 `uiEventCalendarNew`,客户端原件哈希及平台适配见对应客户端 `docs/AVA2-NATIVE-SYSTEMS.md`。 + +- `/battle_pass info|activate CELL VNUM|reward|close` 使用当前战令赛季和原有领取主键,映射九种已接入的任务。原生模式任务完成自动发奖,满包待重试;最终奖励需点击。旧 `/mt_bp` 保留。SQL 使用配置的 PLAYER_SQL 数据库,不硬编码 player;不要把sbtest进度写入生产。 +- CG215(6字节)/GC220(114字节):子类型0打开、1反查怪物、6查询怪物掉落、7查询宝箱、8反查宝箱、9/10反查强化家族。GC子类型2打开、3行、4清空、5完成、6拒绝/超限错误。只读当前加载表,单次上限4096行。 +- `/event_manager info`:AVA2新日历原39号与经典SHOP_SIGN冲突,移到214号,5字节动态头和81字节事件记录。仅对客户端标记mt20261019以上下发新增二进制包。保持经典封包布局。 +- 日历和真实掉落读取同一个 `port_events.tsv`;UTC开始含、结束不含,并检查频道与帝国。月光宝箱映射AVA2事件8,圣诞袜映射扩展20。目前只接入这两种真实活动,其他活动不会因新窗口出现而自动生效。 +- 空文件不是有效排期;没有活动时使用 `MTCALENDAR 1` 加换行。没有文件或文件错误时明确显示不可用,不伪造活动。 + +测试:30组服务端功能脚本;原战令测试新增自动领奖/重复领取/满包/旧数据;新增 `tests/features/test_native_queries.py` 直接编译实际处理器,验证宽度、正反查、限流、超限、旧客户端与活动作用域。FreeBSD隔离构建及macOS/sbtest已联机验证。测试账号原有物品、任务和战令数据已备份恢复。 + +部署工具 `tools/native-systems/deploy.py`:`check`只读;`deploy --candidate PATH --sha256 HASH` 验证候选后备份、优雅停止正式game/auth、更换共享game、恢复13个核心和auth,db保持运行;`rollback --backup DIR` 恢复备份程序。回滚保留已经取得的进度/领取主键,避免再次支付奖励;不回退玩家经济数据。 + +203正式服已于2026-10-19 08:31:54(CEST,UTC+02)更新。game SHA256:a8d606ea88731cb5b7bffabbe8ddc78ef806205f6c8a352d78ba6d46a1c6b2f3。备份:`/root/backup-native-systems/20261019-083154`,auth、13个核心和原db运行,sbtest已恢复。生产排期初始化为空,不发布测试活动。首次优雅停止因换页超过55秒,旧程序未替换;旧核心正常退出后重新部署成功,等待窗口已延长至300秒。保留原motion accumulation警告,没有新增PORT_BP/查询/Lua错误。客户端必须同时更新可执行文件及ava2items/wiki资源包。 diff --git a/src/server/game/src/ava2_native_packets.h b/src/server/game/src/ava2_native_packets.h new file mode 100644 index 00000000..bd429306 --- /dev/null +++ b/src/server/game/src/ava2_native_packets.h @@ -0,0 +1,13 @@ +#ifndef METIN2_AVA2_NATIVE_PACKETS_H +#define METIN2_AVA2_NATIVE_PACKETS_H +#include +#pragma pack(push,1) +struct TPacketCGAva2Drop {uint8_t header,subheader;int32_t vnum;}; +struct TPacketGCAva2Drop {uint8_t header,subheader;char name[100];uint32_t vnum,prob;int32_t count;}; +struct TPacketGCAva2Events {uint8_t header;uint32_t size;}; +struct TAva2Event {uint16_t id;uint8_t kind;uint32_t start,end;uint8_t empire,channel;uint32_t value[4];uint8_t active,onlyStart;char startText[25],endText[25];}; +#pragma pack(pop) +static_assert(sizeof(TPacketCGAva2Drop)==6 && sizeof(TPacketGCAva2Drop)==114 && sizeof(TPacketGCAva2Events)==5 && sizeof(TAva2Event)==81,"AVA2 query wire sizes"); +class CHARACTER; +void PortNativeDrop(CHARACTER*,const TPacketCGAva2Drop&); +#endif diff --git a/src/server/game/src/ava2_native_queries.h b/src/server/game/src/ava2_native_queries.h new file mode 100644 index 00000000..23a2d90c --- /dev/null +++ b/src/server/game/src/ava2_native_queries.h @@ -0,0 +1,92 @@ +// Included only by cmd_general.cpp; reads the same loaded tables/schedule as actual drops. +#include "ava2_native_packets.h" +#include +inline bool PortNativeClient(LPCHARACTER ch) { + const char* mark=ch && ch->GetDesc()?strstr(ch->GetDesc()->GetClientVersion(),"mt"):NULL; + return mark && atoi(mark+2)>=20261019; +} + +void PortNativeDrop(LPCHARACTER ch,const TPacketCGAva2Drop& request) { + if (!ch || !ch->GetDesc() || !PortNativeClient(ch))return; + if (request.subheader!=0 && request.subheader!=1 && request.subheader!=6 && request.subheader!=7 && request.subheader!=8 && request.subheader!=9 && request.subheader!=10)return; + TPacketGCAva2Drop p={};p.header=220; + if (request.subheader==0) {p.subheader=2;ch->GetDesc()->Packet(&p,sizeof(p));return;} + if (request.vnum<=0)return; + const int now=get_global_time(); + // Always finish a refused request so an untagged AVA2 response cannot poison the next query. + p.subheader=4;ch->GetDesc()->Packet(&p,sizeof(p)); + if (ch->GetProtectTime("native_drop")>now) {p.subheader=6;ch->GetDesc()->Packet(&p,sizeof(p));return;} + ch->SetProtectTime("native_drop",now+1); + auto& manager=ITEM_MANAGER::instance();unsigned sent=0;bool overflow=false; + auto send=[&](unsigned id,unsigned count,unsigned probability,const char* name) { + if(!id || !count)return; + if(sent>=4096){overflow=true;return;} + memset(&p,0,sizeof(p));p.header=220;p.subheader=3;p.vnum=id;p.count=count;p.prob=probability; + strlcpy(p.name,name?name:"",sizeof(p.name));ch->GetDesc()->Packet(&p,sizeof(p));++sent; + }; + std::set family;unsigned next=request.vnum; + for(unsigned i=0;i<256 && next && !family.count(next);++i) { + const auto* t=manager.GetTable(next);if(!t)break; + family.insert(next);next=(request.subheader==9 || request.subheader==10)?t->dwRefinedVnum:0; + } + if ((request.subheader==1 || request.subheader==9) && !family.empty()) { + for(auto it=CMobManager::instance().begin();it!=CMobManager::instance().end();++it) + for(const auto& row:manager.PortWikiDrops(it->first)) + if(family.count(row.item))send(it->first,row.count,0,it->second->m_table.szLocaleName); + } else if ((request.subheader==8 || request.subheader==10) && !family.empty()) { + for(const auto& table:manager.GetTable()) + if(table.bType==ITEM_GIFTBOX || table.bType==ITEM_TREASURE_BOX) + for(const auto& row:manager.PortWikiChest(table.dwVnum)) + if(family.count(row.item))send(table.dwVnum,row.count,0,table.szLocaleName); + } else if (request.subheader==6 || request.subheader==7) { + const auto rows=request.subheader==6?manager.PortWikiDrops(request.vnum):manager.PortWikiChest(request.vnum); + for(const auto& row:rows) { + const auto* proto=manager.GetTable(row.item); + // Conditional mob rates cannot be represented by the legacy percentage field. + unsigned probability=row.rule==WIKI_SINGLE && row.total?unsigned(100ULL*row.weight/row.total):row.rule==WIKI_INDEPENDENT?row.weight:0; + if(proto)send(row.item,row.count,probability,proto->szLocaleName); + } + } + memset(&p,0,sizeof(p));p.header=220;p.subheader=overflow?6:5;ch->GetDesc()->Packet(&p,sizeof(p)); +} + +ACMD(do_event_manager) { + if(!ch || !ch->GetDesc() || !PortNativeClient(ch))return; + std::istringstream input(argument);std::string action,extra; + if(!(input>>action) || action!="info" || (input>>extra))return; + const int now=get_global_time(); + if(ch->GetProtectTime("native_calendar")>now)return; + ch->SetProtectTime("native_calendar",now+2); + auto& schedule=PortCurrentEvents(); + if(!schedule.valid){ch->ChatPacket(CHAT_TYPE_COMMAND,"EventCalendarError unavailable");return;} + const time_t stamp=now;struct tm current;gmtime_r(&stamp,¤t); + std::map> days; + unsigned ordinal=0; + for(const auto& e:schedule.events) { + ++ordinal; + const time_t start=e.start,end=e.end;struct tm st,et;gmtime_r(&start,&st);gmtime_r(&end,&et); + // Include an ongoing interval which began in the previous month, on day one. + const bool starts=st.tm_year==current.tm_year && st.tm_mon==current.tm_mon; + const bool overlaps=start<=stamp && end>stamp; + if(!starts && !overlaps)continue; + TAva2Event event={};event.id=ordinal;event.kind=e.kind==1?8:20; + event.start=e.start;event.end=e.end;event.empire=e.empire;event.channel=e.channel; + event.active=e.Active(now,g_bChannel,ch->GetEmpire()); + strftime(event.startText,sizeof(event.startText),"%Y-%m-%d %H:%M:%S",&st); + strftime(event.endText,sizeof(event.endText),"%Y-%m-%d %H:%M:%S",&et); + days[starts?unsigned(st.tm_mday):1].push_back(event); + } + // The AVA2 event-manager payload is retained; GC214 avoids classic SHOP_SIGN=39. + TPacketGCAva2Events header={214,uint32_t(sizeof(TPacketGCAva2Events)+6)}; + for(const auto& day:days)header.size+=2+day.second.size()*sizeof(TAva2Event); + if(header.size>32768)return; + TEMP_BUFFER out;out.write(&header,sizeof(header)); + const uint8_t sub=0,dayCount=days.size();out.write(&sub,1);out.write(&dayCount,1);out.write(&now,4); + for(const auto& day:days) { + // Per-day count is BYTE in AVA2. Reject overflow rather than wrapping its length. + if(day.second.size()>255){ch->ChatPacket(CHAT_TYPE_COMMAND,"EventCalendarError overflow");return;} + const uint8_t index=day.first,count=day.second.size();out.write(&index,1);out.write(&count,1); + out.write(day.second.data(),day.second.size()*sizeof(TAva2Event)); + } + ch->GetDesc()->Packet(out.read_peek(),out.size()); +} diff --git a/src/server/game/src/cmd.cpp b/src/server/game/src/cmd.cpp index ecf2bd77..647a8f0a 100755 --- a/src/server/game/src/cmd.cpp +++ b/src/server/game/src/cmd.cpp @@ -22,6 +22,8 @@ ACMD(do_chest_drop); ACMD(do_chestdrop); ACMD(do_port_vip); ACMD(do_port_bp); +ACMD(do_battle_pass); +ACMD(do_event_manager); ACMD(do_user_horse_ride); ACMD(do_user_horse_back); ACMD(do_user_horse_feed); @@ -623,7 +625,9 @@ struct command_info cmd_info[] = { "chestdrop", do_chestdrop, 0, POS_DEAD, GM_PLAYER }, { "mt_chest", do_port_chest, 0, POS_DEAD, GM_PLAYER }, { "mt_vip", do_port_vip, 0, POS_DEAD, GM_PLAYER }, - { "mt_bp", do_port_bp, 0, POS_DEAD, GM_PLAYER }, + { "event_manager", do_event_manager, 0, POS_DEAD, GM_PLAYER }, + { "battle_pass", do_battle_pass, 0, POS_DEAD, GM_PLAYER }, + { "mt_bp", do_port_bp, 0, POS_DEAD, GM_PLAYER }, { "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* ¹ݵå½Ã ÀÌ °ÍÀÌ ¸¶Áö¸·À̾î¾ß ÇѴÙ. */ }; diff --git a/src/server/game/src/cmd_general.cpp b/src/server/game/src/cmd_general.cpp index 8be15059..5d3a718b 100755 --- a/src/server/game/src/cmd_general.cpp +++ b/src/server/game/src/cmd_general.cpp @@ -52,6 +52,7 @@ #include "ava2_chest_commands.h" #include "port_premium.h" #include "port_battlepass_runtime.h" +#include "ava2_native_queries.h" ACMD(do_port_vip) { @@ -60,6 +61,8 @@ ACMD(do_port_vip) PortVipCommand(ch, argument); } +ACMD(do_battle_pass) { PortBpNativeCommand(ch,argument); } + // PORT: battle pass (port_battlepass_runtime.h) ACMD(do_port_bp) { diff --git a/src/server/game/src/input_main.cpp b/src/server/game/src/input_main.cpp index 94b1658a..e5d95d47 100755 --- a/src/server/game/src/input_main.cpp +++ b/src/server/game/src/input_main.cpp @@ -42,6 +42,7 @@ // #include "XTrapManager.h" #include "DragonSoul.h" #include "port_switchbot.h" +#include "ava2_native_packets.h" extern void SendShout(const char * szText, BYTE bEmpire); extern int g_nPortalLimitTime; @@ -3405,6 +3406,8 @@ int CInputMain::Analyze(LPDESC d, BYTE bHeader, const char * c_pData) Sash(ch, c_pData); break; + case HEADER_CG_AVA2_DROP: + PortNativeDrop(ch,*reinterpret_cast(c_pData));break; case HEADER_CG_SWITCHBOT: if ((iExtraLen = Switchbot(ch, c_pData, m_iBufferLeft)) < 0) return -1; diff --git a/src/server/game/src/packet.h b/src/server/game/src/packet.h index 6a11c821..97a17e70 100755 --- a/src/server/game/src/packet.h +++ b/src/server/game/src/packet.h @@ -110,6 +110,7 @@ enum HEADER_CG_DRAGON_SOUL_REFINE = 205, HEADER_CG_STATE_CHECKER = 206, HEADER_CG_SASH = 211, // AVA2 sash + HEADER_CG_AVA2_DROP = 215, HEADER_CG_ITEMS_PICKUP = 235, // PORT: AVA2 HEADER_CG_SWITCHBOT = 171, // AVA2 switchbot (port_switchbot.cpp) diff --git a/src/server/game/src/packet_info.cpp b/src/server/game/src/packet_info.cpp index 2edc52fb..b49cfae7 100755 --- a/src/server/game/src/packet_info.cpp +++ b/src/server/game/src/packet_info.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "ava2_native_packets.h" #include "../../common/stl.h" #include "constants.h" #include "packet_info.h" @@ -230,6 +231,7 @@ CPacketInfoCG::CPacketInfoCG() Set(HEADER_CG_STATE_CHECKER, sizeof(BYTE), "ServerStateCheck", false); Set(HEADER_CG_SASH, sizeof(TPacketSash), "Sash", true); Set(HEADER_CG_ITEMS_PICKUP,sizeof(TPacketCGItemsPickUp),"ItemsPickup",true); + Set(HEADER_CG_AVA2_DROP,sizeof(TPacketCGAva2Drop),"Ava2Drop",true); Set(HEADER_CG_SWITCHBOT, sizeof(TPacketCGSwitchbot), "Switchbot", true); } diff --git a/src/server/game/src/port_battlepass.h b/src/server/game/src/port_battlepass.h index 0807d3b9..f4508a52 100644 --- a/src/server/game/src/port_battlepass.h +++ b/src/server/game/src/port_battlepass.h @@ -157,7 +157,7 @@ private: // progress and the stored value is capped at the target by the database itself. struct PortBpState { unsigned season=0,generation=0; - bool loaded=false,watching=false,wantInfo=false; + bool loaded=false,watching=false,wantInfo=false,nativeUI=false; unsigned long long base[kPortBpSlots+1]={},delta[kPortBpSlots+1]={},inflight[kPortBpSlots+1]={}; std::set claimed; // slots; 0 = final unsigned playtimeMark=0; // get_dword_time() up to which play time has been counted diff --git a/src/server/game/src/port_battlepass_runtime.h b/src/server/game/src/port_battlepass_runtime.h index 866641b6..10432c57 100644 --- a/src/server/game/src/port_battlepass_runtime.h +++ b/src/server/game/src/port_battlepass_runtime.h @@ -37,8 +37,29 @@ inline void PortBpSendRewards(std::string& line,const std::vector& for(const auto& r:rewards)line+=" "+std::to_string(r.vnum)+" "+std::to_string(r.count); } +// AVA2 uiBattlePassEx is ENABLE_BATTLE_PASS (/battle_pass), distinct from the older GC230 UI. +inline unsigned PortBpNativeType(unsigned type) { + static const unsigned map[]={0,10,1,20,13,2,14,9,18,17}; + return type& rewards) { + std::string text; + for (const auto& r:rewards) {if(!text.empty())text+="#";text+=std::to_string(r.vnum)+"|"+std::to_string(r.count);} + return text.empty()?"Empty":text; +} +inline void PortBpAutoGrant(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state); +inline void PortBpSendNative(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state) { + ch->ChatPacket(CHAT_TYPE_COMMAND,"BattlePassClear"); + const time_t stamp=get_global_time();struct tm date;localtime_r(&stamp,&date); + ch->ChatPacket(CHAT_TYPE_COMMAND,"BattlePassPeriod %u",unsigned((date.tm_year+1900)*100+date.tm_mon+1)); + for (const auto& m:season.missions) + ch->ChatPacket(CHAT_TYPE_COMMAND,"BattlePassAppendMission %u %s %llu %llu %u %u",PortBpNativeType(m.type),PortBpNativeRewards(m.rewards).c_str(),state.Value(m),m.target,m.sub,m.slot); + ch->ChatPacket(CHAT_TYPE_COMMAND,"BattlePassSetStatus %u %lld %s",PortBpAccess(ch),std::max(0LL,(long long)season.end-get_global_time()),PortBpNativeRewards(season.final).c_str()); +} + inline void PortBpSendInfo(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state) { state.watching=true;state.wantInfo=false; + if (state.nativeUI) {PortBpSendNative(ch,season,state);return;} ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 season %u %u %u %lld %u",season.id,season.start,season.end,(long long)get_global_time(),unsigned(season.missions.size())); const time_t serverNow=time_t(get_global_time());struct tm date;localtime_r(&serverNow,&date); ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 access %u %u",PortBpAccess(ch),unsigned(date.tm_mon+1)); @@ -67,7 +88,7 @@ inline void PortBpFlush(DWORD pid,PortBpState& state,const PortBpSeason* season) if(!state.loaded)state.inflight[m.slot]+=d; } if(values.empty())return; - DBManager::instance().Query("INSERT INTO player.mt_battlepass_progress (pid,season,slot,value,target) VALUES %s " + DBManager::instance().Query("INSERT INTO mt_battlepass_progress (pid,season,slot,value,target) VALUES %s " "ON DUPLICATE KEY UPDATE value=LEAST(value+VALUES(value),VALUES(target)),target=VALUES(target)",values.c_str()); } @@ -80,7 +101,7 @@ inline void PortBpLoad(DWORD pid,PortBpState& state) { auto it=PortBpStates().find(pid); if(it==PortBpStates().end() || it->second.generation!=generation || it->second.season!=season)return; PortBpState& state=it->second; - if(!msg->Get()){sys_err("PORT_BP: load failed pid %u season %u",pid,season);return;} + if(!msg || msg->uiSQLErrno || !msg->Get()){sys_err("PORT_BP: load failed pid %u season %u",pid,season);return;} unsigned long long stored[kPortBpSlots+1]={}; for(unsigned i=0;iGet()->uiNumRows;++i) { MYSQL_ROW row=mysql_fetch_row(msg->Get()->pSQLResult); @@ -94,12 +115,13 @@ inline void PortBpLoad(DWORD pid,PortBpState& state) { LPCHARACTER ch=CHARACTER_MANAGER::instance().FindByPID(pid); const PortBpSeason* now=PortBpConfigFile().Active(get_global_time()); if(!ch || !now || now->id!=season)return; + PortBpAutoGrant(ch,*now,state); // PortBpNotify held back the done notices of events counted before the load; send those now. for(const auto& m:now->missions) if(stored[m.slot]ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 done %u",m.slot); if(state.wantInfo)PortBpSendInfo(ch,*now,state); - },"SELECT 'p',slot,value FROM player.mt_battlepass_progress WHERE pid=%u AND season=%u " - "UNION ALL SELECT 'c',slot,0 FROM player.mt_battlepass_claim WHERE pid=%u AND season=%u",pid,season,pid,season); + },"SELECT 'p',slot,value FROM mt_battlepass_progress WHERE pid=%u AND season=%u " + "UNION ALL SELECT 'c',slot,0 FROM mt_battlepass_claim WHERE pid=%u AND season=%u",pid,season,pid,season); } inline const PortBpSeason* PortBpFindSeason(unsigned id) { @@ -135,8 +157,11 @@ inline PortBpState* PortBpSync(LPCHARACTER ch,const PortBpSeason*& season) { inline void PortBpNotify(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state,const std::vector& changed,const std::vector& finished) { if(state.watching) for(unsigned slot:changed)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 progress %u %llu",slot,state.Value(*season.Slot(slot))); + if (state.nativeUI && state.watching) + for(unsigned slot:changed)ch->ChatPacket(CHAT_TYPE_COMMAND,"BattlePassSetMission %u %llu",PortBpNativeType(season.Slot(slot)->type),state.Value(*season.Slot(slot))); if(!state.loaded)return; // values are not known yet; the window shows them once it is loaded for(unsigned slot:finished)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 done %u",slot); + if (!finished.empty())PortBpAutoGrant(ch,season,state); } inline void PortBpAccruePlaytime(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state) { @@ -201,6 +226,7 @@ inline const char* PortBpStacks(const std::vector& rewards,std::ve // /mt_bp 1 claim SLOT. The claim row is written first and synchronously; only the request that inserted it hands // out the items, into cells checked free beforehand, so retries, double clicks and other cores cannot pay twice. inline void PortBpClaim(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state,unsigned slot) { + if(ch->IsDead() || ch->IsWarping() || !ch->CanHandleItem() || ch->GetExchange() || ch->GetMyShop() || ch->GetShopOwner() || ch->IsOpenSafebox() || ch->IsCubeOpen()){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error busy");return;} if(PortBpAccess(ch)!=1){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error ticket");return;} if(const char* error=PortBpClaimError(season,state,slot)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error %s",error);return;} const std::vector& rewards=slot?season.Slot(slot)->rewards:season.final; @@ -216,8 +242,8 @@ inline void PortBpClaim(LPCHARACTER ch,const PortBpSeason& season,PortBpState& s if(!PortBpFit(free,INVENTORY_PAGE_SIZE,5,sizes,cells)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error space");return;} const DWORD pid=ch->GetPlayerID(); std::unique_ptr msg(DBManager::instance().DirectQuery( - "INSERT IGNORE INTO player.mt_battlepass_claim (pid,season,slot,claimed_at) VALUES (%u,%u,%u,%lld)",pid,season.id,slot,(long long)get_global_time())); - if(!msg || !msg->Get()){sys_err("PORT_BP: claim insert failed pid %u season %u slot %u",pid,season.id,slot);ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error db");return;} + "INSERT IGNORE INTO mt_battlepass_claim (pid,season,slot,claimed_at) VALUES (%u,%u,%u,%lld)",pid,season.id,slot,(long long)get_global_time())); + if(!msg || msg->uiSQLErrno || !msg->Get()){sys_err("PORT_BP: claim insert failed pid %u season %u slot %u",pid,season.id,slot);ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error db");return;} state.claimed.insert(slot); if(msg->Get()->uiAffectedRows!=1){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error claimed");return;} const std::string hint=std::to_string(season.id)+" "+std::to_string(slot); @@ -234,6 +260,18 @@ inline void PortBpClaim(LPCHARACTER ch,const PortBpSeason& season,PortBpState& s ch->Save(); } +// AVA2 grants mission rewards on completion. Existing unique claim rows are retained as the +// migration/idempotency boundary; full bags keep the mission claim pending for the next open. +inline void PortBpAutoGrant(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state) { + static std::set granting; + const DWORD pid=ch->GetPlayerID(); + if (!state.nativeUI || !state.loaded || state.season!=season.id || PortBpAccess(ch)!=1 || granting.count(pid))return; + granting.insert(pid); + for (const auto& m:season.missions) + if (state.Done(m) && !state.claimed.count(m.slot))PortBpClaim(ch,season,state,m.slot); + granting.erase(pid); +} + // Explicit confirmation comes from the client; all identity, month, eligibility // and consumption checks are authoritative here. Never turn an arbitrary quest // item into a ticket just because its value[0] happens to match the month. @@ -253,8 +291,8 @@ inline void PortBpActivate(LPCHARACTER ch,const PortBpSeason& season,PortBpState // A free-pass installation may have old progress. Activation starts fresh, // as clear_old_battlepass() does in the AVA2 quest. The ordered connection // runs the deletes before the new load, including across a quick reconnect. - DBManager::instance().Query("DELETE FROM player.mt_battlepass_progress WHERE pid=%u AND season=%u",ch->GetPlayerID(),season.id); - DBManager::instance().Query("DELETE FROM player.mt_battlepass_claim WHERE pid=%u AND season=%u",ch->GetPlayerID(),season.id); + DBManager::instance().Query("DELETE FROM mt_battlepass_progress WHERE pid=%u AND season=%u",ch->GetPlayerID(),season.id); + DBManager::instance().Query("DELETE FROM mt_battlepass_claim WHERE pid=%u AND season=%u",ch->GetPlayerID(),season.id); state.Reset(season.id);state.playtimeMark=get_dword_time();state.wantInfo=true; ch->SetQuestFlag("mt_bp.ticket_period",(date.tm_year+1900)*100+date.tm_mon+1); ch->SetQuestFlag("mt_bp.ticket_status",1); @@ -289,4 +327,24 @@ inline void PortBpCommand(LPCHARACTER ch,const char* argument) { PortBpClaim(ch,*season,*state,unsigned(atoi(args[2].c_str()))); if(state->loaded)PortBpSendInfo(ch,*season,*state); } +inline void PortBpNativeCommand(LPCHARACTER ch,const char* argument) { + if(!ch || !ch->IsPC() || !ch->GetDesc())return; + std::istringstream input(argument);std::string action,cell,vnum,extra; + if(!(input>>action))return; + const PortBpSeason* season=nullptr;PortBpState* state=PortBpSync(ch,season); + if(state)state->nativeUI=true; + if (state && state->lastCommand && get_dword_time()-state->lastCommand>extra)) { + if(state && state->loaded)PortBpAutoGrant(ch,*season,*state); + if(!state){ch->ChatPacket(CHAT_TYPE_COMMAND,"BattlePassClear");ch->ChatPacket(CHAT_TYPE_COMMAND,"BattlePassSetStatus 0 0 Empty");return;} + PortBpCommand(ch,"1 info"); + } else if (action=="reward" && !(input>>extra)) { + if(!state)return; + PortBpAutoGrant(ch,*season,*state); + for (const auto& m:season->missions)if(!state->claimed.count(m.slot)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error incomplete");return;} + PortBpCommand(ch,"1 claim 0"); + } else if (action=="activate" && (input>>cell>>vnum) && !(input>>extra)) { + PortBpCommand(ch,("1 activate "+cell+" "+vnum).c_str()); + } else if (action=="close" && !(input>>extra) && state)state->watching=false; +} #endif diff --git a/tests/features/test_battlepass.py b/tests/features/test_battlepass.py index dfc4bb34..533e6a10 100644 --- a/tests/features/test_battlepass.py +++ b/tests/features/test_battlepass.py @@ -71,7 +71,7 @@ static bool dbDown=false; using MYSQL_ROW=char**; struct Result{std::vector> rows;size_t next=0;std::vector cells;}; struct SQLResult{unsigned uiNumRows=0,uiAffectedRows=0;Result* pSQLResult=nullptr;}; -struct SQLMsg{SQLResult result;Result data;bool ok=true;SQLResult* Get(){return ok?&result:nullptr;}}; +struct SQLMsg{unsigned uiSQLErrno=0;SQLResult result;Result data;bool ok=true;SQLResult* Get(){return ok?&result:nullptr;}}; MYSQL_ROW mysql_fetch_row(Result* r){ if(r->next>=r->rows.size())return nullptr;auto& row=r->rows[r->next++];r->cells.clear(); for(auto& c:row)r->cells.push_back(&c[0]);return r->cells.data();} @@ -81,13 +81,13 @@ struct DBManager{ static DBManager& instance(){static DBManager m;return m;} void Query(const char* f,...){va_list a;va_start(a,f);std::string q=format(f,a);va_end(a);queries.push_back(q); queue.push_back([q]{ - if(q.rfind("DELETE FROM player.mt_battlepass_",0)==0){ + if(q.rfind("DELETE FROM mt_battlepass_",0)==0){ unsigned p,s;const bool isProgress=q.find("_progress")!=std::string::npos; - sscanf(q.c_str()+std::string(isProgress?"DELETE FROM player.mt_battlepass_progress WHERE pid=":"DELETE FROM player.mt_battlepass_claim WHERE pid=").size(),"%u AND season=%u",&p,&s); + sscanf(q.c_str()+std::string(isProgress?"DELETE FROM mt_battlepass_progress WHERE pid=":"DELETE FROM mt_battlepass_claim WHERE pid=").size(),"%u AND season=%u",&p,&s); if(isProgress){for(auto it=progress.begin();it!=progress.end();)if(std::get<0>(it->first)==p&&std::get<1>(it->first)==s)it=progress.erase(it);else ++it;} else {for(auto it=claims.begin();it!=claims.end();)if(std::get<0>(*it)==p&&std::get<1>(*it)==s)it=claims.erase(it);else ++it;}return; } - assert(q.rfind("INSERT INTO player.mt_battlepass_progress (pid,season,slot,value,target) VALUES (",0)==0); + assert(q.rfind("INSERT INTO mt_battlepass_progress (pid,season,slot,value,target) VALUES (",0)==0); assert(q.find("ON DUPLICATE KEY UPDATE value=LEAST(value+VALUES(value),VALUES(target)),target=VALUES(target)")!=std::string::npos); const char* p=q.c_str()+q.find("VALUES (")+7;unsigned pid,season,slot;unsigned long long v,t;int n; while(sscanf(p,"(%u,%u,%u,%llu,%llu)%n",&pid,&season,&slot,&v,&t,&n)==5){ @@ -95,8 +95,8 @@ struct DBManager{ });} template void FuncQuery(F f,const char* fmt,...){va_list a;va_start(a,fmt);std::string q=format(fmt,a);va_end(a);queries.push_back(q);++selects; queue.push_back([f,q]{unsigned pid,season,pid2,season2; - assert(sscanf(q.c_str(),"SELECT 'p',slot,value FROM player.mt_battlepass_progress WHERE pid=%u AND season=%u " - "UNION ALL SELECT 'c',slot,0 FROM player.mt_battlepass_claim WHERE pid=%u AND season=%u",&pid,&season,&pid2,&season2)==4); + assert(sscanf(q.c_str(),"SELECT 'p',slot,value FROM mt_battlepass_progress WHERE pid=%u AND season=%u " + "UNION ALL SELECT 'c',slot,0 FROM mt_battlepass_claim WHERE pid=%u AND season=%u",&pid,&season,&pid2,&season2)==4); assert(pid==pid2 && season==season2); SQLMsg m;m.ok=!dbDown;m.result.pSQLResult=&m.data; for(auto& e:progress)if(std::get<0>(e.first)==pid && std::get<1>(e.first)==season) @@ -105,7 +105,7 @@ struct DBManager{ m.result.uiNumRows=unsigned(m.data.rows.size());f(&m);});} SQLMsg* DirectQuery(const char* f,...){va_list a;va_start(a,f);std::string q=format(f,a);va_end(a);queries.push_back(q); SQLMsg* m=new SQLMsg;m->ok=!dbDown;unsigned pid,season,slot;long long at; - assert(sscanf(q.c_str(),"INSERT IGNORE INTO player.mt_battlepass_claim (pid,season,slot,claimed_at) VALUES (%u,%u,%u,%lld)",&pid,&season,&slot,&at)==4 && at==now); + assert(sscanf(q.c_str(),"INSERT IGNORE INTO mt_battlepass_claim (pid,season,slot,claimed_at) VALUES (%u,%u,%u,%lld)",&pid,&season,&slot,&at)==4 && at==now); if(m->ok)m->result.uiAffectedRows=claims.insert(std::make_tuple(pid,season,slot)).second?1:0; return m;} void Run(){while(!queue.empty()){auto job=queue.front();queue.pop_front();job();}} @@ -284,6 +284,24 @@ int main(int argc,char** argv){ tick();PortBpCommand(locked,"1 activate 3 25159");assert(Last(locked)=="MTBP1 error activated"); Kill(locked,101);assert(PortBpStates()[20].delta[1]==1); locked->SetQuestFlag("mt_bp.ticket_period",202510);assert(PortBpAccess(locked)==0); + + // Native mode reuses existing progress/claims and automatically grants each mission once. + WriteConfig("MTBATTLEPASS 1\nseason 99 "+std::to_string(now-10)+" "+std::to_string(now+10000)+"\nmission 1 1 0 1 25041 1\nfinal 27992 1\n");tick(5001); + auto native=new CHARACTER;native->pid=31;online[31]=native; + PortBpNativeCommand(native,"info");db.Run(); + assert(Said(native,"BattlePassClear") && Said(native,"BattlePassAppendMission 10 25041|1 0 1 0 1")); + Kill(native,101);assert(PortBpStates()[31].claimed.count(1) && claims.count(std::make_tuple(31u,99u,1u))); + auto paid=native->bag.size();tick();PortBpNativeCommand(native,"info");db.Run();assert(native->bag.size()==paid); + tick();PortBpNativeCommand(native,"reward");assert(PortBpStates()[31].claimed.count(0) && PortBpAccess(native)==2); + paid=native->bag.size();tick();PortBpNativeCommand(native,"reward");assert(native->bag.size()==paid); + auto migrated=new CHARACTER;migrated->pid=32;online[32]=migrated; + progress[std::make_tuple(32u,99u,1u)]={1,1};claims.insert(std::make_tuple(32u,99u,1u)); + PortBpNativeCommand(migrated,"info");db.Run();assert(migrated->bag.empty() && PortBpStates()[32].claimed.count(1)); + auto full=new CHARACTER;full->pid=33;online[33]=full;std::fill(full->used.begin(),full->used.end(),true); + progress[std::make_tuple(33u,99u,1u)]={1,1};PortBpNativeCommand(full,"info");db.Run();assert(!PortBpStates()[33].claimed.count(1)); + std::fill(full->used.begin(),full->used.end(),false);tick();PortBpNativeCommand(full,"info");assert(PortBpStates()[33].claimed.count(1) && full->bag.size()==1); + for(const auto& sql:db.queries)assert(sql.find("player.")==std::string::npos); + // --- the file is removed: no season, nothing counted std::remove((basePath+"/port_battlepass.tsv").c_str());tick(5001);mark=b->messages.size(); PortBpCommand(b,"1 info");assert(Last(b)=="MTBP1 none"); diff --git a/tests/features/test_native_queries.py b/tests/features/test_native_queries.py new file mode 100644 index 00000000..8631dc48 --- /dev/null +++ b/tests/features/test_native_queries.py @@ -0,0 +1,54 @@ +"""Run native drop/calendar handlers against loaded-table fixtures and real schedule rules.""" +from pathlib import Path +import subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2];SRC=ROOT/'src/server/game/src' +code=r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "port_calendar.h" +static int now=1792390000;int get_global_time(){return now;}unsigned g_bChannel=5; +size_t strlcpy(char* out,const char* in,size_t n){size_t len=strlen(in);if(n){memcpy(out,in,std::min(len,n-1));out[std::min(len,n-1)]=0;}return len;} +struct Desc {std::string version="1215955205mt20261019";std::vector packets;const char* GetClientVersion(){return version.c_str();}void Packet(const void* p,size_t n){packets.emplace_back((const char*)p,n);}}; +struct Character {Desc desc;std::map protect;unsigned empire=1;std::vector commands;Desc* GetDesc(){return &desc;}unsigned GetEmpire(){return empire;}int GetProtectTime(const char* key){return protect[key];}void SetProtectTime(const char* key,int value){protect[key]=value;}void ChatPacket(int,const char* text){commands.emplace_back(text);}}; +using LPCHARACTER=Character*; +#define ACMD(name) void name(LPCHARACTER ch,const char* argument) +enum {CHAT_TYPE_COMMAND=5,ITEM_GIFTBOX=23,ITEM_TREASURE_BOX=17,WIKI_SINGLE=1,WIKI_INDEPENDENT=2}; +struct Proto {unsigned dwVnum,dwRefinedVnum,bType;char szLocaleName[32]="item";}; +struct Row {unsigned item,count,rule,total,weight;}; +struct Manager {std::vector tables;std::map> mobs,chests;static Manager& instance(){static Manager m;return m;}const Proto* GetTable(unsigned id){for(auto& t:tables)if(t.dwVnum==id)return &t;return nullptr;}const std::vector& GetTable(){return tables;}std::vector PortWikiDrops(unsigned id){return mobs[id];}std::vector PortWikiChest(unsigned id){return chests[id];}}; +using ITEM_MANAGER=Manager; +struct Mob {Proto m_table;}; +struct CMobManager {std::map mobs;static CMobManager& instance(){static CMobManager m;return m;}auto begin(){return mobs.begin();}auto end(){return mobs.end();}}; +PortCalendar schedule;PortCalendar& PortCurrentEvents(){return schedule;} +struct TEMP_BUFFER {std::string bytes;void write(const void* p,size_t n){bytes.append((const char*)p,n);}const char* read_peek(){return bytes.data();}size_t size(){return bytes.size();}}; +#include "ava2_native_queries.h" +int main(){ + static_assert(sizeof(TPacketCGAva2Drop)==6,"");static_assert(sizeof(TPacketGCAva2Drop)==114,"");static_assert(sizeof(TPacketGCAva2Events)==5,"");static_assert(sizeof(TAva2Event)==81,""); + Character c;auto& m=Manager::instance();m.tables={{19,20,1},{20,0,1},{500,0,ITEM_GIFTBOX}}; + Mob mob;CMobManager::instance().mobs[101]=&mob;m.mobs[101]={{19,2,0,0,0},{20,1,0,0,0}};m.chests[500]={{19,1,WIKI_SINGLE,100,25}}; + PortNativeDrop(&c,{215,6,101});assert(c.desc.packets.size()==4);TPacketGCAva2Drop row;memcpy(&row,c.desc.packets[1].data(),sizeof(row));assert(row.vnum==19 && row.count==2 && row.prob==0); + c.desc.packets.clear();PortNativeDrop(&c,{215,7,500});assert(c.desc.packets.size()==2 && (unsigned char)c.desc.packets.back()[1]==6); // refusal is not an empty result + ++now;c.desc.packets.clear();PortNativeDrop(&c,{215,7,500});memcpy(&row,c.desc.packets[1].data(),sizeof(row));assert(row.vnum==19 && row.prob==25); + ++now;c.desc.packets.clear();PortNativeDrop(&c,{215,9,19});assert(c.desc.packets.size()==4); // both refinements + c.desc.version="1215955205mt20261016";c.desc.packets.clear();PortNativeDrop(&c,{215,6,101});do_event_manager(&c,"info");assert(c.desc.packets.empty());c.desc.version="1215955205mt20261019"; + schedule.valid=false;do_event_manager(&c,"info");assert(c.commands.back()=="EventCalendarError unavailable");now+=2; + schedule.valid=true;schedule.events={{1,1,unsigned(now-1),unsigned(now+60),5,1},{2,2,unsigned(now+60),unsigned(now+120),0,0}}; + do_event_manager(&c,"info");assert(c.desc.packets.size()==1);const auto& wire=c.desc.packets.back();TPacketGCAva2Events head;memcpy(&head,wire.data(),5);assert(head.header==214 && head.size==wire.size());assert((unsigned char)wire[6]==1);TAva2Event event;memcpy(&event,wire.data()+13,81);assert(event.kind==8 && event.active==1 && strlen(event.startText)==19); // 5 header + 6 payload + 2 day header + now+=2;c.desc.packets.clear();c.empire=2;do_event_manager(&c,"info");memcpy(&event,c.desc.packets[0].data()+13,81);assert(event.active==0); + now+=2;c.desc.packets.clear();schedule.events.clear();do_event_manager(&c,"info");assert(c.desc.packets[0].size()==11 && c.desc.packets[0][6]==0); + ++now;c.desc.packets.clear();m.mobs[101].assign(4097,{19,1,0,0,0});PortNativeDrop(&c,{215,6,101});assert(c.desc.packets.size()==4098 && (unsigned char)c.desc.packets.back()[1]==6); + puts("PASS: native packet widths, loaded drops, refine family, rate/overflow errors, version gate, actual scoped UTC calendar"); +} +''' +with tempfile.TemporaryDirectory(prefix='native-queries-') as d: + p=Path(d);(p/'test.cpp').write_text(code) + subprocess.run(['c++','-std=c++17','-Wall','-I'+str(SRC),str(p/'test.cpp'),'-o',str(p/'test')],check=True) + subprocess.run([str(p/'test')],check=True) diff --git a/tests/features/test_switchbot.py b/tests/features/test_switchbot.py index 4e14d4e3..44ded178 100644 --- a/tests/features/test_switchbot.py +++ b/tests/features/test_switchbot.py @@ -103,8 +103,8 @@ if cpacket.is_file(): assert 'static_assert(sizeof(TPacketCGSwitchbot) == 7 && sizeof(TPacketGCSwitchbot) == 7,' in client stream=(CLIENT/'PythonNetworkStreamPhaseGame.cpp').read_bytes().decode('latin1') # the EU branch (the one every locale.cfg build takes) keeps 1215955205 first for the atoi version check - assert 'strncpy(kVersionPacket.timestamp, "1215955205 mt20261016", sizeof(kVersionPacket.timestamp)-1);' in stream - assert 'strncpy(kVersionPacket.timestamp, "mt20261016", sizeof(kVersionPacket.timestamp)-1);' in stream + assert 'strncpy(kVersionPacket.timestamp, "1215955205 mt20261019", sizeof(kVersionPacket.timestamp)-1);' in stream + assert 'strncpy(kVersionPacket.timestamp, "mt20261019", sizeof(kVersionPacket.timestamp)-1);' in stream pyswitch=(CLIENT/'PythonSwitchbot.h').read_bytes().decode('latin1') ctable=pyswitch[pyswitch.index('struct TSwitchbotTable'):];ctable=ctable[:ctable.index('};')] assert re.findall(r'^\s*[A-Za-z_][\w:]*\s+(\w+)(?:\[[^;]*\])?;',ctable,re.M)==table,ctable diff --git a/tools/battlepass/schema.sql b/tools/battlepass/schema.sql index 67b04056..d974ad4c 100644 --- a/tools/battlepass/schema.sql +++ b/tools/battlepass/schema.sql @@ -1,6 +1,6 @@ -- PORT: battle pass tables (docs/FEATURE-BATTLEPASS.md). Idempotent; run once on the player database. -- Progress: one row per player, season and mission slot; the game adds deltas and MySQL caps them at target. -CREATE TABLE IF NOT EXISTS player.mt_battlepass_progress ( +CREATE TABLE IF NOT EXISTS mt_battlepass_progress ( pid INT UNSIGNED NOT NULL, season INT UNSIGNED NOT NULL, slot TINYINT UNSIGNED NOT NULL, @@ -11,7 +11,7 @@ CREATE TABLE IF NOT EXISTS player.mt_battlepass_progress ( ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- Claims: the primary key is the idempotency guard; only the request whose INSERT IGNORE adds the row pays out. -- slot 0 is the final reward. -CREATE TABLE IF NOT EXISTS player.mt_battlepass_claim ( +CREATE TABLE IF NOT EXISTS mt_battlepass_claim ( pid INT UNSIGNED NOT NULL, season INT UNSIGNED NOT NULL, slot TINYINT UNSIGNED NOT NULL, diff --git a/tools/native-systems/deploy.py b/tools/native-systems/deploy.py new file mode 100644 index 00000000..18dc63db --- /dev/null +++ b/tools/native-systems/deploy.py @@ -0,0 +1,82 @@ +#!/usr/local/bin/python3.9 +"""203 game-only deployment. Keep db running; back up first; retain earned claims on rollback.""" +import argparse,hashlib,json,os,shutil,signal,subprocess,time +from pathlib import Path +ROOT=Path('/usr/metin2/server') +CORES=[ROOT/'auth']+[ROOT/('channel%d/%s'%(ch,part)) for ch in range(1,5) for part in ('first','game1','game2')]+[ROOT/'game99'] +LIVE=ROOT/'share/bin/game';CAL=ROOT/'share/locale/newcibn/port_events.tsv' +def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest() +def alive(pid): + try:os.kill(pid,0);return True + except ProcessLookupError:return False +def pid(core): + try:return int((core/'pid').read_text().strip()) + except (OSError,ValueError):return 0 +def verified_pid(core): + value=pid(core) + if not value or not alive(value):return 0 + details=subprocess.check_output(['procstat','-f',str(value)]).decode() + if not any(' cwd ' in line and str(core) in line for line in details.splitlines()):raise RuntimeError('Unexpected pid owner for '+str(core)) + return value +def stop(): + pending=[verified_pid(core) for core in CORES];pending=[p for p in pending if p] + for value in pending:os.kill(value,signal.SIGHUP) + deadline=time.time()+300 + while any(alive(p) for p in pending): + if time.time()>deadline:raise RuntimeError('Graceful stop timed out; binary remains unchanged') + time.sleep(.5) +def port(core): + return int(next(line.split(':',1)[1] for line in (core/'CONFIG').read_text().splitlines() if line.startswith('PORT:'))) +def start(): + for core in CORES: + if verified_pid(core):continue + executable='./auth' if core.name=='auth' else './game' + subprocess.run(['daemon','-f','-o',str(core/'native-deploy.stdout'),executable],cwd=str(core),check=True) + time.sleep(.3) + deadline=time.time()+55 + while True: + listeners=subprocess.check_output(['sockstat','-4','-l','-P','tcp']).decode() + missing=[str(core.relative_to(ROOT)) for core in CORES if not verified_pid(core) or (':%d '%port(core)) not in listeners] + if not missing:return + if time.time()>deadline:raise RuntimeError('Cores failed health check: '+','.join(missing)) + time.sleep(1) +def replace(source): + target=LIVE.with_suffix('.native-new');shutil.copy2(source,target);target.chmod(0o755);target.replace(LIVE) +def report(): + print(json.dumps({'game_sha256':digest(LIVE),'cores':{str(c.relative_to(ROOT)):verified_pid(c) for c in CORES},'db_running':alive(pid(ROOT/'db'))},sort_keys=True),flush=True) +def rollback(backup): + meta=json.loads((backup/'metadata.json').read_text());stop();replace(backup/'game') + # Progress/claim rows are intentionally retained: reverting them could pay rewards twice. + if not meta['calendar_existed'] and CAL.exists() and CAL.read_bytes()==b'MTCALENDAR 1\n':CAL.unlink() + start();report() +def deploy(candidate,expected,destination): + if digest(candidate)!=expected:raise RuntimeError('Staged candidate hash mismatch') + if not alive(pid(ROOT/'db')):raise RuntimeError('Production db is not running') + for core in CORES:verified_pid(core) + backup=destination/time.strftime('%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700) + shutil.copy2(LIVE,backup/'game') + meta={'old_hash':digest(LIVE),'new_hash':expected,'calendar_existed':CAL.exists(),'syserr_offsets':{str(c.relative_to(ROOT)):(c/'syserr').stat().st_size if (c/'syserr').exists() else 0 for c in CORES}} + (backup/'metadata.json').write_text(json.dumps(meta,indent=2)+'\n') + for name in ('port_events.tsv','port_battlepass.tsv'): + f=CAL.parent/name + if f.exists():shutil.copy2(f,backup/name) + for table in ('mt_battlepass_progress','mt_battlepass_claim'): + data=subprocess.check_output(['mysqldump','--no-create-info','--complete-insert','--skip-add-locks','player',table]);f=backup/(table+'.sql');f.write_bytes(data);f.chmod(0o600) + print('backup='+str(backup),flush=True) + try: + stop() + replace(candidate) + if not CAL.exists(): + temporary=CAL.with_suffix('.native-new');temporary.write_bytes(b'MTCALENDAR 1\n');temporary.replace(CAL) + start();report() + except Exception: + rollback(backup);raise + (backup/'DEPLOYED').write_text(expected+'\n') + print('deployed='+str(backup),flush=True) +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('action',choices=['check','deploy','rollback']);p.add_argument('--candidate',type=Path);p.add_argument('--sha256');p.add_argument('--backups',type=Path,default=Path('/root/backup-native-systems'));p.add_argument('--backup',type=Path);a=p.parse_args() + if a.action=='check':report() + elif a.action=='rollback':rollback(a.backup) + else: + if not a.candidate or not a.sha256:p.error('deploy requires --candidate and --sha256') + deploy(a.candidate,a.sha256,a.backups)