Skip to content

Commit

Permalink
feat: add system time checker (#314) (#317)
Browse files Browse the repository at this point in the history
* feat: add system time checker (#314)

* fix: code-style
  • Loading branch information
MelvinAchterhuis authored Mar 1, 2025
1 parent c9faac5 commit cca746f
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/Components/Health/Checker/HealthChecker/SystemTimeChecker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare (strict_types=1);

namespace Frosh\Tools\Components\Health\Checker\HealthChecker;

use Frosh\Tools\Components\Health\Checker\CheckerInterface;
use Frosh\Tools\Components\Health\HealthCollection;
use Frosh\Tools\Components\Health\SettingsResult;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class SystemTimeChecker implements HealthCheckerInterface, CheckerInterface
{
public function collect(HealthCollection $collection): void
{
$this->checkSystemTime($collection);
}

private function checkSystemTime(HealthCollection $collection): void
{
$url = 'https://cloudflare.com/cdn-cgi/trace';
$snippet = 'System time';
$recommended = 'max 5 seconds';

try {
$response = (new Client())->request('GET', $url);

$data = [];
$lines = explode("\n", trim((string) $response->getBody()));
foreach ($lines as $line) {
if (str_contains($line, '=')) {
[$key, $value] = explode("=", $line, 2);
$data[$key] = $value;
}
}

$cloudflareTimestamp = isset($data['ts']) ? (int) $data['ts'] : null;
if (!$cloudflareTimestamp) {
$status = SettingsResult::info('system-time', $snippet, 'Could not parse remote time', $recommended, $url);
$collection->add($status);
return;
}

$diff = abs(time() - $cloudflareTimestamp);
if ($diff > 5) {
$status = SettingsResult::warning('system-time', $snippet, $diff . ' seconds', $recommended);
} else {
$status = SettingsResult::ok('system-time', $snippet, $diff . ' second(s)', $recommended);
}
} catch (GuzzleException) {
$status = SettingsResult::info('system-time', $snippet, 'Could not fetch remote time', $recommended, $url);
}

$collection->add($status);
}
}

0 comments on commit cca746f

Please sign in to comment.