From e2d01abe289a8dd16827d971c3ec6a0d9fa23e03 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 1 Oct 2026 04:46:59 +0000 Subject: [PATCH] perf: remove slow visitCountriesFor query from device list - visitCountriesFor queried page_visits (5.5M rows, 1.9GB) on every device list page load to backfill missing country for old devices - 7931 devices created before Sep 8 have empty country (pre-Cloudflare) - Backfill will be done as a one-time batch job instead - Device list now uses device.country directly, shows empty if null Co-authored-by: Cursor --- .../Controllers/Admin/DeviceController.php | 41 +------------------ 1 file changed, 2 insertions(+), 39 deletions(-) diff --git a/app/Http/Controllers/Admin/DeviceController.php b/app/Http/Controllers/Admin/DeviceController.php index 640ffa4..7367328 100644 --- a/app/Http/Controllers/Admin/DeviceController.php +++ b/app/Http/Controllers/Admin/DeviceController.php @@ -68,10 +68,8 @@ class DeviceController extends Controller $portal = $this->portal(); $items = collect($paginator->items()); - $visitCountries = $this->visitCountriesFor($items); - $data = $items->map(function (Device $d) use ($portal, $visitCountries) { - $country = CfIpCountry::normalize($d->country) - ?? CfIpCountry::normalize($visitCountries[trim((string) $d->ip)] ?? null); + $data = $items->map(function (Device $d) use ($portal) { + $country = CfIpCountry::normalize($d->country); return [ 'id' => $d->id, @@ -1022,39 +1020,4 @@ class DeviceController extends Controller 'msg' => '队列顺序已更新', ]); } - - /** - * Latest visit country per IP for devices that have no country of their own. - * - * @param Collection $devices - * @return array - */ - private function visitCountriesFor(Collection $devices): array - { - $ips = $devices - ->filter(fn (Device $d) => CfIpCountry::normalize($d->country) === null) - ->map(fn (Device $d) => trim((string) $d->ip)) - ->filter() - ->unique() - ->values(); - if ($ips->isEmpty()) { - return []; - } - - $latestIds = PageVisit::query() - ->selectRaw('MAX(id) as id') - ->whereIn('ip', $ips) - ->whereNotNull('country') - ->where('country', '!=', '') - ->groupBy('ip') - ->pluck('id'); - if ($latestIds->isEmpty()) { - return []; - } - - return PageVisit::query() - ->whereIn('id', $latestIds) - ->pluck('country', 'ip') - ->all(); - } }