test_ghs_stock_concurrency.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * Concurrently calls app-ghs order/create-order and stock-out/create-order,
  5. * then compares xhGhsItem.stock with the expected stock after successful calls.
  6. *
  7. * WARNING: this script sends real requests to api.shop.hzghd.com and creates
  8. * real business records. It does not rollback stock, orders, or stock-out rows.
  9. *
  10. * Usage:
  11. * php scripts/test_ghs_stock_concurrency.php
  12. * php scripts/test_ghs_stock_concurrency.php --rounds=10
  13. * php scripts/test_ghs_stock_concurrency.php --order=2 --stock-out=2 --rounds=3
  14. */
  15. require(__DIR__ . '/../vendor/autoload.php');
  16. require(__DIR__ . '/../env.php');
  17. require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
  18. require(__DIR__ . '/../common/config/bootstrap.php');
  19. require(__DIR__ . '/../console/config/bootstrap.php');
  20. $config = yii\helpers\ArrayHelper::merge(
  21. require(__DIR__ . '/../common/config/main.php'),
  22. require(__DIR__ . '/../common/config/main-local.php'),
  23. require(__DIR__ . '/../console/config/main.php'),
  24. require(__DIR__ . '/../console/config/main-local.php')
  25. );
  26. unset($config['components']['request']);
  27. new yii\console\Application($config);
  28. if (!extension_loaded('curl')) {
  29. fwrite(STDERR, "ERROR: PHP curl extension is required.\n");
  30. exit(1);
  31. }
  32. $options = getopt('', ['order::', 'stock-out::', 'rounds::']);
  33. $orderCount = normalizePositiveInt($options, 'order', 1);
  34. $stockOutCount = normalizePositiveInt($options, 'stock-out', 1);
  35. $rounds = normalizePositiveInt($options, 'rounds', 1);
  36. $baseUrl = 'http://api.shop.hzghd.com';
  37. $productIds = [27286, 27282];
  38. $commonHeaders = [
  39. 'Connection: keep-alive',
  40. 'account: 12362',
  41. 'content-type: application/x-www-form-urlencoded;charset=UTF-8',
  42. 'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 17_0_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0.1 Mobile/21A360 Safari/604.1 wechatdevtools/2.01.2510260 MicroMessenger/8.0.5 Language/zh_CN webview/ hash/1237023557 sid/o7x10OLPfZ',
  43. 'token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImp0aSI6IjBfOTMyIn0.eyJpc3MiOiJodHRwczpcL1wvYXBpLnNob3AuaHpnaGQuY29tIiwiYXVkIjoiaHR0cHM6XC9cL2FwaS5zaG9wLmh6Z2hkLmNvbSIsImp0aSI6IjBfOTMyIiwiaWF0IjoxNzc5Mjc1MzgxLCJuYmYiOjE3NzkyNzUzODEsImV4cCI6MTg3Mzg4MzM4MSwidW5pcXVlSWQiOjkzMiwic291cmNlSWQiOjB9.OVuQTjXMvklAFnYdIIRGVR2D5VK14Dp6QX5bDQAUHyE',
  44. 'appVersion: 2',
  45. 'Accept: */*',
  46. 'Sec-Fetch-Site: cross-site',
  47. 'Sec-Fetch-Mode: cors',
  48. 'Sec-Fetch-Dest: empty',
  49. 'Referer: https://servicewechat.com/wx21b7c3ef12082099/devtools/page-frame.html',
  50. 'Accept-Language: zh-CN,zh;q=0.9',
  51. ];
  52. $orderBody = 'shopId=12986&shopName=&sendType=0&transType=4&sendDate=&sendTimeWant=&historyDate=&sendCost=&customSendCost=0&customId=914&packCost=&product=%5B%7B%22productId%22%3A%2227286%22%2C%22bigNum%22%3A2%2C%22smallNum%22%3A0%2C%22classId%22%3A%223322%22%2C%22itemId%22%3A%221009%22%2C%22price%22%3A%2227.00%22%2C%22remark%22%3A%22%22%7D%2C%7B%22productId%22%3A%2227282%22%2C%22bigNum%22%3A2%2C%22smallNum%22%3A0%2C%22classId%22%3A%223322%22%2C%22itemId%22%3A%221005%22%2C%22price%22%3A%220.30%22%2C%22remark%22%3A%22%22%7D%5D&remark=&payWay=0&needPrint=1&hasPay=2&getStaffId=0&getStaffName=&dealPrice=0&wlName=&reductionRule=0&callErrand=0&weight=1&deliveryRemark=&customName=%E5%BE%AE%E5%8D%87%E6%BC%AB%E8%8A%B1&modifyPrice=54.6&newVersion=1&book=0&xj=%22%22&treeData=%22%22';
  53. $stockOutBody = 'confirmIn=1&date=2026-05-25&remark=123&inShopId=37043&itemInfo=%5B%7B%22productId%22%3A%2227286%22%2C%22bigNum%22%3A1%2C%22smallNum%22%3A0%2C%22name%22%3A%22%E8%8B%8F%E9%86%92%22%7D%2C%7B%22productId%22%3A%2227282%22%2C%22bigNum%22%3A1%2C%22smallNum%22%3A0%2C%22name%22%3A%22%E6%B4%9B%E7%A5%9E%22%7D%5D&action=confirm';
  54. $requestDefs = [
  55. 'order' => [
  56. 'url' => $baseUrl . '/order/create-order',
  57. 'body' => $orderBody,
  58. 'stockDelta' => [27286 => '2', 27282 => '2'],
  59. ],
  60. 'stock-out' => [
  61. 'url' => $baseUrl . '/stock-out/create-order',
  62. 'body' => $stockOutBody,
  63. 'stockDelta' => [27286 => '1', 27282 => '1'],
  64. ],
  65. ];
  66. echo "app-ghs stock concurrency test\n";
  67. echo "Target: {$baseUrl}\n";
  68. echo "Rounds: {$rounds}, order/create-order: {$orderCount}, stock-out/create-order: {$stockOutCount}\n";
  69. echo "Products: " . implode(', ', $productIds) . "\n";
  70. echo "WARNING: real requests will create real orders and decrease real stock.\n\n";
  71. $overallPass = true;
  72. $overallInvalid = false;
  73. $overallConcurrencyError = false;
  74. $appLogFile = __DIR__ . '/../app-ghs/runtime/logs/app.log';
  75. for ($round = 1; $round <= $rounds; $round++) {
  76. echo "========== Round {$round}/{$rounds} ==========\n";
  77. $before = loadStocks($productIds);
  78. printStocks('Before', $before, $productIds);
  79. $requests = buildRequests($requestDefs, $orderCount, $stockOutCount);
  80. $logOffset = getFileSize($appLogFile);
  81. $responses = runConcurrentRequests($requests, $commonHeaders);
  82. $newLog = readFileFromOffset($appLogFile, $logOffset);
  83. $concurrencyErrors = findConcurrencyErrors($newLog);
  84. foreach ($responses as $response) {
  85. $ok = $response['businessSuccess'] ? 'OK' : 'ERR';
  86. echo sprintf(
  87. "[%s] %-18s HTTP %s %.3fs %s\n",
  88. $ok,
  89. $response['label'],
  90. $response['httpCode'],
  91. $response['totalTime'],
  92. $response['summary']
  93. );
  94. }
  95. if (!empty($concurrencyErrors)) {
  96. echo "Concurrency errors from app log:\n";
  97. foreach ($concurrencyErrors as $errorLine) {
  98. echo " - " . $errorLine . "\n";
  99. }
  100. }
  101. $successCounts = countSuccessfulRequests($responses);
  102. $after = loadStocks($productIds);
  103. $expected = calcExpectedStocks($before, $requestDefs, $successCounts, $productIds);
  104. printStocks('Expected after successful requests', $expected, $productIds);
  105. printStocks('Actual', $after, $productIds);
  106. printDiff($expected, $after, $productIds);
  107. $allBusinessSuccess = count($responses) === array_sum($successCounts);
  108. $stockMatches = stocksMatch($expected, $after, $productIds);
  109. if (!$allBusinessSuccess && !empty($concurrencyErrors)) {
  110. $overallConcurrencyError = true;
  111. echo "Round result: CONCURRENCY_ERROR (business request failed because concurrent stock update hit a database lock/deadlock)\n\n";
  112. continue;
  113. }
  114. if (!$allBusinessSuccess) {
  115. $overallInvalid = true;
  116. echo "Round result: INVALID (one or more business requests failed; this round is not a valid concurrency conclusion)\n\n";
  117. continue;
  118. }
  119. if ($stockMatches) {
  120. echo "Round result: PASS\n\n";
  121. } else {
  122. $overallPass = false;
  123. echo "Round result: FAIL (stock mismatch after all business requests succeeded)\n\n";
  124. }
  125. }
  126. if ($overallConcurrencyError) {
  127. echo "FINAL: CONCURRENCY_ERROR\n";
  128. exit(4);
  129. }
  130. if ($overallInvalid) {
  131. echo "FINAL: INVALID (at least one round had failed business responses)\n";
  132. }
  133. if (!$overallInvalid && $overallPass) {
  134. echo "FINAL: PASS\n";
  135. exit(0);
  136. }
  137. if (!$overallPass) {
  138. echo "FINAL: FAIL\n";
  139. exit(2);
  140. }
  141. exit(3);
  142. function normalizePositiveInt($options, $key, $default)
  143. {
  144. if (!isset($options[$key]) || $options[$key] === false || $options[$key] === '') {
  145. return $default;
  146. }
  147. $value = (int)$options[$key];
  148. if ($value < 1) {
  149. fwrite(STDERR, "ERROR: --{$key} must be a positive integer.\n");
  150. exit(1);
  151. }
  152. return $value;
  153. }
  154. function loadStocks($productIds)
  155. {
  156. $rows = Yii::$app->db->createCommand(
  157. 'select id, stock from xhGhsItem where id in (' . implode(',', array_map('intval', $productIds)) . ')'
  158. )->queryAll();
  159. $stocks = [];
  160. foreach ($rows as $row) {
  161. $stocks[(int)$row['id']] = (string)$row['stock'];
  162. }
  163. foreach ($productIds as $productId) {
  164. if (!array_key_exists($productId, $stocks)) {
  165. throw new RuntimeException("Product {$productId} was not found in xhGhsItem.");
  166. }
  167. }
  168. return $stocks;
  169. }
  170. function buildRequests($requestDefs, $orderCount, $stockOutCount)
  171. {
  172. $requests = [];
  173. for ($i = 1; $i <= $orderCount; $i++) {
  174. $requests[] = [
  175. 'type' => 'order',
  176. 'label' => 'order#' . $i,
  177. 'url' => $requestDefs['order']['url'],
  178. 'body' => $requestDefs['order']['body'],
  179. ];
  180. }
  181. for ($i = 1; $i <= $stockOutCount; $i++) {
  182. $requests[] = [
  183. 'type' => 'stock-out',
  184. 'label' => 'stock-out#' . $i,
  185. 'url' => $requestDefs['stock-out']['url'],
  186. 'body' => $requestDefs['stock-out']['body'],
  187. ];
  188. }
  189. return $requests;
  190. }
  191. function runConcurrentRequests($requests, $headers)
  192. {
  193. $multi = curl_multi_init();
  194. $handles = [];
  195. foreach ($requests as $index => $request) {
  196. $ch = curl_init($request['url']);
  197. curl_setopt_array($ch, [
  198. CURLOPT_POST => true,
  199. CURLOPT_POSTFIELDS => $request['body'],
  200. CURLOPT_HTTPHEADER => $headers,
  201. CURLOPT_RETURNTRANSFER => true,
  202. CURLOPT_ENCODING => '',
  203. CURLOPT_CONNECTTIMEOUT => 10,
  204. CURLOPT_TIMEOUT => 60,
  205. ]);
  206. curl_multi_add_handle($multi, $ch);
  207. $handles[$index] = [
  208. 'handle' => $ch,
  209. 'request' => $request,
  210. 'startedAt' => microtime(true),
  211. ];
  212. }
  213. $running = null;
  214. do {
  215. $status = curl_multi_exec($multi, $running);
  216. if ($running) {
  217. $selected = curl_multi_select($multi, 1.0);
  218. if ($selected === -1) {
  219. usleep(1000);
  220. }
  221. }
  222. } while ($running && $status === CURLM_OK);
  223. $responses = [];
  224. foreach ($handles as $item) {
  225. $ch = $item['handle'];
  226. $body = curl_multi_getcontent($ch);
  227. $info = curl_getinfo($ch);
  228. $error = curl_error($ch);
  229. $httpCode = isset($info['http_code']) ? (int)$info['http_code'] : 0;
  230. $totalTime = isset($info['total_time']) ? (float)$info['total_time'] : microtime(true) - $item['startedAt'];
  231. $parsed = parseBusinessResponse($body, $httpCode, $error);
  232. $responses[] = [
  233. 'type' => $item['request']['type'],
  234. 'label' => $item['request']['label'],
  235. 'httpCode' => $httpCode,
  236. 'totalTime' => $totalTime,
  237. 'businessSuccess' => $parsed['success'],
  238. 'summary' => $parsed['summary'],
  239. ];
  240. curl_multi_remove_handle($multi, $ch);
  241. curl_close($ch);
  242. }
  243. curl_multi_close($multi);
  244. return $responses;
  245. }
  246. function parseBusinessResponse($body, $httpCode, $curlError)
  247. {
  248. if ($curlError !== '') {
  249. return ['success' => false, 'summary' => 'curl_error=' . $curlError];
  250. }
  251. $decoded = json_decode($body, true);
  252. if (is_array($decoded)) {
  253. $code = isset($decoded['code']) ? $decoded['code'] : null;
  254. $msg = isset($decoded['msg']) ? $decoded['msg'] : '';
  255. $success = ($httpCode >= 200 && $httpCode < 300 && (string)$code === '1');
  256. return [
  257. 'success' => $success,
  258. 'summary' => 'code=' . json_encode($code, JSON_UNESCAPED_UNICODE) . ' msg=' . trimText((string)$msg, 180),
  259. ];
  260. }
  261. return [
  262. 'success' => false,
  263. 'summary' => trimText(preg_replace('/\s+/', ' ', (string)$body), 240),
  264. ];
  265. }
  266. function countSuccessfulRequests($responses)
  267. {
  268. $counts = ['order' => 0, 'stock-out' => 0];
  269. foreach ($responses as $response) {
  270. if ($response['businessSuccess']) {
  271. $counts[$response['type']]++;
  272. }
  273. }
  274. return $counts;
  275. }
  276. function calcExpectedStocks($before, $requestDefs, $successCounts, $productIds)
  277. {
  278. $expected = $before;
  279. foreach ($successCounts as $type => $count) {
  280. foreach ($productIds as $productId) {
  281. $delta = isset($requestDefs[$type]['stockDelta'][$productId])
  282. ? $requestDefs[$type]['stockDelta'][$productId]
  283. : '0';
  284. if ($count > 0 && bccomp($delta, '0', 2) !== 0) {
  285. $expected[$productId] = bcsub($expected[$productId], bcmul($delta, (string)$count, 2), 2);
  286. }
  287. }
  288. }
  289. return $expected;
  290. }
  291. function stocksMatch($expected, $actual, $productIds)
  292. {
  293. foreach ($productIds as $productId) {
  294. if (bccomp((string)$expected[$productId], (string)$actual[$productId], 2) !== 0) {
  295. return false;
  296. }
  297. }
  298. return true;
  299. }
  300. function printStocks($title, $stocks, $productIds)
  301. {
  302. echo $title . ': ';
  303. $parts = [];
  304. foreach ($productIds as $productId) {
  305. $parts[] = $productId . '=' . $stocks[$productId];
  306. }
  307. echo implode(', ', $parts) . "\n";
  308. }
  309. function printDiff($expected, $actual, $productIds)
  310. {
  311. echo 'Diff(actual - expected): ';
  312. $parts = [];
  313. foreach ($productIds as $productId) {
  314. $parts[] = $productId . '=' . bcsub((string)$actual[$productId], (string)$expected[$productId], 2);
  315. }
  316. echo implode(', ', $parts) . "\n";
  317. }
  318. function trimText($text, $maxLength)
  319. {
  320. $text = trim($text);
  321. if (function_exists('mb_strlen') && function_exists('mb_substr')) {
  322. return mb_strlen($text, 'UTF-8') > $maxLength
  323. ? mb_substr($text, 0, $maxLength, 'UTF-8') . '...'
  324. : $text;
  325. }
  326. return strlen($text) > $maxLength ? substr($text, 0, $maxLength) . '...' : $text;
  327. }
  328. function getFileSize($file)
  329. {
  330. clearstatcache(true, $file);
  331. return is_file($file) ? filesize($file) : 0;
  332. }
  333. function readFileFromOffset($file, $offset)
  334. {
  335. if (!is_file($file)) {
  336. return '';
  337. }
  338. $handle = fopen($file, 'rb');
  339. if (!$handle) {
  340. return '';
  341. }
  342. fseek($handle, $offset);
  343. $content = stream_get_contents($handle);
  344. fclose($handle);
  345. return $content === false ? '' : $content;
  346. }
  347. function findConcurrencyErrors($logContent)
  348. {
  349. if ($logContent === '') {
  350. return [];
  351. }
  352. $patterns = [
  353. 'Deadlock found',
  354. 'Serialization failure',
  355. 'Lock wait timeout exceeded',
  356. ];
  357. $lines = preg_split('/\r\n|\r|\n/', $logContent);
  358. $matched = [];
  359. foreach ($lines as $line) {
  360. foreach ($patterns as $pattern) {
  361. if (strpos($line, $pattern) !== false) {
  362. $matched[] = trimText(trim($line), 240);
  363. break;
  364. }
  365. }
  366. }
  367. return array_values(array_unique(array_filter($matched)));
  368. }