AdminRealtimeTest.php 29 KB

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