Cache agent metrics for polling
This commit is contained in:
@@ -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', []));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user