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.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
feat(traffic): add application analytics view
Aditya Tripathi3439f0fe63d6
diff --git a/app/Livewire/Project/Application/Analytics.php b/app/Livewire/Project/Application/Analytics.phpnew file mode 100644index 0000000000..0de1b62c84--- /dev/null+++ b/app/Livewire/Project/Application/Analytics.php@@ -0,0 +1,129 @@+<?php++namespace App\Livewire\Project\Application;++use App\Models\Application;+use App\Services\SentinelTrafficClient;+use Livewire\Component;++class Analytics extends Component+{+ public Application $application;++ public string $chartId = 'application-analytics';++ public string $range = '24h';++ public bool $enabled = false;++ public ?array $overview = null;++ public array $topPaths = [];++ /** @var array<string, array<int, array<string, mixed>>> */+ public array $breakdowns = [];++ public ?string $attribution = null;++ /** @var array<int, string> */+ protected array $breakdownDimensions = ['country', 'referer', 'browser', 'os', 'device'];++ public function mount(): void+ {+ $this->enabled = (bool) $this->application->destination?->server?->isTrafficAnalyticsEnabled();++ if ($this->enabled) {+ $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->enabled) {+ return;+ }++ try {+ [$from, $to] = $this->window();+ $client = $this->trafficClient();+ $key = $this->application->uuid;++ $this->overview = $client->overview($key, $from, $to)->toArray();+ $this->topPaths = $client->paths($key, $from, $to, 20)+ ->map(fn ($path) => $path->toArray())+ ->all();++ $breakdowns = [];+ foreach ($this->breakdownDimensions as $dimension) {+ $breakdowns[$dimension] = $client->breakdown($key, $dimension, $from, $to, 10)+ ->map(fn ($row) => $row->toArray())+ ->all();+ }+ $this->breakdowns = $breakdowns;++ $this->attribution = $client->attribution();++ $this->dispatch("refreshChartData-{$this->chartId}-status", [+ 'seriesData' => [+ $this->overview['s2xx'] ?? 0,+ $this->overview['s3xx'] ?? 0,+ $this->overview['s4xx'] ?? 0,+ $this->overview['s5xx'] ?? 0,+ ],+ ]);+ } catch (\Throwable $e) {+ handleError($e, $this);+ }+ }++ 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(): SentinelTrafficClient+ {+ return app(SentinelTrafficClient::class, ['server' => $this->application->destination->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.project.application.analytics');+ }+}diff --git a/resources/views/components/application/configuration-sidebar.blade.php b/resources/views/components/application/configuration-sidebar.blade.phpindex 078f3cafa4..34c1880783 100644--- a/resources/views/components/application/configuration-sidebar.blade.php+++ b/resources/views/components/application/configuration-sidebar.blade.php@@ -115,6 +115,11 @@'route' => 'project.application.metrics','active' => $currentRoute === 'project.application.metrics',],+ [+ 'label' => 'Analytics',+ 'route' => 'project.application.analytics',+ 'active' => $currentRoute === 'project.application.analytics',+ ],['label' => 'Tags','route' => 'project.application.tags',@@ -154,6 +159,7 @@'Resource Limits' => 'cpu','Resource Operations' => 'server-update','Metrics' => 'graph',+ 'Analytics' => 'network','Tags' => 'tags','Danger Zone' => 'shield-alert',];@@ -161,7 +167,7 @@// Discord-style groups for the settings sidebar$menuGroups = ['Settings' => ['General', 'Domains', 'Environment Variables', 'Persistent Storage', 'Advanced', 'Swarm', 'Healthcheck'],- 'Observe & troubleshoot' => ['Runtime Logs', 'Deployment Logs', 'Terminal', 'Metrics'],+ 'Observe & troubleshoot' => ['Runtime Logs', 'Deployment Logs', 'Terminal', 'Metrics', 'Analytics'],'Deploy' => ['Git Source', 'Servers', 'Preview Deployments'],'Automation' => ['Scheduled Tasks', 'Webhooks', 'Backups'],'Operations' => ['Resource Operations', 'Resource Limits', 'Rollback', 'Tags', 'Danger Zone'],diff --git a/resources/views/livewire/project/application/analytics.blade.php b/resources/views/livewire/project/application/analytics.blade.phpnew file mode 100644index 0000000000..66634a9b6b--- /dev/null+++ b/resources/views/livewire/project/application/analytics.blade.php@@ -0,0 +1,190 @@+<?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';++$dimensionLabels = [+ 'country' => 'Countries',+ 'referer' => 'Referrers',+ 'browser' => 'Browsers',+ 'os' => 'Operating systems',+ 'device' => 'Devices',+];+?>+<div class="flex flex-col gap-6">+ @if (! $enabled)+ <x-application.settings-section id="analytics-section" title="Analytics"+ helper="Inspect Cloudflare-style traffic statistics reported by Sentinel.">+ <x-slot:actions>+ <a class="button"+ href="{{ route('server.sentinel', ['server_uuid' => $application->destination->server->uuid]) }}"+ {{ wireNavigate() }}>+ Server settings+ <x-external-link />+ </a>+ </x-slot:actions>+ <x-empty size="sm" title="Traffic analytics is not enabled"+ description="Enable Sentinel traffic analytics for this server to start collecting request analytics."+ icon-name="network" />+ </x-application.settings-section>+ @elseif (! $overview)+ <x-application.settings-section id="analytics-section" title="Analytics"+ helper="Inspect Cloudflare-style traffic statistics reported by Sentinel.">+ <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" />+ </x-application.settings-section>+ @else+ <x-application.settings-section id="analytics-range-section" title="Analytics"+ helper="Inspect Cloudflare-style traffic statistics reported by Sentinel.">+ <x-slot:actions>+ <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>+ </x-slot:actions>++ <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="text-[11px] font-medium tracking-wide text-neutral-500 uppercase dark:text-fg-dim">Unique visitors</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="text-[11px] font-medium tracking-wide text-neutral-500 uppercase dark:text-fg-dim">p95 latency</span>+ <span class="text-xl font-semibold text-black dark:text-fg">{{ number_format($overview['latencyP95'] ?? 0, 1) }} ms</span>+ </div>+ </div>+ </x-application.settings-section>++ <x-application.settings-section id="analytics-status-section" title="Status codes"+ helper="Distribution of response status codes for the selected range.">+ <div wire:ignore id="{!! $chartId !!}-status" class="min-h-[220px] w-full"></div>++ @script+ <script>+ (() => {+ checkTheme();++ const statusColorsLight = ['#0ca30c', '#2a78d6', '#fab219', '#d03b3b'];+ const statusColorsDark = ['#0ca30c', '#3987e5', '#fab219', '#d03b3b'];+ const statusColors = () => theme === 'light' ? statusColorsLight : statusColorsDark;++ const statusChart = new ApexCharts(document.getElementById('{!! $chartId !!}-status'), {+ chart: {+ height: 220,+ type: 'donut',+ toolbar: {+ show: false+ },+ background: 'transparent',+ },+ series: [0, 0, 0, 0],+ labels: ['2xx', '3xx', '4xx', '5xx'],+ colors: statusColors(),+ stroke: {+ width: 2,+ },+ dataLabels: {+ enabled: false,+ },+ legend: {+ position: 'bottom',+ labels: {+ colors: textColor,+ },+ },+ noData: {+ text: 'Loading status codes…',+ style: {+ color: textColor,+ },+ },+ tooltip: {+ y: {+ formatter: value => `${value.toLocaleString()} requests`,+ },+ },+ });++ statusChart.render();++ Livewire.on('refreshChartData-{!! $chartId !!}-status', chartData => {+ checkTheme();+ statusChart.updateOptions({+ colors: statusColors(),+ series: chartData[0].seriesData,+ legend: {+ position: 'bottom',+ labels: {+ colors: textColor,+ },+ },+ });+ });+ })();+ </script>+ @endscript+ </x-application.settings-section>++ <x-application.settings-section id="analytics-paths-section" title="Top paths"+ helper="Most requested paths for the selected range." flush>+ @forelse ($topPaths as $path)+ <div wire:key="analytics-path-{{ $loop->index }}"+ 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 font-mono text-[12px] text-black dark:text-fg">{{ $path['path'] }}</span>+ <span class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ number_format($path['requests']) }} req</span>+ <span class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ formatBytes($path['bytesOut']) }}</span>+ <span class="hidden shrink-0 text-[12px] text-neutral-500 sm:inline dark:text-fg-dim">p95 {{ number_format($path['p95'], 1) }} ms</span>+ </div>+ @empty+ <x-empty size="sm" title="No path data" description="No requests were recorded for the selected range."+ icon-name="unordered-list" />+ @endforelse+ </x-application.settings-section>++ @foreach ($dimensionLabels as $dimension => $label)+ <x-application.settings-section id="analytics-{{ $dimension }}-section" title="{{ $label }}"+ helper="Top {{ strtolower($label) }} by request count for the selected range." flush>+ @forelse (data_get($breakdowns, $dimension, []) as $row)+ <div wire:key="analytics-{{ $dimension }}-{{ $loop->index }}"+ 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'] ?: 'Unknown' }}</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 data" description="No {{ strtolower($label) }} data for the selected range."+ icon-name="network" />+ @endforelse++ @if ($dimension === 'country' && $attribution)+ <p class="border-t border-neutral-200 px-4 py-2 text-[11px] text-neutral-400 dark:border-white/[0.07] dark:text-fg-faint">+ {{ $attribution }}+ </p>+ @endif+ </x-application.settings-section>+ @endforeach+ @endif+</div>diff --git a/resources/views/livewire/project/application/configuration.blade.php b/resources/views/livewire/project/application/configuration.blade.phpindex d5538f8698..26590ccfb6 100644--- a/resources/views/livewire/project/application/configuration.blade.php+++ b/resources/views/livewire/project/application/configuration.blade.php@@ -44,6 +44,8 @@<livewire:project.shared.resource-operations :resource="$application" />@elseif ($currentRoute === 'project.application.metrics')<livewire:project.shared.metrics :resource="$application" />+ @elseif ($currentRoute === 'project.application.analytics')+ <livewire:project.application.analytics :application="$application" />@elseif ($currentRoute === 'project.application.tags')<livewire:project.shared.tags :resource="$application" />@elseif ($currentRoute === 'project.application.danger')diff --git a/routes/web.php b/routes/web.phpindex 1d4e80d067..f3575b1269 100644--- a/routes/web.php+++ b/routes/web.php@@ -275,6 +275,7 @@ Route::middleware(['auth', 'verified'])->group(function () {Route::get('/resource-limits', ApplicationConfiguration::class)->name('project.application.resource-limits');Route::get('/resource-operations', ApplicationConfiguration::class)->name('project.application.resource-operations');Route::get('/metrics', ApplicationConfiguration::class)->name('project.application.metrics');+ Route::get('/analytics', ApplicationConfiguration::class)->name('project.application.analytics');Route::get('/tags', ApplicationConfiguration::class)->name('project.application.tags');Route::get('/danger', ApplicationConfiguration::class)->name('project.application.danger');diff --git a/tests/Feature/ResourceHeadingUnifiedNavbarTest.php b/tests/Feature/ResourceHeadingUnifiedNavbarTest.phpindex cd2cb69b61..683a91ce67 100644--- a/tests/Feature/ResourceHeadingUnifiedNavbarTest.php+++ b/tests/Feature/ResourceHeadingUnifiedNavbarTest.php@@ -179,7 +179,7 @@ it('moves application terminal and logs from the top tabs into the settings side->toContain("'label' => 'Terminal'")->toContain("'label' => 'Deployment Logs'")->toContain("'label' => 'Runtime Logs'")- ->toContain("'Observe & troubleshoot' => ['Runtime Logs', 'Deployment Logs', 'Terminal', 'Metrics']")+ ->toContain("'Observe & troubleshoot' => ['Runtime Logs', 'Deployment Logs', 'Terminal', 'Metrics', 'Analytics']")->toContain("'Operations' => ['Resource Operations', 'Resource Limits', 'Rollback'");});diff --git a/tests/Feature/ServiceDatabaseVerticalNavigationTest.php b/tests/Feature/ServiceDatabaseVerticalNavigationTest.phpindex c191c0f255..9ab7866ba2 100644--- a/tests/Feature/ServiceDatabaseVerticalNavigationTest.php+++ b/tests/Feature/ServiceDatabaseVerticalNavigationTest.php@@ -69,7 +69,7 @@ it('groups application navigation by user workflow', function () {expect($application)->toContain("'Settings' => ['General', 'Domains', 'Environment Variables', 'Persistent Storage', 'Advanced', 'Swarm', 'Healthcheck']")- ->toContain("'Observe & troubleshoot' => ['Runtime Logs', 'Deployment Logs', 'Terminal', 'Metrics']")+ ->toContain("'Observe & troubleshoot' => ['Runtime Logs', 'Deployment Logs', 'Terminal', 'Metrics', 'Analytics']")->toContain("'Deploy' => ['Git Source', 'Servers', 'Preview Deployments']")->toContain("'Automation' => ['Scheduled Tasks', 'Webhooks', 'Backups']")->toContain("'Operations' => ['Resource Operations', 'Resource Limits', 'Rollback', 'Tags', 'Danger Zone']");diff --git a/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php b/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.phpnew file mode 100644index 0000000000..c4c0b7e929--- /dev/null+++ b/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php@@ -0,0 +1,134 @@+<?php++use App\Livewire\Project\Application\Analytics;+use App\Models\Application;+use App\Models\Environment;+use App\Models\PrivateKey;+use App\Models\Project;+use App\Models\Server;+use App\Models\StandaloneDocker;+use App\Models\Team;+use App\Models\User;+use App\Services\SentinelTrafficClient;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Livewire\Livewire;++uses(RefreshDatabase::class);++class FakeAnalyticsTrafficClient 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 fakeAnalyticsResponses(): array+{+ return [+ '/traffic/overview' => json_encode([+ 'requests' => 1000,+ '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/paths' => json_encode([+ ['path' => '/', 'requests' => 500, 'bytes_out' => 12000, 'p50' => 10.0, 'p95' => 30.0],+ ]),+ '/traffic/breakdown/country' => json_encode([+ ['value' => 'US', 'requests' => 600, 'bytes_out' => 15000],+ ]),+ '/traffic/breakdown/referer' => json_encode([+ ['value' => 'google.com', 'requests' => 300, 'bytes_out' => 8000],+ ]),+ '/traffic/breakdown/browser' => json_encode([+ ['value' => 'Chrome', 'requests' => 700, 'bytes_out' => 18000],+ ]),+ '/traffic/breakdown/os' => json_encode([+ ['value' => 'macOS', 'requests' => 400, 'bytes_out' => 10000],+ ]),+ '/traffic/breakdown/device' => json_encode([+ ['value' => 'Desktop', 'requests' => 800, 'bytes_out' => 20000],+ ]),+ '/traffic/attribution' => json_encode(['attribution' => 'GeoIP data by MaxMind']),+ ];+}++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,+ ]);++ $this->project = Project::factory()->create(['team_id' => $this->team->id]);+ $this->environment = Environment::factory()->create(['project_id' => $this->project->id]);+});++function makeAnalyticsApplication(Team $team, PrivateKey $privateKey, Environment $environment, bool $enabled): Application+{+ $server = Server::factory()->create([+ 'team_id' => $team->id,+ 'private_key_id' => $privateKey->id,+ ]);+ $server->settings->is_traffic_analytics_enabled = $enabled;+ $server->settings->save();++ $destination = StandaloneDocker::where('server_id', $server->id)->first()+ ?? StandaloneDocker::factory()->create(['server_id' => $server->id, 'network' => 'coolify-test']);++ return Application::factory()->create([+ 'environment_id' => $environment->id,+ 'destination_id' => $destination->id,+ 'destination_type' => StandaloneDocker::class,+ ]);+}++it('renders KPIs from a mocked traffic client when analytics is enabled', function () {+ $application = makeAnalyticsApplication($this->team, $this->privateKey, $this->environment, true);++ $fake = new FakeAnalyticsTrafficClient($application->destination->server);+ $fake->responses = fakeAnalyticsResponses();+ app()->bind(SentinelTrafficClient::class, fn () => $fake);++ Livewire::test(Analytics::class, ['application' => $application])+ ->assertOk()+ ->assertSee('Requests')+ ->assertSee('1,000')+ ->assertSee('Unique visitors')+ ->assertSee('Error rate')+ ->assertSee('/')+ ->assertSee('US')+ ->assertSee('GeoIP data by MaxMind');+});++it('shows an empty state when traffic analytics is disabled for the server', function () {+ $application = makeAnalyticsApplication($this->team, $this->privateKey, $this->environment, false);++ Livewire::test(Analytics::class, ['application' => $application])+ ->assertOk()+ ->assertSee('Analytics')+ ->assertDontSee('Unique visitors');+});