| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188 |
- <?php
- namespace Tests\Integration;
- use App\Http\Controllers\admin\Withdraw as WithdrawController;
- use App\Models\User;
- use App\Models\Withdraw;
- use App\Services\AdminRealtime\AdminRealtime;
- use App\Services\AdminRealtime\AdminRealtimeFeed;
- use App\Services\AdminRealtime\AdminRealtimeRows;
- use App\Services\AdminRealtime\AdminRealtimeTicket;
- use Carbon\Carbon;
- use Illuminate\Cache\ArrayStore;
- use Illuminate\Cache\Repository as CacheRepository;
- use Illuminate\Config\Repository;
- use Illuminate\Database\Capsule\Manager;
- use Illuminate\Database\DatabaseTransactionsManager;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Events\Dispatcher;
- use Illuminate\Foundation\Application;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Facade;
- use Illuminate\Support\Facades\Schema;
- use Illuminate\Translation\ArrayLoader;
- use Illuminate\Translation\Translator;
- use Illuminate\Validation\Factory;
- use PHPUnit\Framework\TestCase;
- class AdminRealtimeTest extends TestCase
- {
- private Application $app;
- private object $log;
- protected function setUp(): void
- {
- Carbon::setTestNow(Carbon::parse('2026-10-31 10:00:00', 'Asia/Shanghai'));
- Facade::clearResolvedInstances();
- Model::clearBootedModels();
- $this->app = new Application(dirname(__DIR__, 2));
- $this->app->instance('config', new Repository([
- 'app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai'],
- 'admin_realtime' => ['enabled' => true, 'ticket_secret' => 'ticket-secret', 'ticket_ttl' => 60, 'public_url' => 'wss://admin.test/admin-ws', 'batch_size' => 200, 'online_scan_seconds' => 15, 'retention_hours' => 72],
- ]));
- Facade::setFacadeApplication($this->app);
- $events = new Dispatcher($this->app); $this->app->instance('events', $events);
- $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
- $db->setEventDispatcher($events); $db->setAsGlobal(); $db->bootEloquent();
- $db->getConnection()->setTransactionManager(new DatabaseTransactionsManager());
- $this->app->instance('db', $db->getDatabaseManager());
- $this->app->bind('db.schema', fn () => $db->schema());
- $translator = new Translator(new ArrayLoader(), 'zh'); $this->app->instance('translator', $translator);
- $this->app->instance('validator', new Factory($translator, $this->app));
- $this->log = new class {
- public array $records = [];
- public function channel($name = null) { return $this; }
- public function __call($level, $args) { $this->records[] = [$level, $args[0] ?? '']; }
- };
- $this->app->instance('log', $this->log);
- $this->app->instance('cache', new CacheRepository(new ArrayStore()));
- $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
- public function json($data, $status = 200, $headers = [], $options = 0) { return new JsonResponse($data, $status, $headers, $options); }
- });
- Request::macro('validate', function (array $rules) { return app('validator')->make($this->all(), $rules)->validate(); });
- $this->app->instance('request', Request::create('/admin/realtime/events', 'GET'));
- (require dirname(__DIR__, 2) . '/database/migrations/2026_10_31_160000_create_admin_realtime_events.php')->up();
- Schema::create('users', function (Blueprint $t) {
- $t->id(); $t->string('member_id'); $t->string('user_id')->default(''); $t->string('first_name')->default('');
- $t->string('admin_note')->nullable(); $t->string('language')->nullable(); $t->integer('recharge_channel_group_id')->nullable(); $t->timestamps();
- });
- Schema::create('withdraws', function (Blueprint $t) {
- $t->id(); $t->string('member_id'); $t->decimal('amount', 20, 10)->default(0); $t->decimal('service_charge', 20, 10)->default(0);
- $t->decimal('to_account', 20, 10)->default(0); $t->string('address')->default(''); $t->decimal('exchange_rate', 20, 10)->default(0);
- $t->integer('status')->default(0); $t->decimal('after_balance', 20, 10)->default(0); $t->string('remark')->nullable();
- $t->string('admin_note')->nullable(); $t->integer('is_locked')->default(0); $t->integer('is_send')->default(0); $t->timestamps();
- });
- DB::table('users')->insert(['member_id' => '9001', 'user_id' => 'u9001', 'first_name' => 'Alice', 'admin_note' => 'vip']);
- }
- protected function tearDown(): void { Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); }
- private function events(): array
- {
- return DB::table('admin_realtime_events')->orderBy('id')->get()->map(fn ($r) => "{$r->resource}:{$r->resource_id}:{$r->action}")->all();
- }
- public function test_record_waits_for_commit_and_drops_on_rollback(): void
- {
- AdminRealtime::record('withdraws', 1);
- $this->assertSame(['withdraws:1:updated'], $this->events());
- DB::beginTransaction();
- AdminRealtime::record('withdraws', [2, 2, 3], 'created');
- $this->assertCount(1, $this->events(), '事务内不写入');
- DB::commit();
- $this->assertSame(['withdraws:1:updated', 'withdraws:2:created', 'withdraws:3:created'], $this->events());
- DB::beginTransaction();
- AdminRealtime::record('withdraws', 4);
- DB::rollBack();
- $this->assertCount(3, $this->events(), '回滚后丢弃');
- $this->app['config']->set('admin_realtime.enabled', false);
- AdminRealtime::record('withdraws', 5);
- $this->assertCount(3, $this->events(), '关闭时不登记');
- }
- public function test_record_failure_never_breaks_business_transaction(): void
- {
- Schema::drop('admin_realtime_events');
- DB::transaction(function () {
- Withdraw::create(['member_id' => '9001', 'amount' => 10]);
- });
- $this->assertSame(1, Withdraw::count(), '事件表缺失也不影响主业务');
- $this->assertSame('error', $this->log->records[0][0] ?? null);
- }
- public function test_model_hooks_capture_orders_and_new_users_only(): void
- {
- $withdraw = Withdraw::create(['member_id' => '9001', 'amount' => 10]);
- $withdraw->update(['is_send' => 1]);
- $withdraw->update(['status' => 1]);
- $user = User::query()->create(['member_id' => '9002', 'first_name' => 'Bob']);
- $user->first_name = 'Bobby'; $user->save();
- $withdraw->delete();
- $this->assertSame([
- "withdraws:{$withdraw->id}:created", "withdraws:{$withdraw->id}:updated",
- "users:{$user->id}:created", "withdraws:{$withdraw->id}:deleted",
- ], $this->events());
- }
- public function test_feed_resolves_rows_with_the_list_endpoint_shape(): void
- {
- $this->assertSame(['last_id' => 0, 'ids' => [], 'events' => [], 'has_more' => false], AdminRealtimeFeed::pull(-1));
- $withdraw = Withdraw::create(['member_id' => '9001', 'amount' => 12.5, 'to_account' => 12.5]);
- $withdraw->update(['status' => 1]);
- Withdraw::create(['member_id' => '9001', 'amount' => 3]);
- $result = AdminRealtimeFeed::pull(0);
- $this->assertSame(3, $result['last_id']);
- $this->assertSame([1, 2, 3], $result['ids']);
- $this->assertCount(2, $result['events'], '同一记录一批内合并');
- $first = $result['events'][0];
- $this->assertSame(['id' => 2, 'channel' => 'admin.orders.withdraw', 'event' => 'order.created', 'action' => 'created', 'key' => ['id' => 1]],
- array_intersect_key($first, array_flip(['id', 'channel', 'event', 'action', 'key'])));
- $listRequest = Request::create('/admin/withdraw', 'GET');
- $this->app->instance('request', $listRequest);
- $list = (new WithdrawController())->index()->getData(true)['data']['data'];
- $row = collect($list)->firstWhere('id', 1);
- $this->assertSame($row, $first['data'], '推送行与列表接口返回的行一致');
- $this->assertSame('Alice', $first['data']['first_name']);
- $this->assertSame(1, $first['data']['status']);
- $withdraw->delete();
- $deleted = AdminRealtimeFeed::pull(3)['events'];
- $this->assertSame([['channel' => 'admin.orders.withdraw', 'action' => 'deleted', 'key' => ['id' => 1], 'data' => null]],
- array_map(fn ($e) => array_intersect_key($e, array_flip(['channel', 'action', 'key', 'data'])), $deleted));
- $gapped = AdminRealtimeFeed::pull(4, ['2']);
- $this->assertSame([2], $gapped['ids'], '按 gaps 补拉已处理游标之前的事件');
- $this->assertSame(4, $gapped['last_id']);
- $this->assertNotEmpty(array_filter($this->log->records, fn ($r) => $r[1] === 'admin_realtime_online_scan_failed'),
- 'SQLite 不支持在线判定 SQL,扫描失败只记日志不影响拉取');
- }
- public function test_ticket_is_signed_for_gateway_and_lists_channels(): void
- {
- $ticket = AdminRealtimeTicket::issue(1, 1893456000);
- [$body, $sig] = explode('.', $ticket['ticket']);
- $this->assertSame(rtrim(strtr(base64_encode(hash_hmac('sha256', $body, 'ticket-secret', true)), '+/', '-_'), '='), $sig);
- $payload = json_decode(base64_decode(strtr($body, '-_', '+/')), true);
- $this->assertSame(1, $payload['aid']);
- $this->assertSame(1893456000, $payload['sxp']);
- $this->assertSame(array_keys(AdminRealtimeRows::CHANNELS), $payload['ch']);
- $this->assertSame('wss://admin.test/admin-ws', $ticket['url']);
- $node = trim((string) shell_exec('command -v node'));
- if ($node === '') $this->markTestIncomplete('node 不可用,跳过网关签名互通校验');
- $script = "const c=require('crypto');const [b,s]=process.argv[1].split('.');process.stdout.write(String(c.createHmac('sha256','ticket-secret').update(b).digest('base64url')===s))";
- $this->assertSame('true', shell_exec(escapeshellarg($node) . ' -e ' . escapeshellarg($script) . ' ' . escapeshellarg($ticket['ticket'])));
- }
- }
|