From 9ad210c7b0b7a4c21023e353202371ef283ebf4e Mon Sep 17 00:00:00 2001 From: Aditya Tripathi Date: Mon, 10 Aug 2026 19:58:13 +0000 Subject: [PATCH] feat(traffic): cache Sentinel traffic responses for 60s --- app/Services/SentinelTrafficClient.php | 12 ++++++- .../SentinelTrafficCacheTest.php | 31 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 tests/Feature/TrafficAnalytics/SentinelTrafficCacheTest.php diff --git a/app/Services/SentinelTrafficClient.php b/app/Services/SentinelTrafficClient.php index 91209756f2..0bceaae747 100644 --- a/app/Services/SentinelTrafficClient.php +++ b/app/Services/SentinelTrafficClient.php @@ -7,6 +7,7 @@ use App\Data\Traffic\TrafficOverviewData; use App\Data\Traffic\TrafficPathData; use App\Models\Server; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Cache; class SentinelTrafficClient { @@ -62,14 +63,23 @@ class SentinelTrafficClient } protected function raw(string $url): string + { + return Cache::remember('traffic:'.$this->server->uuid.':'.md5($url), 60, fn () => $this->guard($this->remoteFetch($url))); + } + + protected function remoteFetch(string $url): string { $token = $this->server->settings->ensureValidSentinelToken(); - $response = instant_remote_process( + + return instant_remote_process( ["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$token}\" {$url}'"], $this->server, false ); + } + private function guard(string $response): string + { if (str($response)->contains('"error"')) { $error = data_get(json_decode($response, true), 'error', 'Traffic analytics request failed.'); throw new \Exception($error); diff --git a/tests/Feature/TrafficAnalytics/SentinelTrafficCacheTest.php b/tests/Feature/TrafficAnalytics/SentinelTrafficCacheTest.php new file mode 100644 index 0000000000..1eb0329c99 --- /dev/null +++ b/tests/Feature/TrafficAnalytics/SentinelTrafficCacheTest.php @@ -0,0 +1,31 @@ +calls++; + + return '{"requests":0}'; + } +} + +it('caches identical requests within the TTL', function () { + Cache::flush(); + $team = Team::factory()->create(); + $server = Server::factory()->create(['team_id' => $team->id]); + $client = new CountingTrafficClient($server); + $client->overview('app', 'a', 'b'); + $client->overview('app', 'a', 'b'); + expect($client->calls)->toBe(1); +});