Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

feat(traffic): cache Sentinel traffic responses for 60s

Aditya Tripathi9ad210c7b0b7
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 @@
+<?php
+
+use App\Models\Server;
+use App\Models\Team;
+use App\Services\SentinelTrafficClient;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Cache;
+
+uses(RefreshDatabase::class);
+
+class CountingTrafficClient extends SentinelTrafficClient
+{
+ public int $calls = 0;
+
+ protected function remoteFetch(string $url): string
+ {
+ $this->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);
+});