AdminRealtimeTest.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Http\Controllers\admin\Withdraw as WithdrawController;
  4. use App\Models\User;
  5. use App\Models\Withdraw;
  6. use App\Services\AdminRealtime\AdminRealtime;
  7. use App\Services\AdminRealtime\AdminRealtimeFeed;
  8. use App\Services\AdminRealtime\AdminRealtimeRows;
  9. use App\Services\AdminRealtime\AdminRealtimeAccess;
  10. use App\Services\JwtService;
  11. use App\Http\Controllers\admin\Realtime as RealtimeController;
  12. use Illuminate\Broadcasting\BroadcastManager;
  13. use Illuminate\Contracts\Broadcasting\Factory as BroadcastingFactory;
  14. use Carbon\Carbon;
  15. use Illuminate\Cache\ArrayStore;
  16. use Illuminate\Cache\Repository as CacheRepository;
  17. use Illuminate\Config\Repository;
  18. use Illuminate\Database\Capsule\Manager;
  19. use Illuminate\Database\DatabaseTransactionsManager;
  20. use Illuminate\Database\Eloquent\Model;
  21. use Illuminate\Database\Schema\Blueprint;
  22. use Illuminate\Events\Dispatcher;
  23. use Illuminate\Foundation\Application;
  24. use Illuminate\Http\JsonResponse;
  25. use Illuminate\Http\Request;
  26. use Illuminate\Support\Facades\DB;
  27. use Illuminate\Support\Facades\Facade;
  28. use Illuminate\Support\Facades\Schema;
  29. use Illuminate\Translation\ArrayLoader;
  30. use Illuminate\Translation\Translator;
  31. use Illuminate\Validation\Factory;
  32. use PHPUnit\Framework\TestCase;
  33. use Illuminate\Support\Facades\Broadcast;
  34. use Symfony\Component\Console\Tester\CommandTester;
  35. class AdminRealtimeTest extends TestCase
  36. {
  37. private Application $app;
  38. private object $log;
  39. protected function setUp(): void
  40. {
  41. Carbon::setTestNow(Carbon::parse('2026-10-31 10:00:00', 'Asia/Shanghai'));
  42. Facade::clearResolvedInstances();
  43. Model::clearBootedModels();
  44. $this->app = new Application(dirname(__DIR__, 2));
  45. $this->app->instance('config', new Repository([
  46. 'app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai'],
  47. 'admin_realtime' => ['enabled' => true, 'connection' => 'reverb', 'batch_size' => 200, 'gap_seconds' => 60, 'replay_limit' => 1000,
  48. 'permission_cache_seconds' => 60, 'online_scan_seconds' => 15, 'retention_hours' => 72],
  49. ]));
  50. Facade::setFacadeApplication($this->app);
  51. $events = new Dispatcher($this->app); $this->app->instance('events', $events);
  52. $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  53. $db->setEventDispatcher($events); $db->setAsGlobal(); $db->bootEloquent();
  54. $db->getConnection()->setTransactionManager(new DatabaseTransactionsManager());
  55. $this->app->instance('db', $db->getDatabaseManager());
  56. $this->app->bind('db.schema', fn () => $db->schema());
  57. $translator = new Translator(new ArrayLoader(), 'zh'); $this->app->instance('translator', $translator);
  58. $this->app->instance('validator', new Factory($translator, $this->app));
  59. $this->log = new class {
  60. public array $records = [];
  61. public function channel($name = null) { return $this; }
  62. public function __call($level, $args) { $this->records[] = [$level, $args[0] ?? '']; }
  63. };
  64. $this->app->instance('log', $this->log);
  65. $this->app->instance('cache', new CacheRepository(new ArrayStore()));
  66. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Tests\Support\JsonResponseFactory());
  67. Request::macro('validate', function (array $rules) { return app('validator')->make($this->all(), $rules)->validate(); });
  68. $this->app->instance('request', Request::create('/admin/realtime/events', 'GET'));
  69. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_31_160000_create_admin_realtime_events.php')->up();
  70. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_31_210000_add_seq_to_admin_realtime_events.php')->up();
  71. (require dirname(__DIR__, 2) . '/database/migrations/2026_11_01_000000_add_delivery_state_to_admin_realtime_events.php')->up();
  72. Schema::create('users', function (Blueprint $t) {
  73. $t->id(); $t->string('member_id'); $t->string('user_id')->default(''); $t->string('first_name')->default('');
  74. $t->string('admin_note')->nullable(); $t->string('language')->nullable(); $t->integer('recharge_channel_group_id')->nullable(); $t->timestamps();
  75. });
  76. Schema::create('withdraws', function (Blueprint $t) {
  77. $t->id(); $t->string('member_id'); $t->decimal('amount', 20, 10)->default(0); $t->decimal('service_charge', 20, 10)->default(0);
  78. $t->decimal('to_account', 20, 10)->default(0); $t->string('address')->default(''); $t->decimal('exchange_rate', 20, 10)->default(0);
  79. $t->integer('status')->default(0); $t->decimal('after_balance', 20, 10)->default(0); $t->string('remark')->nullable();
  80. $t->string('admin_note')->nullable(); $t->integer('is_locked')->default(0); $t->integer('is_send')->default(0); $t->timestamps();
  81. });
  82. DB::table('users')->insert(['member_id' => '9001', 'user_id' => 'u9001', 'first_name' => 'Alice', 'admin_note' => 'vip']);
  83. }
  84. protected function tearDown(): void { Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); }
  85. private function events(): array
  86. {
  87. return DB::table('admin_realtime_events')->orderBy('id')->get()->map(fn ($r) => "{$r->resource}:{$r->resource_id}:{$r->action}")->all();
  88. }
  89. private function consume(int $cursor): array
  90. {
  91. $batch = AdminRealtimeFeed::next($cursor);
  92. AdminRealtimeFeed::acknowledge($batch['ids']);
  93. return $batch;
  94. }
  95. public function test_record_waits_for_commit_and_drops_on_rollback(): void
  96. {
  97. AdminRealtime::record('withdraws', 1);
  98. $this->assertSame(['withdraws:1:updated'], $this->events());
  99. DB::beginTransaction();
  100. AdminRealtime::record('withdraws', [2, 2, 3], 'created');
  101. $this->assertCount(1, $this->events(), '事务内不写入');
  102. DB::commit();
  103. $this->assertSame(['withdraws:1:updated', 'withdraws:2:created', 'withdraws:3:created'], $this->events());
  104. DB::beginTransaction();
  105. AdminRealtime::record('withdraws', 4);
  106. DB::rollBack();
  107. $this->assertCount(3, $this->events(), '回滚后丢弃');
  108. $this->app['config']->set('admin_realtime.enabled', false);
  109. AdminRealtime::record('withdraws', 5);
  110. $this->assertCount(3, $this->events(), '关闭时不登记');
  111. }
  112. public function test_record_failure_never_breaks_business_transaction(): void
  113. {
  114. Schema::drop('admin_realtime_events');
  115. DB::transaction(function () {
  116. Withdraw::create(['member_id' => '9001', 'amount' => 10]);
  117. });
  118. $this->assertSame(1, Withdraw::count(), '事件表缺失也不影响主业务');
  119. $this->assertSame('error', $this->log->records[0][0] ?? null);
  120. }
  121. public function test_model_hooks_capture_orders_and_new_users_only(): void
  122. {
  123. $withdraw = Withdraw::create(['member_id' => '9001', 'amount' => 10]);
  124. $withdraw->update(['is_send' => 1]);
  125. $withdraw->update(['status' => 1]);
  126. $user = User::query()->create(['member_id' => '9002', 'first_name' => 'Bob']);
  127. $user->first_name = 'Bobby'; $user->save();
  128. $withdraw->delete();
  129. $this->assertSame([
  130. "withdraws:{$withdraw->id}:created", "withdraws:{$withdraw->id}:updated",
  131. "users:{$user->id}:created", "withdraws:{$withdraw->id}:deleted",
  132. ], $this->events());
  133. }
  134. public function test_feed_resolves_rows_with_the_list_endpoint_shape(): void
  135. {
  136. $this->assertSame(0, AdminRealtimeFeed::startCursor());
  137. $this->assertSame(['cursor' => 0, 'ids' => [], 'events' => [], 'has_more' => false], $this->consume(0));
  138. $withdraw = Withdraw::create(['member_id' => '9001', 'amount' => 12.5, 'to_account' => 12.5]);
  139. $withdraw->update(['status' => 1]);
  140. Withdraw::create(['member_id' => '9001', 'amount' => 3]);
  141. $result = $this->consume(0);
  142. $this->assertSame(3, $result['cursor']);
  143. $this->assertSame([1, 2, 3], DB::table('admin_realtime_events')->orderBy('id')->pluck('seq')->map(fn ($v) => (int) $v)->all());
  144. $this->assertCount(2, $result['events'], '同一记录一批内合并');
  145. $first = $result['events'][0];
  146. $this->assertSame(['seq' => 2, 'id' => 2, 'channel' => 'admin.orders.withdraw', 'event' => 'order.created', 'action' => 'created', 'key' => ['id' => 1]],
  147. array_intersect_key($first, array_flip(['seq', 'id', 'channel', 'event', 'action', 'key'])));
  148. $listRequest = Request::create('/admin/withdraw', 'GET');
  149. $this->app->instance('request', $listRequest);
  150. $list = (new WithdrawController())->index()->getData(true)['data']['data'];
  151. $row = collect($list)->firstWhere('id', 1);
  152. $this->assertSame($row, $first['data'], '推送行与列表接口返回的行一致');
  153. $this->assertSame('Alice', $first['data']['first_name']);
  154. $this->assertSame(1, $first['data']['status']);
  155. $withdraw->delete();
  156. $deleted = $this->consume(3)['events'];
  157. $this->assertSame([['seq' => 4, 'channel' => 'admin.orders.withdraw', 'action' => 'deleted', 'key' => ['id' => 1], 'data' => null]],
  158. array_map(fn ($e) => array_intersect_key($e, array_flip(['seq', 'channel', 'action', 'key', 'data'])), $deleted));
  159. $this->assertSame(4, AdminRealtimeFeed::startCursor(), '重启后从上次广播到的 id 继续');
  160. $this->assertNotEmpty(array_filter($this->log->records, fn ($r) => $r[1] === 'admin_realtime_online_scan_failed'),
  161. 'SQLite 不支持在线判定 SQL,扫描失败只记日志不影响广播');
  162. }
  163. public function test_feed_delivers_late_commits_with_a_later_seq(): void
  164. {
  165. $insert = fn (int $id, string $at) => DB::table('admin_realtime_events')->insert([
  166. 'id' => $id, 'resource' => 'withdraws', 'resource_id' => (string) $id, 'action' => 'deleted', 'source' => 'melbet', 'created_at' => $at,
  167. ]);
  168. $insert(1, '2026-10-31 09:59:59');
  169. $insert(3, '2026-10-31 09:59:59');
  170. $this->assertSame([1, 3], array_column($this->consume(0)['events'], 'id'));
  171. $insert(2, '2026-10-31 09:59:30');
  172. $insert(4, '2026-10-31 09:58:00');
  173. $insert(5, '2026-10-31 09:58:00');
  174. $batch = $this->consume(3);
  175. $this->assertSame([[3, 2], [4, 4], [5, 5]], array_map(fn ($e) => [$e['seq'], $e['id']], $batch['events']),
  176. '游标之前晚提交的 id 仍会广播,seq 按广播先后递增');
  177. $this->assertSame(5, $batch['cursor']);
  178. $insert(6, '2026-10-31 10:00:00');
  179. $insert(7, '2026-10-31 10:00:00');
  180. DB::table('admin_realtime_events')->where('id', 6)->delete();
  181. $this->consume(5);
  182. $insert(6, '2026-10-31 09:58:00');
  183. $this->assertSame([], $this->consume(7)['events'], '超过 gap_seconds 的晚提交不再补发');
  184. }
  185. public function test_replay_by_seq_filters_channels_and_requests_resync(): void
  186. {
  187. $withdraw = Withdraw::create(['member_id' => '9001', 'amount' => 1]);
  188. Withdraw::create(['member_id' => '9001', 'amount' => 2]);
  189. AdminRealtime::record('sport_order', 99, 'deleted');
  190. $withdraw->delete();
  191. $this->consume(0);
  192. $this->assertSame(4, AdminRealtimeFeed::lastSeq());
  193. $replay = AdminRealtimeFeed::replay(1, ['admin.orders.withdraw']);
  194. $this->assertFalse($replay['resync']);
  195. $this->assertSame(4, $replay['last_seq']);
  196. $this->assertSame([[2, 'order.created'], [4, 'order.deleted']], array_map(fn ($e) => [$e['seq'], $e['event']], $replay['events']),
  197. '只返回请求的频道,并按当前数据解析');
  198. $this->assertSame([], AdminRealtimeFeed::replay(4, ['admin.orders.withdraw'])['events']);
  199. $this->assertSame('invalid_cursor', AdminRealtimeFeed::replay(9, ['admin.orders.withdraw'])['reason']);
  200. $this->app['config']->set('admin_realtime.replay_limit', 2);
  201. $this->assertSame('too_many_events', AdminRealtimeFeed::replay(0, ['admin.orders.withdraw'])['reason']);
  202. DB::table('admin_realtime_events')->where('seq', 1)->delete();
  203. $this->assertSame('history_unavailable', AdminRealtimeFeed::replay(1, ['admin.orders.withdraw'])['reason'], '游标已被清理时重新拉列表');
  204. }
  205. public function test_channel_auth_signs_session_user_for_reverb(): void
  206. {
  207. $this->bindBroadcasting();
  208. Schema::create('admin', function (Blueprint $t) { $t->id(); $t->string('username'); $t->timestamps(); });
  209. DB::table('admin')->insert(['id' => 1, 'username' => 'root']);
  210. $exp = time() + 3600;
  211. $token = \Firebase\JWT\JWT::encode(['iat' => time(), 'exp' => $exp, 'sub' => 1, 'user_id' => 1], str_repeat('k', 32), 'HS256');
  212. $call = function (?string $token, string $channel) {
  213. $request = Request::create('/admin/broadcasting/auth', 'POST', ['socket_id' => '123.456', 'channel_name' => $channel]);
  214. if ($token) $request->headers->set('Authorization', 'Bearer ' . $token);
  215. $this->app->instance('request', $request);
  216. return (new RealtimeController())->auth(new JwtService());
  217. };
  218. $response = $call($token, 'private-admin.orders.withdraw');
  219. $this->assertSame(200, $response->getStatusCode());
  220. $body = $response->getData(true);
  221. $this->assertSame(['user_id' => "1:{$exp}"], json_decode($body['channel_data'], true));
  222. // 与 Reverb 校验私有频道的签名算法一致(InteractsWithPrivateChannels::verify)
  223. $this->assertSame('app-key:' . hash_hmac('sha256', "123.456:private-admin.orders.withdraw:{$body['channel_data']}", 'app-secret'), $body['auth']);
  224. $this->assertSame(401, $call(null, 'private-admin.orders.withdraw')->getStatusCode());
  225. $this->assertSame(401, $call($token . 'x', 'private-admin.orders.withdraw')->getStatusCode());
  226. $this->assertSame(403, $call($token, 'private-admin.orders.unknown')->getStatusCode());
  227. $this->assertSame(403, $call($token, 'admin.orders.withdraw')->getStatusCode(), '只授权私有频道');
  228. $this->assertSame(array_keys(AdminRealtimeRows::CHANNELS), AdminRealtimeAccess::allowedChannels(1));
  229. DB::table('admin')->insert(['id' => 2, 'username' => 'limited']);
  230. $this->app['cache']->put('admin_realtime:channels:2', ['admin.users'], 60);
  231. $limited = \Firebase\JWT\JWT::encode(['iat' => time(), 'exp' => $exp, 'sub' => 2, 'user_id' => 2], str_repeat('k', 32), 'HS256');
  232. foreach (['admin.stats.platform_count', 'admin.stats.unprocessed'] as $statsChannel) {
  233. $this->assertSame(200, $call($token, 'private-' . $statsChannel)->getStatusCode());
  234. $this->assertSame(403, $call($limited, 'private-' . $statsChannel)->getStatusCode(), '统计频道也必须校验管理员权限');
  235. }
  236. }
  237. public function test_failed_termination_retries_without_affecting_a_newer_login(): void
  238. {
  239. $pusher = $this->fakePusher();
  240. $expired = time() - 10;
  241. $future = time() + 600;
  242. AdminRealtimeAccess::authorize(7, $expired, 'private-admin.orders.withdraw', '1.1');
  243. AdminRealtimeAccess::authorize(7, $expired, 'private-admin.users', '1.1');
  244. AdminRealtimeAccess::authorize(7, $future, 'private-admin.users', '2.2');
  245. $pusher->fail = true;
  246. $this->assertSame([], AdminRealtimeAccess::terminateExpiredSessions());
  247. $this->assertArrayHasKey("7:{$expired}", $this->app['cache']->get('admin_realtime:sessions'));
  248. $pusher->fail = false;
  249. // 模拟发出 HTTP 请求期间有另一个管理员完成授权;合并清理不能覆盖它。
  250. $pusher->onTerminate = static fn() => AdminRealtimeAccess::authorize(8, $future, 'private-admin.users', '3.3');
  251. $this->assertSame(["7:{$expired}"], AdminRealtimeAccess::terminateExpiredSessions());
  252. $this->assertSame([], AdminRealtimeAccess::terminateExpiredSessions(), '已断开的会话不重复处理');
  253. $this->assertSame(["7:{$expired}", "7:{$expired}"], $pusher->attempts);
  254. $this->assertSame(["7:{$future}" => $future, "8:{$future}" => $future], $this->app['cache']->get('admin_realtime:sessions'));
  255. $this->assertNotEmpty(array_filter($this->log->records, fn ($r) => $r[1] === 'admin_realtime_terminate_failed'),
  256. 'Reverb 不可达时只记日志');
  257. }
  258. public function test_session_registration_failure_denies_channel_authorization(): void
  259. {
  260. $this->fakePusher();
  261. $this->app->instance('cache', new CacheRepository(new class extends ArrayStore {
  262. public function forever($key, $value) { return false; }
  263. }));
  264. Facade::clearResolvedInstance('cache');
  265. $this->expectException(\RuntimeException::class);
  266. $this->expectExceptionMessage('登记后台推送会话失败');
  267. AdminRealtimeAccess::authorize(7, time() + 600, 'private-admin.users', '1.1');
  268. }
  269. public function test_session_without_expiry_cannot_be_authorized(): void
  270. {
  271. $this->fakePusher();
  272. $this->expectException(\RuntimeException::class);
  273. AdminRealtimeAccess::authorize(7, null, 'private-admin.users', '1.1');
  274. }
  275. public function test_delayed_expired_subscription_is_rejected_using_verified_metadata(): void
  276. {
  277. $connection = $this->reverbConnection();
  278. $application = $connection->app();
  279. $subscription = new \Laravel\Reverb\Protocols\Pusher\Channels\ChannelConnection($connection, ['user_id' => '7:' . (time() - 10)]);
  280. $channel = $this->createMock(\Laravel\Reverb\Protocols\Pusher\Channels\Channel::class);
  281. $channel->method('find')->with($connection)->willReturn($subscription);
  282. $manager = $this->createMock(\Laravel\Reverb\Protocols\Pusher\Contracts\ChannelManager::class);
  283. $manager->method('for')->with($application)->willReturnSelf();
  284. $manager->method('find')->with('private-admin.users')->willReturn($channel);
  285. $this->app->instance(\Laravel\Reverb\Protocols\Pusher\Contracts\ChannelManager::class, $manager);
  286. $listener = new \App\Listeners\RejectExpiredAdminRealtimeSubscription();
  287. // 客户端伪造的未来时间不能替代 Reverb 已验签的过期订阅数据。
  288. $listener->handle(new \Laravel\Reverb\Events\MessageReceived($connection, json_encode([
  289. 'event' => 'pusher:subscribe', 'data' => ['channel' => 'private-admin.users', 'channel_data' => json_encode(['user_id' => '7:' . (time() + 600)])],
  290. ])));
  291. $this->assertSame(1, $connection->disconnects);
  292. }
  293. public function test_valid_subscription_remains_connected(): void
  294. {
  295. $connection = $this->reverbConnection();
  296. $subscription = new \Laravel\Reverb\Protocols\Pusher\Channels\ChannelConnection($connection, ['user_id' => '7:' . (time() + 600)]);
  297. $channel = $this->createStub(\Laravel\Reverb\Protocols\Pusher\Channels\Channel::class);
  298. $channel->method('find')->willReturn($subscription);
  299. $manager = $this->createStub(\Laravel\Reverb\Protocols\Pusher\Contracts\ChannelManager::class);
  300. $manager->method('for')->willReturnSelf();
  301. $manager->method('find')->willReturn($channel);
  302. $this->app->instance(\Laravel\Reverb\Protocols\Pusher\Contracts\ChannelManager::class, $manager);
  303. (new \App\Listeners\RejectExpiredAdminRealtimeSubscription())->handle(new \Laravel\Reverb\Events\MessageReceived($connection,
  304. json_encode(['event' => 'pusher:subscribe', 'data' => json_encode(['channel' => 'private-admin.users'])])));
  305. $this->assertSame(0, $connection->disconnects);
  306. }
  307. public function test_mixed_session_identities_cannot_hide_an_expiring_channel_on_the_same_socket(): void
  308. {
  309. $this->app->bind(\Laravel\Reverb\Protocols\Pusher\Contracts\ChannelConnectionManager::class,
  310. \Laravel\Reverb\Protocols\Pusher\Managers\ArrayChannelConnectionManager::class);
  311. $manager = new \Laravel\Reverb\Protocols\Pusher\Managers\ArrayChannelManager();
  312. $this->app->instance(\Laravel\Reverb\Protocols\Pusher\Contracts\ChannelManager::class, $manager);
  313. $mixed = $this->reverbConnection('1.1');
  314. $newer = $this->reverbConnection('2.2');
  315. $later = time() + 600;
  316. $earlier = time() + 60;
  317. $subscribe = function ($connection, string $name, int $expires) use ($manager): void {
  318. $data = json_encode(['user_id' => "7:{$expires}"]);
  319. $auth = 'key:' . hash_hmac('sha256', "{$connection->id()}:{$name}:{$data}", 'secret');
  320. $manager->for($connection->app())->findOrCreate($name)->subscribe($connection, $auth, $data);
  321. (new \App\Listeners\RejectExpiredAdminRealtimeSubscription())->handle(new \Laravel\Reverb\Events\MessageReceived($connection,
  322. json_encode(['event' => 'pusher:subscribe', 'data' => ['channel' => $name]])));
  323. };
  324. $subscribe($mixed, 'private-admin.users', $later);
  325. $subscribe($mixed, 'private-admin.orders.withdraw', $earlier);
  326. $this->assertSame("7:{$later}", $manager->connections()['1.1']->data('user_id'), '真实 Reverb 管理器只保留首个 user_id');
  327. $this->assertSame(1, $mixed->disconnects, '不同到期时间不能共用同一 socket');
  328. $subscribe($newer, 'private-admin.users', $later);
  329. $subscribe($newer, 'private-admin.orders.withdraw', $later);
  330. $this->assertSame(0, $newer->disconnects, '独立的新登录及同一会话的多个频道保持有效');
  331. }
  332. private function reverbConnection(string $id = '1.1'): \Laravel\Reverb\Contracts\Connection
  333. {
  334. return new class($id) extends \Laravel\Reverb\Contracts\Connection {
  335. public int $disconnects = 0;
  336. public function __construct(private string $socketId) { $this->application = new \Laravel\Reverb\Application('app', 'key', 'secret', 60, 30, ['*'], 10000); }
  337. public function identifier(): string { return $this->socketId; }
  338. public function id(): string { return $this->socketId; }
  339. public function send(string $message): void {}
  340. public function control(string $type = '9'): void {}
  341. public function terminate(): void { $this->disconnects++; }
  342. };
  343. }
  344. public function test_broadcast_failure_is_retried_in_order_after_relay_restart(): void
  345. {
  346. $broadcaster = new class {
  347. public bool $fail = true;
  348. public array $attempts = [];
  349. public function queue($event) {
  350. $this->attempts[] = $event->message['seq'];
  351. if ($this->fail && $event->message['seq'] === 2) throw new \RuntimeException('temporary publish failure');
  352. }
  353. };
  354. Broadcast::swap($broadcaster);
  355. AdminRealtime::record('withdraws', [77, 88, 99], 'deleted');
  356. $run = function (): int {
  357. $command = new \App\Console\Commands\RelayAdminRealtimeEvents();
  358. $command->setLaravel($this->app);
  359. // 隔离测试不启动 ConsoleKernel,只验证命令投递状态;不注册进程信号。
  360. $previous = (new \ReflectionProperty(\Illuminate\Console\Signals::class, 'availabilityResolver'))->getValue();
  361. \Illuminate\Console\Signals::resolveAvailabilityUsing(static fn() => false);
  362. try {
  363. return (new CommandTester($command))->execute(['--once' => true]);
  364. } finally {
  365. \Illuminate\Console\Signals::resolveAvailabilityUsing($previous);
  366. }
  367. };
  368. $this->assertSame(1, $run());
  369. $this->assertSame([1, 2], $broadcaster->attempts, '失败后不能发送更大的 seq');
  370. $this->assertSame(3, DB::table('admin_realtime_events')->whereNull('published_at')->count());
  371. $broadcaster->fail = false;
  372. $this->assertSame(0, $run());
  373. $this->assertSame([1, 2, 1, 2, 3], $broadcaster->attempts, '新进程恢复未确认批次,允许重复但不丢失');
  374. $this->assertSame(0, DB::table('admin_realtime_events')->whereNull('published_at')->count());
  375. $this->assertSame(0, $run());
  376. $this->assertSame([1, 2, 1, 2, 3], $broadcaster->attempts);
  377. }
  378. public function test_pruning_all_history_never_reuses_seq_and_keeps_pending_delivery(): void
  379. {
  380. AdminRealtime::record('withdraws', 77, 'deleted');
  381. $first = $this->consume(0);
  382. DB::table('admin_realtime_events')->update(['created_at' => '2026-10-27 00:00:00']);
  383. $this->assertSame(1, AdminRealtimeFeed::prune());
  384. $this->assertSame(1, AdminRealtimeFeed::lastSeq());
  385. AdminRealtime::record('withdraws', 88, 'deleted');
  386. $second = AdminRealtimeFeed::next(AdminRealtimeFeed::startCursor());
  387. $this->assertSame(2, $second['events'][0]['seq']);
  388. $this->assertSame('history_unavailable', AdminRealtimeFeed::replay($first['events'][0]['seq'], ['admin.orders.withdraw'])['reason']);
  389. DB::table('admin_realtime_events')->update(['created_at' => '2026-10-27 00:00:00']);
  390. $this->assertSame(0, AdminRealtimeFeed::prune(), '待发送批次即使超期也不能清理');
  391. $retry = AdminRealtimeFeed::next(AdminRealtimeFeed::startCursor());
  392. $this->assertSame($second['ids'], $retry['ids']);
  393. $this->assertSame(array_column($second['events'], 'seq'), array_column($retry['events'], 'seq'));
  394. AdminRealtimeFeed::acknowledge($second['ids']);
  395. $this->assertSame(1, AdminRealtimeFeed::prune());
  396. $this->assertSame(2, AdminRealtimeFeed::lastSeq());
  397. }
  398. private function fakePusher(): \Pusher\Pusher
  399. {
  400. $pusher = new class('app-key', 'app-secret', 'app-id', ['host' => '127.0.0.1', 'port' => 1, 'scheme' => 'http', 'useTLS' => false]) extends \Pusher\Pusher {
  401. public bool $fail = false;
  402. public array $attempts = [];
  403. public $onTerminate = null;
  404. public function terminateUserConnections(string $user_id): object {
  405. $this->attempts[] = $user_id;
  406. if ($this->fail) throw new \RuntimeException('temporary termination failure');
  407. if ($this->onTerminate) ($this->onTerminate)();
  408. return (object) [];
  409. }
  410. };
  411. Broadcast::swap(new class($pusher) {
  412. public function __construct(private $pusher) {}
  413. public function connection($name) { return $this; }
  414. public function getPusher() { return $this->pusher; }
  415. });
  416. return $pusher;
  417. }
  418. private function bindBroadcasting(): void
  419. {
  420. $this->app['config']->set('broadcasting.connections.reverb', [
  421. 'driver' => 'reverb', 'key' => 'app-key', 'secret' => 'app-secret', 'app_id' => 'app-id',
  422. 'options' => ['host' => '127.0.0.1', 'port' => 1, 'scheme' => 'http', 'useTLS' => false],
  423. 'client_options' => ['connect_timeout' => 1, 'timeout' => 1],
  424. ]);
  425. $this->app['config']->set('app.jwt_secret', str_repeat('k', 32));
  426. $this->app['config']->set('app.jwt_exp', 3600);
  427. $this->app->instance(BroadcastingFactory::class, new BroadcastManager($this->app));
  428. }
  429. }