Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

feat(traffic): add team dashboard traffic analytics

Aditya Tripathi70f7d7452ef8
diff --git a/app/Livewire/Dashboard/TrafficAnalytics.php b/app/Livewire/Dashboard/TrafficAnalytics.php
new file mode 100644
index 0000000000..409c96a982
--- /dev/null
+++ b/app/Livewire/Dashboard/TrafficAnalytics.php
@@ -0,0 +1,152 @@
+<?php
+
+namespace App\Livewire\Dashboard;
+
+use App\Models\Application;
+use App\Models\Server;
+use App\Services\SentinelTrafficClient;
+use App\Services\TrafficAnalyticsAggregator;
+use Illuminate\Support\Collection;
+use Livewire\Component;
+
+class TrafficAnalytics extends Component
+{
+ public Collection $servers;
+
+ public string $range = '24h';
+
+ public ?array $overview = null;
+
+ public bool $latencyApproximate = false;
+
+ public bool $uniquesApproximate = false;
+
+ /** @var array<int, array<string, mixed>> */
+ public array $topApps = [];
+
+ /** @var array<int, array<string, mixed>> */
+ public array $topCountries = [];
+
+ public function mount(): void
+ {
+ $this->servers = Server::ownedByCurrentTeamCached()
+ ->filter(fn (Server $server) => $server->isTrafficAnalyticsEnabled())
+ ->values();
+
+ if ($this->servers->isNotEmpty()) {
+ $this->loadData();
+ }
+ }
+
+ public function setRange(string $range): void
+ {
+ $this->range = in_array($range, ['24h', '7d', '30d'], true) ? $range : '24h';
+ $this->loadData();
+ }
+
+ public function loadData(): void
+ {
+ if ($this->servers->isEmpty()) {
+ return;
+ }
+
+ [$from, $to] = $this->window();
+
+ $overviews = [];
+ $appRows = [];
+ $countryTotals = [];
+
+ foreach ($this->servers as $server) {
+ try {
+ $client = $this->trafficClient($server);
+
+ $overviews[] = $client->overview(null, $from, $to);
+
+ foreach ($client->apps() as $uuid) {
+ if (! is_string($uuid) || $uuid === '') {
+ continue;
+ }
+
+ $appOverview = $client->overview($uuid, $from, $to)->toArray();
+
+ $appRows[] = [
+ 'uuid' => $uuid,
+ 'name' => Application::whereUuid($uuid)->first()?->name ?? $uuid,
+ 'requests' => (int) ($appOverview['requests'] ?? 0),
+ 'bandwidth' => (int) ($appOverview['bytesIn'] ?? 0) + (int) ($appOverview['bytesOut'] ?? 0),
+ ];
+ }
+
+ foreach ($client->breakdown(null, 'country', $from, $to, 20) as $row) {
+ $data = $row->toArray();
+ $value = $data['value'] !== '' ? $data['value'] : 'Unknown';
+
+ $countryTotals[$value] ??= ['value' => $value, 'requests' => 0, 'bytesOut' => 0];
+ $countryTotals[$value]['requests'] += (int) ($data['requests'] ?? 0);
+ $countryTotals[$value]['bytesOut'] += (int) ($data['bytesOut'] ?? 0);
+ }
+ } catch (\Throwable $e) {
+ // Skip unreachable/failed servers so one bad server doesn't break the whole summary.
+ continue;
+ }
+ }
+
+ $result = TrafficAnalyticsAggregator::sumOverviews($overviews);
+
+ $this->overview = $result['overview']->toArray();
+ $this->latencyApproximate = $result['latencyApproximate'];
+ $this->uniquesApproximate = $result['uniquesApproximate'];
+
+ usort($appRows, fn ($a, $b) => $b['requests'] <=> $a['requests']);
+ $this->topApps = array_slice($appRows, 0, 10);
+
+ $countries = array_values($countryTotals);
+ usort($countries, fn ($a, $b) => $b['requests'] <=> $a['requests']);
+ $this->topCountries = array_slice($countries, 0, 10);
+ }
+
+ public function errorRate(): float
+ {
+ if (! $this->overview || (int) ($this->overview['requests'] ?? 0) === 0) {
+ return 0.0;
+ }
+
+ $errors = (int) ($this->overview['s4xx'] ?? 0) + (int) ($this->overview['s5xx'] ?? 0);
+
+ return round(($errors / $this->overview['requests']) * 100, 2);
+ }
+
+ public function bandwidthBytes(): int
+ {
+ if (! $this->overview) {
+ return 0;
+ }
+
+ return (int) ($this->overview['bytesIn'] ?? 0) + (int) ($this->overview['bytesOut'] ?? 0);
+ }
+
+ protected function trafficClient(Server $server): SentinelTrafficClient
+ {
+ return app(SentinelTrafficClient::class, ['server' => $server]);
+ }
+
+ /**
+ * @return array{0: string, 1: string}
+ */
+ private function window(): array
+ {
+ $to = now();
+ $from = match ($this->range) {
+ '7d' => now()->subDays(7),
+ '30d' => now()->subDays(30),
+ default => now()->subDay(),
+ };
+
+ return [$from->toIso8601ZuluString(), $to->toIso8601ZuluString()];
+ }
+
+ public function render()
+ {
+ return view('livewire.dashboard.traffic-analytics');
+ }
+}
diff --git a/resources/views/livewire/dashboard.blade.php b/resources/views/livewire/dashboard.blade.php
index 652dbb0e28..b121648111 100644
--- a/resources/views/livewire/dashboard.blade.php
+++ b/resources/views/livewire/dashboard.blade.php
@@ -16,6 +16,8 @@
<div class="flex min-w-0 flex-col gap-8">
<livewire:dashboard.active-deployments />
+ <livewire:dashboard.traffic-analytics />
+
<section class="mb-0! min-w-0">
<div class="mb-3 flex items-end justify-between gap-4">
<div>
diff --git a/resources/views/livewire/dashboard/traffic-analytics.blade.php b/resources/views/livewire/dashboard/traffic-analytics.blade.php
new file mode 100644
index 0000000000..c4f7a71b3c
--- /dev/null
+++ b/resources/views/livewire/dashboard/traffic-analytics.blade.php
@@ -0,0 +1,147 @@
+<?php
+$tabButtonBase = 'h-7 rounded-md px-2.5 text-[12px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40';
+$tabButtonActive = 'bg-white text-black shadow-sm ring-1 ring-neutral-200 dark:bg-white/[0.09] dark:text-fg dark:ring-white/[0.08]';
+$tabButtonInactive = 'text-neutral-500 hover:text-black dark:text-fg-faint dark:hover:text-fg';
+
+$approxBadge = fn (string $tooltip) => '<span title="'.e($tooltip).'" class="ml-1.5 inline-flex items-center rounded-full bg-amber-100 px-1.5 py-0.5 text-[9px] font-medium tracking-wide text-amber-700 uppercase dark:bg-amber-500/10 dark:text-amber-400">~ approximate</span>';
+?>
+<section class="mb-0! min-w-0">
+ <div class="mb-3 flex items-end justify-between gap-4">
+ <div>
+ <h2 class="text-[14px]! leading-5! font-semibold! text-black dark:text-fg">
+ Traffic analytics
+ </h2>
+ <p class="mt-0.5 text-[11px] text-neutral-500 dark:text-fg-faint">
+ Team-wide request volume across traffic-enabled servers
+ </p>
+ </div>
+
+ @if ($servers->isNotEmpty() && $overview)
+ <div class="inline-flex items-center gap-0.5 rounded-lg bg-neutral-100 p-1 dark:bg-white/[0.04]">
+ <button type="button" wire:click="setRange('24h')"
+ @class([$tabButtonBase, $range === '24h' ? $tabButtonActive : $tabButtonInactive])>
+ 24 hours
+ </button>
+ <button type="button" wire:click="setRange('7d')"
+ @class([$tabButtonBase, $range === '7d' ? $tabButtonActive : $tabButtonInactive])>
+ 7 days
+ </button>
+ <button type="button" wire:click="setRange('30d')"
+ @class([$tabButtonBase, $range === '30d' ? $tabButtonActive : $tabButtonInactive])>
+ 30 days
+ </button>
+ </div>
+ @endif
+ </div>
+
+ @if ($servers->isEmpty())
+ <x-empty size="sm" title="Traffic analytics is not enabled"
+ description="Enable Sentinel traffic analytics on a server to see a team-wide summary here."
+ icon-name="network">
+ <x-slot:contents>
+ <a class="button" href="{{ route('server.index') }}" {{ wireNavigate() }}>
+ View servers
+ </a>
+ </x-slot:contents>
+ </x-empty>
+ @elseif (! $overview)
+ <x-empty size="sm" title="No analytics data yet"
+ description="We could not load traffic analytics for the selected range. Try a different range or check back shortly."
+ icon-name="network" />
+ @else
+ <div
+ class="grid grid-cols-2 gap-px overflow-hidden rounded-lg bg-neutral-200 sm:grid-cols-3 lg:grid-cols-5 dark:bg-white/[0.07]">
+ <div class="flex flex-col gap-1 bg-white px-4 py-3 dark:bg-base">
+ <span
+ class="text-[11px] font-medium tracking-wide text-neutral-500 uppercase dark:text-fg-dim">Requests</span>
+ <span class="text-xl font-semibold text-black dark:text-fg">{{ number_format($overview['requests'] ?? 0) }}</span>
+ </div>
+ <div class="flex flex-col gap-1 bg-white px-4 py-3 dark:bg-base">
+ <span class="flex items-center text-[11px] font-medium tracking-wide text-neutral-500 uppercase dark:text-fg-dim">
+ Unique visitors
+ @if ($uniquesApproximate)
+ {!! $approxBadge('Summed across '.$servers->count().' servers; visitors seen on multiple servers may be double-counted.') !!}
+ @endif
+ </span>
+ <span class="text-xl font-semibold text-black dark:text-fg">{{ number_format($overview['uniqueVisitors'] ?? 0) }}</span>
+ </div>
+ <div class="flex flex-col gap-1 bg-white px-4 py-3 dark:bg-base">
+ <span
+ class="text-[11px] font-medium tracking-wide text-neutral-500 uppercase dark:text-fg-dim">Bandwidth</span>
+ <span class="text-xl font-semibold text-black dark:text-fg">{{ formatBytes($this->bandwidthBytes()) }}</span>
+ </div>
+ <div class="flex flex-col gap-1 bg-white px-4 py-3 dark:bg-base">
+ <span
+ class="text-[11px] font-medium tracking-wide text-neutral-500 uppercase dark:text-fg-dim">Error rate</span>
+ <span class="text-xl font-semibold text-black dark:text-fg">{{ $this->errorRate() }}%</span>
+ </div>
+ <div class="flex flex-col gap-1 bg-white px-4 py-3 dark:bg-base">
+ <span class="flex items-center text-[11px] font-medium tracking-wide text-neutral-500 uppercase dark:text-fg-dim">
+ p95 latency
+ @if ($latencyApproximate)
+ {!! $approxBadge('Highest p95 latency across '.$servers->count().' servers; not a true cross-server percentile.') !!}
+ @endif
+ </span>
+ <span class="text-xl font-semibold text-black dark:text-fg">{{ number_format($overview['latencyP95'] ?? 0, 1) }} ms</span>
+ </div>
+ </div>
+
+ <div class="mt-4 grid min-w-0 grid-cols-1 gap-4 lg:grid-cols-2">
+ <div
+ class="overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-sm dark:border-white/[0.08] dark:bg-white/[0.025]">
+ <div class="border-b border-neutral-200 px-4 py-2.5 dark:border-white/[0.08]">
+ <h3 class="text-[12px]! leading-4! font-semibold! text-black dark:text-fg">
+ Top applications
+ </h3>
+ <p class="mt-0.5 text-[11px] text-neutral-500 dark:text-fg-faint">
+ Ranked by request volume across all servers
+ </p>
+ </div>
+
+ @forelse ($topApps as $row)
+ <div wire:key="dashboard-traffic-app-{{ $row['uuid'] }}"
+ class="flex min-h-11 items-center gap-3 border-b border-neutral-200 px-4 py-2 last:border-b-0 dark:border-white/[0.07]">
+ <span
+ class="min-w-0 flex-1 truncate text-[12px] text-black dark:text-fg">{{ $row['name'] }}</span>
+ <span
+ class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ number_format($row['requests']) }} req</span>
+ <span
+ class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ formatBytes($row['bandwidth']) }}</span>
+ </div>
+ @empty
+ <x-empty size="sm" title="No application data"
+ description="No per-application requests were recorded for the selected range."
+ icon-name="unordered-list" />
+ @endforelse
+ </div>
+
+ <div
+ class="overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-sm dark:border-white/[0.08] dark:bg-white/[0.025]">
+ <div class="border-b border-neutral-200 px-4 py-2.5 dark:border-white/[0.08]">
+ <h3 class="text-[12px]! leading-4! font-semibold! text-black dark:text-fg">
+ Top countries
+ </h3>
+ <p class="mt-0.5 text-[11px] text-neutral-500 dark:text-fg-faint">
+ Summed across all servers for the selected range
+ </p>
+ </div>
+
+ @forelse ($topCountries as $row)
+ <div wire:key="dashboard-traffic-country-{{ $row['value'] }}"
+ class="flex min-h-11 items-center gap-3 border-b border-neutral-200 px-4 py-2 last:border-b-0 dark:border-white/[0.07]">
+ <span
+ class="min-w-0 flex-1 truncate text-[12px] text-black dark:text-fg">{{ $row['value'] }}</span>
+ <span
+ class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ number_format($row['requests']) }} req</span>
+ <span
+ class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ formatBytes($row['bytesOut']) }}</span>
+ </div>
+ @empty
+ <x-empty size="sm" title="No country data"
+ description="No country data was recorded for the selected range."
+ icon-name="network" />
+ @endforelse
+ </div>
+ </div>
+ @endif
+</section>
diff --git a/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php b/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php
new file mode 100644
index 0000000000..660d0e3a23
--- /dev/null
+++ b/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php
@@ -0,0 +1,113 @@
+<?php
+
+use App\Livewire\Dashboard\TrafficAnalytics;
+use App\Models\PrivateKey;
+use App\Models\Server;
+use App\Models\Team;
+use App\Models\User;
+use App\Services\SentinelTrafficClient;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+class FakeDashboardTrafficClient extends SentinelTrafficClient
+{
+ public array $responses = [];
+
+ protected function raw(string $url): string
+ {
+ foreach ($this->responses as $needle => $response) {
+ if (str_contains($url, $needle)) {
+ return $response;
+ }
+ }
+
+ return '{}';
+ }
+}
+
+function fakeDashboardTrafficResponses(int $requests = 1000): array
+{
+ return [
+ '/traffic/apps' => json_encode([]),
+ '/traffic/overview' => json_encode([
+ 'requests' => $requests,
+ 'bytes_in' => 5000,
+ 'bytes_out' => 25000,
+ 'status' => ['s2xx' => 900, 's3xx' => 50, 's4xx' => 40, 's5xx' => 10],
+ 'latency' => ['p50' => 12.5, 'p95' => 45.2, 'p99' => 90.1],
+ 'unique_visitors' => 320,
+ ]),
+ '/traffic/breakdown/country' => json_encode([
+ ['value' => 'US', 'requests' => 600, 'bytes_out' => 15000],
+ ]),
+ ];
+}
+
+beforeEach(function () {
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+
+ $this->privateKey = PrivateKey::create([
+ 'name' => 'Test Key',
+ 'private_key' => '-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
+QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
+hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
+AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
+uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
+-----END OPENSSH PRIVATE KEY-----',
+ 'team_id' => $this->team->id,
+ ]);
+});
+
+it('renders the team traffic summary aggregated across servers with an approximate badge', function () {
+ $serverOne = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => $this->privateKey->id,
+ ]);
+ $serverOne->settings->is_traffic_analytics_enabled = true;
+ $serverOne->settings->save();
+
+ $serverTwo = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => $this->privateKey->id,
+ ]);
+ $serverTwo->settings->is_traffic_analytics_enabled = true;
+ $serverTwo->settings->save();
+
+ $fakeOne = new FakeDashboardTrafficClient($serverOne);
+ $fakeOne->responses = fakeDashboardTrafficResponses(1000);
+
+ $fakeTwo = new FakeDashboardTrafficClient($serverTwo);
+ $fakeTwo->responses = fakeDashboardTrafficResponses(500);
+
+ app()->bind(SentinelTrafficClient::class, function ($app, $params) use ($serverOne, $fakeOne, $fakeTwo) {
+ $server = $params['server'] ?? null;
+
+ return $server && $server->is($serverOne) ? $fakeOne : $fakeTwo;
+ });
+
+ Livewire::test(TrafficAnalytics::class)
+ ->assertOk()
+ ->assertSee('Requests')
+ ->assertSee('1,500')
+ ->assertSee('Unique visitors')
+ ->assertSee('approximate');
+});
+
+it('shows an empty state when no server in the team has traffic analytics enabled', function () {
+ Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => $this->privateKey->id,
+ ]);
+
+ Livewire::test(TrafficAnalytics::class)
+ ->assertOk()
+ ->assertDontSee('Unique visitors')
+ ->assertSee('not enabled');
+});