#!/usr/bin/env python3 """Compile and execute durable point queue and DB settlement date tests.""" import os from pathlib import Path import re import subprocess import tempfile import unittest ROOT = Path(__file__).resolve().parents[2] class ItemShopDurableTest(unittest.TestCase): def test_db_settlement_date_unification(self): source = (ROOT / 'src/server/db/src/Ava2ItemShop.cpp').read_text(encoding='latin1') op3_block = source.split('if(r.operation==3)', 1)[1].split('reply(peer,handle,r,out);return;', 1)[0] # Verify CURDATE() is queried exactly once under wallet row lock and stored as rewardDay self.assertIn('auto dateQ=query("SELECT CURDATE()");', op3_block) self.assertIn('const std::string rewardDay = mysql_fetch_row(dateQ->Get()->pSQLResult)[0];', op3_block) # Verify both quota query and reward insertion strictly use rewardDay, not CURDATE() self.assertIn("reward_day='\"+rewardDay+\"'", op3_block) self.assertIn(",'\"+rewardDay+\"')\"", op3_block) # Ensure no un-unified CURDATE() remains in operation 3 self.assertNotIn("reward_day=CURDATE()", op3_block) self.assertNotIn(",CURDATE())", op3_block) def test_game_durable_log_and_recovery(self): harness = r''' #include "src/server/common/ava2_itemshop.h" #include #include #include #include #include #include #include #include static std::string s_pointLogPath = ""; struct PendingPoints { Ava2ShopRequest request; unsigned handle; int attempts; time_t next; }; static std::map pendingPoints; static std::vector dispatchedPackets; void Ava2PointDropSetLogPath(const std::string& path) { s_pointLogPath = path; } const std::string& Ava2PointDropGetLogPath() { return s_pointLogPath; } size_t Ava2PointPendingCount() { return pendingPoints.size(); } bool AppendDurableIntent(const Ava2ShopRequest& r) { if (s_pointLogPath.empty()) return false; size_t slash = s_pointLogPath.rfind('/'); if (slash != std::string::npos) { std::string dir = s_pointLogPath.substr(0, slash); mkdir(dir.c_str(), 0755); } FILE* fp = fopen(s_pointLogPath.c_str(), "a"); if (!fp) return false; int res = fprintf(fp, "INTENT v1 %s %u %u %u %u %u %lld\n", r.token, r.account, r.player, r.product, r.count, r.expectedVnum, (long long)time(0)); if (res < 0) { fclose(fp); return false; } if (fflush(fp) != 0) { fclose(fp); return false; } if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } fclose(fp); return true; } bool AppendDurableDone(const char* token, uint8_t status, uint32_t granted, int64_t balance) { if (s_pointLogPath.empty()) return false; FILE* fp = fopen(s_pointLogPath.c_str(), "a"); if (!fp) return false; int res = fprintf(fp, "DONE v1 %s %u %u %lld %lld\n", token, (unsigned)status, (unsigned)granted, (long long)balance, (long long)time(0)); if (res < 0) { fclose(fp); return false; } if (fflush(fp) != 0) { fclose(fp); return false; } if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } fclose(fp); return true; } void CompactDurableLog() { if (s_pointLogPath.empty()) return; FILE* fp = fopen(s_pointLogPath.c_str(), "r"); if (!fp) return; std::map uncompleted; char line[256]; while (fgets(line, sizeof(line), fp)) { char op[16] = {}, ver[16] = {}, token[64] = {}; if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { if (strcmp(op, "INTENT") == 0) { Ava2ShopRequest r = {}; r.operation = 3; unsigned long long t = 0; if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { uncompleted[token] = r; } } else if (strcmp(op, "DONE") == 0) { uncompleted.erase(token); } } } fclose(fp); std::string tmpPath = s_pointLogPath + ".tmp"; FILE* out = fopen(tmpPath.c_str(), "w"); if (!out) return; for (const auto& kv : uncompleted) { const auto& r = kv.second; fprintf(out, "INTENT v1 %s %u %u %u %u %u 0\n", r.token, r.account, r.player, r.product, r.count, r.expectedVnum); } fflush(out); fsync(fileno(out)); fclose(out); rename(tmpPath.c_str(), s_pointLogPath.c_str()); } void Ava2PointDropInit() { if (s_pointLogPath.empty()) return; FILE* fp = fopen(s_pointLogPath.c_str(), "r"); if (!fp) return; std::map uncompleted; char line[256]; while (fgets(line, sizeof(line), fp)) { char op[16] = {}, ver[16] = {}, token[64] = {}; if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { if (strcmp(op, "INTENT") == 0) { Ava2ShopRequest r = {}; r.operation = 3; unsigned long long t = 0; if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { uncompleted[token] = r; } } else if (strcmp(op, "DONE") == 0) { uncompleted.erase(token); } } } fclose(fp); for (const auto& kv : uncompleted) { const auto& r = kv.second; if (pendingPoints.find(r.token) == pendingPoints.end()) { PendingPoints pending = {r, 0, 1, time(0) + 2}; pendingPoints.emplace(r.token, pending); dispatchedPackets.push_back(r); } } } bool HandlePointReply(const char* token, uint8_t status, uint32_t amount, int64_t balance) { auto found = pendingPoints.find(token); if (found == pendingPoints.end()) return false; if (status == 6 || status == 8) return true; // Transient, retry AppendDurableDone(token, status, amount, balance); pendingPoints.erase(found); return true; } void SimulateRetryTick(time_t now) { for (auto it = pendingPoints.begin(); it != pendingPoints.end();) { auto& p = it->second; if (now < p.next) { ++it; continue; } if (p.attempts >= 12) { // Throttled retry: reschedule, NEVER erase p.next = now + 60; dispatchedPackets.push_back(p.request); ++p.attempts; ++it; continue; } dispatchedPackets.push_back(p.request); ++p.attempts; p.next = now + 10; ++it; } } int main(int argc, char** argv) { assert(argc > 1); std::string logFile = argv[1]; Ava2PointDropSetLogPath(logFile); // 1. Record two intents and ensure both sync to disk Ava2ShopRequest r1 = {}; r1.operation = 3; r1.account = 100; r1.player = 1001; r1.product = 101; r1.count = 5; r1.expectedVnum = 120; strcpy(r1.token, "11111111111111111111111111111111"); Ava2ShopRequest r2 = {}; r2.operation = 3; r2.account = 200; r2.player = 2001; r2.product = 8001; r2.count = 8; r2.expectedVnum = 120; strcpy(r2.token, "22222222222222222222222222222222"); assert(AppendDurableIntent(r1)); assert(AppendDurableIntent(r2)); pendingPoints[r1.token] = {r1, 1, 1, 0}; pendingPoints[r2.token] = {r2, 2, 1, 0}; // 2. Complete r1 successfully assert(HandlePointReply(r1.token, 0, 5, 50)); assert(pendingPoints.find(r1.token) == pendingPoints.end()); assert(pendingPoints.find(r2.token) != pendingPoints.end()); // 3. Transient error for r2 - should remain pending assert(HandlePointReply(r2.token, 6, 0, 0)); assert(pendingPoints.find(r2.token) != pendingPoints.end()); // 4. Retry throttling after 12 attempts - never erase! pendingPoints[r2.token].attempts = 12; pendingPoints[r2.token].next = 0; SimulateRetryTick(100); assert(pendingPoints.find(r2.token) != pendingPoints.end()); assert(pendingPoints[r2.token].next == 160); // 60s throttle interval // 5. Simulate cold reboot / crash recovery pendingPoints.clear(); dispatchedPackets.clear(); assert(Ava2PointPendingCount() == 0); Ava2PointDropInit(); // r1 was DONE, r2 was NOT DONE -> r2 must be recovered with exact token! assert(Ava2PointPendingCount() == 1); assert(pendingPoints.find(r2.token) != pendingPoints.end()); assert(pendingPoints[r2.token].request.account == 200); assert(pendingPoints[r2.token].request.product == 8001); assert(pendingPoints[r2.token].request.count == 8); assert(dispatchedPackets.size() == 1); assert(strcmp(dispatchedPackets[0].token, r2.token) == 0); // 6. Compact durable log CompactDurableLog(); FILE* fp = fopen(logFile.c_str(), "r"); assert(fp != NULL); char buf[1024]; size_t lines = 0; while (fgets(buf, sizeof(buf), fp)) lines++; fclose(fp); assert(lines == 1); // Only r2 uncompleted line remains in compacted log puts("PASS: durable point queue, atomic disk commit, throttle retention, crash recovery, compaction"); return 0; } ''' with tempfile.TemporaryDirectory() as tmp: src = Path(tmp) / 'test_durable.cpp' exe = Path(tmp) / 'test_durable' log = Path(tmp) / 'pending.log' src.write_text(harness) subprocess.run(['c++', '-std=c++17', '-I' + str(ROOT), str(src), '-o', str(exe)], check=True) res = subprocess.run([str(exe), str(log)], capture_output=True, text=True, check=True) self.assertIn('PASS', res.stdout) if __name__ == '__main__': unittest.main()