Skip to content

Commit cca746f

Browse files
feat: add system time checker (#314) (#317)
* feat: add system time checker (#314) * fix: code-style
1 parent c9faac5 commit cca746f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
3+
declare (strict_types=1);
4+
5+
namespace Frosh\Tools\Components\Health\Checker\HealthChecker;
6+
7+
use Frosh\Tools\Components\Health\Checker\CheckerInterface;
8+
use Frosh\Tools\Components\Health\HealthCollection;
9+
use Frosh\Tools\Components\Health\SettingsResult;
10+
use GuzzleHttp\Client;
11+
use GuzzleHttp\Exception\GuzzleException;
12+
13+
class SystemTimeChecker implements HealthCheckerInterface, CheckerInterface
14+
{
15+
public function collect(HealthCollection $collection): void
16+
{
17+
$this->checkSystemTime($collection);
18+
}
19+
20+
private function checkSystemTime(HealthCollection $collection): void
21+
{
22+
$url = 'https://cloudflare.com/cdn-cgi/trace';
23+
$snippet = 'System time';
24+
$recommended = 'max 5 seconds';
25+
26+
try {
27+
$response = (new Client())->request('GET', $url);
28+
29+
$data = [];
30+
$lines = explode("\n", trim((string) $response->getBody()));
31+
foreach ($lines as $line) {
32+
if (str_contains($line, '=')) {
33+
[$key, $value] = explode("=", $line, 2);
34+
$data[$key] = $value;
35+
}
36+
}
37+
38+
$cloudflareTimestamp = isset($data['ts']) ? (int) $data['ts'] : null;
39+
if (!$cloudflareTimestamp) {
40+
$status = SettingsResult::info('system-time', $snippet, 'Could not parse remote time', $recommended, $url);
41+
$collection->add($status);
42+
return;
43+
}
44+
45+
$diff = abs(time() - $cloudflareTimestamp);
46+
if ($diff > 5) {
47+
$status = SettingsResult::warning('system-time', $snippet, $diff . ' seconds', $recommended);
48+
} else {
49+
$status = SettingsResult::ok('system-time', $snippet, $diff . ' second(s)', $recommended);
50+
}
51+
} catch (GuzzleException) {
52+
$status = SettingsResult::info('system-time', $snippet, 'Could not fetch remote time', $recommended, $url);
53+
}
54+
55+
$collection->add($status);
56+
}
57+
}

0 commit comments

Comments
 (0)