From 9100d5b031de9f2ab5017d2d4d863c0cce6ed1a4 Mon Sep 17 00:00:00 2001 From: root Date: Sat, 31 Jan 2026 17:35:19 +0200 Subject: [PATCH] Cache agent metrics for polling --- app/Services/Agent/AgentClient.php | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/app/Services/Agent/AgentClient.php b/app/Services/Agent/AgentClient.php index 23e54f3..ac1bf69 100644 --- a/app/Services/Agent/AgentClient.php +++ b/app/Services/Agent/AgentClient.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Services\Agent; use Exception; +use Illuminate\Support\Facades\Cache; class AgentClient { @@ -66,6 +67,20 @@ class AgentClient return $decoded; } + /** + * Cache lightweight metrics to reduce socket churn on polling pages. + */ + private function cachedMetrics(string $key, int $seconds, callable $callback): array + { + if ($seconds <= 0) { + return $callback(); + } + + return Cache::remember($key, now()->addSeconds($seconds), function () use ($callback): array { + return $callback(); + }); + } + /** * Recursively sanitize array values to ensure they are JSON-safe. * Removes control characters (except newlines/tabs) from strings. @@ -1089,7 +1104,7 @@ class AgentClient */ public function metricsOverview(): array { - return $this->send('metrics.overview', []); + return $this->cachedMetrics('agent.metrics.overview', 5, fn (): array => $this->send('metrics.overview', [])); } /** @@ -1097,7 +1112,7 @@ class AgentClient */ public function metricsCpu(): array { - return $this->send('metrics.cpu', []); + return $this->cachedMetrics('agent.metrics.cpu', 5, fn (): array => $this->send('metrics.cpu', [])); } /** @@ -1105,7 +1120,7 @@ class AgentClient */ public function metricsMemory(): array { - return $this->send('metrics.memory', []); + return $this->cachedMetrics('agent.metrics.memory', 5, fn (): array => $this->send('metrics.memory', [])); } /** @@ -1113,7 +1128,7 @@ class AgentClient */ public function metricsDisk(): array { - return $this->send('metrics.disk', []); + return $this->cachedMetrics('agent.metrics.disk', 10, fn (): array => $this->send('metrics.disk', [])); } /** @@ -1121,7 +1136,7 @@ class AgentClient */ public function metricsNetwork(): array { - return $this->send('metrics.network', []); + return $this->cachedMetrics('agent.metrics.network', 5, fn (): array => $this->send('metrics.network', [])); } /**