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 <cursoragent@cursor.com>
This commit is contained in:
@@ -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<int, Device> $devices
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user