Skip to content

Commit

Permalink
πŸš€ Feature - added caching to uptime report
Browse files Browse the repository at this point in the history
  • Loading branch information
Owen Melbourne committed Oct 8, 2019
1 parent 2d3811c commit 3ffae39
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 12 deletions.
6 changes: 6 additions & 0 deletions app/Checkers/Uptime.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function run()
{
$this->fetch();
$this->notify();
$this->cache();
}

private function fetch()
Expand Down Expand Up @@ -86,4 +87,9 @@ private function notify()
);
}
}

private function cache()
{
$this->website->generateUptimeReport(true);
}
}
29 changes: 28 additions & 1 deletion app/HasUptime.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,34 @@ trait HasUptime
{
public function uptimes()
{
return $this->hasMany(UptimeScan::class)->orderBy('created_at', 'desc');
return $this->hasMany(UptimeScan::class)
->where('created_at', '<', now()->addDays(31))
->orderBy('created_at', 'desc');
}

public function generateUptimeReport($refreshCache = false)
{
if ($refreshCache) {
cache()->forget($this->cache_key);
$this->load(['uptimes']);
}

return cache()->rememberForever($this->cache_key, function () {
return [
'uptime' => $this->uptime_summary,
'response_time' => $this->response_time,
'response_times' => $this->response_times,
'online' => $this->current_state,
'online_time' => $this->uptime,
'last_incident' => $this->last_incident,
'events' => $this->recent_events,
];
});
}

public function getCacheKeyAttribute()
{
return 'uptime_' . $this->getKey();
}

public function getLastIncidentAttribute()
Expand Down
14 changes: 3 additions & 11 deletions app/Http/Controllers/UptimeReportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Http\Controllers;

use Exception;
use App\Website;
use App\Jobs\UptimeCheck;
use Illuminate\Http\Request;
Expand All @@ -14,24 +15,15 @@ class UptimeReportController extends Controller
* @param Request $request
* @param Website $website
* @return array
* @throws Exception
*/
public function __invoke(Request $request, Website $website)
{
if ($request->has('refresh')) {
UptimeCheck::dispatchNow($website);
}

$website->load(['uptimes']);

$response = [
'uptime' => $website->uptime_summary,
'response_time' => $website->response_time,
'response_times' => $website->response_times,
'online' => $website->current_state,
'online_time' => $website->uptime,
'last_incident' => $website->last_incident,
'events' => $website->recent_events,
];
$response = $website->generateUptimeReport();

return response($response);
}
Expand Down

0 comments on commit 3ffae39

Please sign in to comment.