mirror of
https://github.com/coollabsio/coolify.git
synced 2026-11-04 10:42:23 +00:00
feat(traffic): cache Sentinel traffic responses for 60s
This commit is contained in:
2 files changed
+42
-1
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user