From f5cc846913f5b8dc665c6149ace63bf301e979ad Mon Sep 17 00:00:00 2001 From: Damodar Lohani Date: Mon, 6 Jul 2026 02:25:17 +0000 Subject: [PATCH] refactor(geo): resolve locale per request in getGeoForIp and drop in-memory cache Swoole workers reuse the singleton getGeoForIp closure across all requests. Capturing the Locale reference at first resolution would lock every subsequent request to the first request's language, and the per-worker $cache grew unbounded for the life of the process. Pass Locale into the closure invocation instead of closing over it, and rely on the per-request geoRecord resource to cache within a request. --- app/init/resources/request.php | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/app/init/resources/request.php b/app/init/resources/request.php index df6ba2c4ec..dcf783e6d4 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -1323,7 +1323,7 @@ return function (Container $context): void { return new Agent($adapter); }, ['register']); - $context->set('geoRecord', function ($request, callable $getGeoForIp) { + $context->set('geoRecord', function ($request, Locale $locale, callable $getGeoForIp) { $ip = $request->getIp(); if (!filter_var($ip, FILTER_VALIDATE_IP)) { @@ -1331,17 +1331,11 @@ return function (Container $context): void { $ip = '0.0.0.0'; } - return $getGeoForIp($ip); - }, ['request', 'getGeoForIp']); - - $context->set('getGeoForIp', function (Locale $locale) { - $cache = []; - - return function (string $ip) use ($locale, &$cache): GeoRecord { - if (isset($cache[$ip])) { - return $cache[$ip]; - } + return $getGeoForIp($locale, $ip); + }, ['request', 'locale', 'getGeoForIp']); + $context->set('getGeoForIp', function () { + return function (Locale $locale, string $ip): GeoRecord { $record = null; $lookupSucceeded = false; $geoEndpoint = System::getEnv('_APP_GEO_ENDPOINT', ''); @@ -1384,7 +1378,7 @@ return function (Container $context): void { $autonomousSystemNumber = $record['autonomousSystemNumber'] ?? null; - $geoRecord = (new GeoRecord([ + return (new GeoRecord([ 'ip' => $ip, 'countryCode' => $countryCode, 'continentCode' => $continentCode, @@ -1404,10 +1398,6 @@ return function (Container $context): void { ])) ->setLocale($locale) ->setLookupSucceeded($lookupSucceeded); - - $cache[$ip] = $geoRecord; - - return $geoRecord; }; - }, ['locale']); + }, []); };