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 global analytics page with status time series

Aditya Tripathia5cfa7c238c4
diff --git a/app/Data/Traffic/TrafficPathData.php b/app/Data/Traffic/TrafficPathData.php
index 6716d7a193..40549c9ebf 100644
--- a/app/Data/Traffic/TrafficPathData.php
+++ b/app/Data/Traffic/TrafficPathData.php
@@ -12,6 +12,9 @@ class TrafficPathData extends Data
public int $bytesOut,
public float $p50,
public float $p95,
+ // Owning app key (Sentinel returns this per path row so the UI can show the
+ // domain). Empty on older Sentinel builds that predate the field.
+ public string $app = '',
) {}
public static function fromSentinel(array $row): self
@@ -22,6 +25,7 @@ class TrafficPathData extends Data
bytesOut: (int) data_get($row, 'bytes_out', 0),
p50: (float) data_get($row, 'p50', 0.0),
p95: (float) data_get($row, 'p95', 0.0),
+ app: (string) data_get($row, 'app', ''),
);
}
}
diff --git a/app/Data/Traffic/TrafficSeriesBucketData.php b/app/Data/Traffic/TrafficSeriesBucketData.php
new file mode 100644
index 0000000000..077d3cf7bf
--- /dev/null
+++ b/app/Data/Traffic/TrafficSeriesBucketData.php
@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Data\Traffic;
+
+use Spatie\LaravelData\Data;
+
+class TrafficSeriesBucketData extends Data
+{
+ public function __construct(
+ // Unix-millis start of the bucket (hour- or day-aligned by the request's range).
+ public int $bucket,
+ public int $s2xx,
+ public int $s3xx,
+ public int $s4xx,
+ public int $s5xx,
+ ) {}
+
+ public static function fromSentinel(array $row): self
+ {
+ return new self(
+ bucket: (int) data_get($row, 'bucket', 0),
+ s2xx: (int) data_get($row, 's2xx', 0),
+ s3xx: (int) data_get($row, 's3xx', 0),
+ s4xx: (int) data_get($row, 's4xx', 0),
+ s5xx: (int) data_get($row, 's5xx', 0),
+ );
+ }
+}
diff --git a/app/Livewire/Analytics.php b/app/Livewire/Analytics.php
new file mode 100644
index 0000000000..5801170a4f
--- /dev/null
+++ b/app/Livewire/Analytics.php
@@ -0,0 +1,481 @@
+<?php
+
+namespace App\Livewire;
+
+use App\Models\Application;
+use App\Models\Server;
+use App\Services\SentinelTrafficClient;
+use App\Services\TrafficAnalyticsAggregator;
+use Illuminate\Support\Collection;
+use Livewire\Attributes\Url;
+use Livewire\Component;
+
+class Analytics extends Component
+{
+ public string $chartId = 'global-analytics';
+
+ /** Traffic-enabled servers owned by the current team. */
+ public Collection $servers;
+
+ /** @var array<string, string> uuid => name, for the server filter */
+ public array $serverOptions = [];
+
+ /** @var array<string, string> uuid => name, for the application filter (scoped to the selected server) */
+ public array $appOptions = [];
+
+ /**
+ * Listbox options for the application filter, grouped under project headers so
+ * it's clear which application belongs to which project.
+ *
+ * @var array<int, array{value: string, label: string, header?: bool}>
+ */
+ public array $appGroupedOptions = [];
+
+ #[Url(as: 'range')]
+ public string $range = '24h';
+
+ #[Url(as: 'server')]
+ public string $serverUuid = '';
+
+ #[Url(as: 'app')]
+ public string $appUuid = '';
+
+ // Realtime refresh; armed only on the 24h range (matches the 60s Sentinel cache TTL).
+ public bool $live = true;
+
+ 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 $topPaths = [];
+
+ /** @var array<string, array<int, array<string, mixed>>> */
+ public array $breakdowns = [];
+
+ public ?string $attribution = null;
+
+ /**
+ * Per-bucket status-class time series for the stacked area chart, summed across
+ * target servers and sorted by bucket. Empty when no target Sentinel exposes the
+ * series endpoint (older builds), which flips the chart back to the status donut.
+ *
+ * @var array<int, array{bucket: int, s2xx: int, s3xx: int, s4xx: int, s5xx: int}>
+ */
+ public array $series = [];
+
+ public bool $hasSeries = false;
+
+ /**
+ * Servers that could run traffic analytics but have it off — drives the nudge banner.
+ *
+ * @var array<int, array{uuid: string, name: string}>
+ */
+ public array $eligibleDisabledServers = [];
+
+ public string $nudgeKey = '';
+
+ /** @var array<int, string> */
+ protected array $breakdownDimensions = ['country', 'referer', 'browser', 'os', 'device', 'agent', 'ip', 'useragent'];
+
+ /**
+ * Per-request cache of app uuid => display metadata, so resolving a name/domain/link
+ * for the leaderboard and path domains hits the DB at most once per app.
+ *
+ * @var array<string, array{name: string, domain: ?string, link: ?string}>
+ */
+ protected array $appMetaCache = [];
+
+ public function mount(): void
+ {
+ $allServers = Server::ownedByCurrentTeamCached();
+
+ $this->servers = $allServers
+ ->filter(fn (Server $server) => $server->isTrafficAnalyticsEnabled())
+ ->values();
+
+ $this->serverOptions = $this->servers
+ ->mapWithKeys(fn (Server $server) => [$server->uuid => $server->name])
+ ->all();
+
+ $eligibleDisabled = $allServers
+ ->filter(fn (Server $server) => ! $server->isTrafficAnalyticsEnabled()
+ && ! $server->isSwarm()
+ && ! $server->isBuildServer())
+ ->values();
+
+ $this->eligibleDisabledServers = $eligibleDisabled
+ ->map(fn (Server $server) => ['uuid' => $server->uuid, 'name' => $server->name])
+ ->all();
+ $this->nudgeKey = substr(md5($eligibleDisabled->pluck('uuid')->sort()->implode(',')), 0, 12);
+
+ // A bookmarked ?server= may point at a server that is no longer enabled.
+ if ($this->serverUuid !== '' && ! array_key_exists($this->serverUuid, $this->serverOptions)) {
+ $this->serverUuid = '';
+ }
+
+ $this->refreshAppOptions();
+
+ if ($this->appUuid !== '' && ! array_key_exists($this->appUuid, $this->appOptions)) {
+ $this->appUuid = '';
+ }
+
+ 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 toggleLive(): void
+ {
+ if ($this->range !== '24h') {
+ return;
+ }
+ $this->live = ! $this->live;
+ }
+
+ public function isLivePollable(): bool
+ {
+ return $this->live && $this->range === '24h';
+ }
+
+ public function updatedServerUuid(): void
+ {
+ // Scope the app options to the newly selected server and drop an app filter
+ // that no longer belongs to it.
+ $this->refreshAppOptions();
+
+ if ($this->appUuid !== '' && ! array_key_exists($this->appUuid, $this->appOptions)) {
+ $this->appUuid = '';
+ }
+
+ $this->loadData();
+ }
+
+ public function updatedAppUuid(): void
+ {
+ $this->loadData();
+ }
+
+ protected function refreshAppOptions(): void
+ {
+ $enabledUuids = $this->servers->pluck('uuid');
+
+ $apps = Application::ownedByCurrentTeam()->with('environment.project')->get()
+ ->filter(function (Application $app) use ($enabledUuids): bool {
+ $serverUuid = $app->destination?->server?->uuid;
+
+ if (! $serverUuid || ! $enabledUuids->contains($serverUuid)) {
+ return false;
+ }
+
+ return $this->serverUuid === '' || $serverUuid === $this->serverUuid;
+ });
+
+ // Flat uuid => name map, used to validate a bookmarked ?app= filter.
+ $options = $apps->mapWithKeys(fn (Application $app) => [$app->uuid => $app->name])->all();
+ asort($options);
+ $this->appOptions = $options;
+
+ // Grouped listbox options: a header row per project, then its apps (both alpha-sorted).
+ $grouped = [];
+ $byProject = $apps
+ ->groupBy(fn (Application $app) => (string) (data_get($app, 'environment.project.name') ?: 'Ungrouped'))
+ ->sortKeys();
+
+ foreach ($byProject as $projectName => $projectApps) {
+ $grouped[] = ['value' => '__group_'.md5($projectName), 'label' => $projectName, 'header' => true];
+ foreach ($projectApps->sortBy('name') as $app) {
+ $grouped[] = ['value' => $app->uuid, 'label' => $app->name];
+ }
+ }
+
+ $this->appGroupedOptions = $grouped;
+ }
+
+ /**
+ * Servers this view should query, honoring the active server/app filters.
+ */
+ protected function targetServers(): Collection
+ {
+ if ($this->appUuid !== '') {
+ $server = Application::ownedByCurrentTeam()->whereUuid($this->appUuid)->first()
+ ?->destination?->server;
+
+ return $server && $this->servers->contains(fn (Server $s) => $s->uuid === $server->uuid)
+ ? collect([$server])
+ : collect();
+ }
+
+ if ($this->serverUuid !== '') {
+ return $this->servers->filter(fn (Server $s) => $s->uuid === $this->serverUuid)->values();
+ }
+
+ return $this->servers;
+ }
+
+ public function loadData(): void
+ {
+ if ($this->servers->isEmpty()) {
+ return;
+ }
+
+ [$from, $to] = $this->window();
+ $appKey = $this->appUuid !== '' ? $this->appUuid : null;
+ $servers = $this->targetServers();
+
+ $overviews = [];
+ $appRows = [];
+ $pathTotals = [];
+ $breakdownTotals = array_fill_keys($this->breakdownDimensions, []);
+ $seriesByBucket = [];
+ $attribution = null;
+
+ foreach ($servers as $server) {
+ try {
+ $client = $this->trafficClient($server);
+
+ $overviews[] = $client->overview($appKey, $from, $to);
+
+ // Per-application leaderboard only makes sense when not already filtered to one app.
+ if ($appKey === null) {
+ foreach ($client->apps() as $uuid) {
+ if (! is_string($uuid) || $uuid === '') {
+ continue;
+ }
+
+ $appOverview = $client->overview($uuid, $from, $to)->toArray();
+ $meta = $this->appMeta($uuid);
+
+ $appRows[] = [
+ 'uuid' => $uuid,
+ 'name' => $meta['name'],
+ 'domain' => $meta['domain'],
+ 'link' => $meta['link'],
+ 'requests' => (int) ($appOverview['requests'] ?? 0),
+ 'bandwidth' => (int) ($appOverview['bytesIn'] ?? 0) + (int) ($appOverview['bytesOut'] ?? 0),
+ ];
+ }
+ }
+
+ foreach ($client->paths($appKey, $from, $to, 50) as $path) {
+ $data = $path->toArray();
+ $pathStr = (string) ($data['path'] ?? '');
+ // Prefer the per-path app from Sentinel; fall back to the active app filter
+ // (older Sentinel omits `app`, but a filtered view still knows the app).
+ $appId = (string) ($data['app'] ?? '');
+ $resolveId = $appId !== '' ? $appId : ($appKey ?? '');
+ // Key by (app, path) so the same path under two apps stays two rows, each
+ // carrying its own domain.
+ $key = $resolveId."\n".$pathStr;
+ $domain = $resolveId !== '' ? ($this->appMeta($resolveId)['domain'] ?? null) : null;
+
+ $pathTotals[$key] ??= ['path' => $pathStr, 'domain' => $domain, 'requests' => 0, 'bytesOut' => 0, 'p95' => 0.0];
+ $pathTotals[$key]['requests'] += (int) ($data['requests'] ?? 0);
+ $pathTotals[$key]['bytesOut'] += (int) ($data['bytesOut'] ?? 0);
+ $pathTotals[$key]['p95'] = max($pathTotals[$key]['p95'], (float) ($data['p95'] ?? 0));
+ }
+
+ foreach ($this->breakdownDimensions as $dimension) {
+ foreach ($client->breakdown($appKey, $dimension, $from, $to, 50) as $row) {
+ $data = $row->toArray();
+ $value = (string) ($data['value'] ?? '');
+
+ $breakdownTotals[$dimension][$value] ??= ['value' => $value, 'requests' => 0, 'bytesOut' => 0];
+ $breakdownTotals[$dimension][$value]['requests'] += (int) ($data['requests'] ?? 0);
+ $breakdownTotals[$dimension][$value]['bytesOut'] += (int) ($data['bytesOut'] ?? 0);
+ }
+ }
+
+ $attribution ??= $client->attribution();
+
+ // Per-bucket status series; summed by bucket across servers. Isolated so a
+ // series hiccup (or an older Sentinel lacking the endpoint) never discards a
+ // server's other data — an empty result simply flips the chart to the donut.
+ try {
+ foreach ($client->series($appKey, $this->range) as $bucket) {
+ $data = $bucket->toArray();
+ $ts = (int) ($data['bucket'] ?? 0);
+
+ $seriesByBucket[$ts] ??= ['bucket' => $ts, 's2xx' => 0, 's3xx' => 0, 's4xx' => 0, 's5xx' => 0];
+ $seriesByBucket[$ts]['s2xx'] += (int) ($data['s2xx'] ?? 0);
+ $seriesByBucket[$ts]['s3xx'] += (int) ($data['s3xx'] ?? 0);
+ $seriesByBucket[$ts]['s4xx'] += (int) ($data['s4xx'] ?? 0);
+ $seriesByBucket[$ts]['s5xx'] += (int) ($data['s5xx'] ?? 0);
+ }
+ } catch (\Throwable $e) {
+ // Leave this server out of the series; donut fallback covers it.
+ }
+ } catch (\Throwable $e) {
+ // Skip unreachable/failed servers so one bad server doesn't break the whole view.
+ continue;
+ }
+ }
+
+ if (empty($overviews)) {
+ $this->resetData();
+
+ return;
+ }
+
+ $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, 50);
+
+ $paths = array_values($pathTotals);
+ usort($paths, fn ($a, $b) => $b['requests'] <=> $a['requests']);
+ $this->topPaths = array_slice($paths, 0, 50);
+
+ $breakdowns = [];
+ foreach ($this->breakdownDimensions as $dimension) {
+ $rows = array_values($breakdownTotals[$dimension]);
+ usort($rows, fn ($a, $b) => $b['requests'] <=> $a['requests']);
+ $breakdowns[$dimension] = array_slice($rows, 0, 50);
+ }
+ $this->breakdowns = $breakdowns;
+
+ $this->attribution = $attribution;
+
+ ksort($seriesByBucket);
+ $this->series = array_values($seriesByBucket);
+ $this->hasSeries = $this->series !== [];
+
+ $this->dispatch("refreshChartData-{$this->chartId}-status", $this->chartPayload());
+ }
+
+ /**
+ * Payload for the status chart: the stacked-area time series when available,
+ * plus the donut totals as a fallback for older Sentinel builds.
+ *
+ * @return array<string, mixed>
+ */
+ protected function chartPayload(): array
+ {
+ return [
+ 'hasSeries' => $this->hasSeries,
+ 'range' => $this->range,
+ 'seriesData' => [
+ $this->overview['s2xx'] ?? 0,
+ $this->overview['s3xx'] ?? 0,
+ $this->overview['s4xx'] ?? 0,
+ $this->overview['s5xx'] ?? 0,
+ ],
+ 'timeSeries' => [
+ 'categories' => array_column($this->series, 'bucket'),
+ 's2xx' => array_column($this->series, 's2xx'),
+ 's3xx' => array_column($this->series, 's3xx'),
+ 's4xx' => array_column($this->series, 's4xx'),
+ 's5xx' => array_column($this->series, 's5xx'),
+ ],
+ ];
+ }
+
+ protected function resetData(): void
+ {
+ $this->overview = null;
+ $this->latencyApproximate = false;
+ $this->uniquesApproximate = false;
+ $this->topApps = [];
+ $this->topPaths = [];
+ $this->breakdowns = [];
+ $this->attribution = null;
+ $this->series = [];
+ $this->hasSeries = false;
+ }
+
+ 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]);
+ }
+
+ /**
+ * Resolve an app uuid to its display name, primary domain, and analytics-page link,
+ * memoized per request. Returns the uuid as the name for apps not owned by the team
+ * so a Sentinel-reported uuid never discloses another team's application name.
+ *
+ * @return array{name: string, domain: ?string, link: ?string}
+ */
+ protected function appMeta(string $uuid): array
+ {
+ if (isset($this->appMetaCache[$uuid])) {
+ return $this->appMetaCache[$uuid];
+ }
+
+ $app = Application::ownedByCurrentTeam()->with('environment.project')->whereUuid($uuid)->first();
+
+ $domain = null;
+ if ($app) {
+ $first = collect($app->fqdns)->first();
+ $domain = $first ? (parse_url($first, PHP_URL_HOST) ?: null) : null;
+ }
+
+ $link = null;
+ if ($app && data_get($app, 'environment.project.uuid')) {
+ $link = route('project.application.analytics', [
+ 'project_uuid' => $app->environment->project->uuid,
+ 'environment_uuid' => $app->environment->uuid,
+ 'application_uuid' => $app->uuid,
+ ]);
+ }
+
+ return $this->appMetaCache[$uuid] = [
+ 'name' => $app?->name ?? $uuid,
+ 'domain' => $domain,
+ 'link' => $link,
+ ];
+ }
+
+ /**
+ * @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.analytics');
+ }
+}
diff --git a/app/Livewire/Project/Application/Analytics.php b/app/Livewire/Project/Application/Analytics.php
index 963bd0b515..e89b7df6b6 100644
--- a/app/Livewire/Project/Application/Analytics.php
+++ b/app/Livewire/Project/Application/Analytics.php
@@ -30,8 +30,18 @@ class Analytics extends Component
public ?string $attribution = null;
+ /**
+ * Per-bucket status-class time series for the stacked area chart. Empty when this
+ * app's Sentinel lacks the series endpoint, which flips the chart to the donut.
+ *
+ * @var array<int, array{bucket: int, s2xx: int, s3xx: int, s4xx: int, s5xx: int}>
+ */
+ public array $series = [];
+
+ public bool $hasSeries = false;
+
/** @var array<int, string> */
- protected array $breakdownDimensions = ['country', 'referer', 'browser', 'os', 'device'];
+ protected array $breakdownDimensions = ['country', 'referer', 'browser', 'os', 'device', 'agent', 'ip', 'useragent'];
public function mount(): void
{
@@ -76,13 +86,17 @@ class Analytics extends Component
$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())
+
+ // Every path belongs to this one app, so decorate each row with its domain
+ // for a consistent "domain + path" presentation and an openable live link.
+ $domain = $this->applicationDomain();
+ $this->topPaths = $client->paths($key, $from, $to, 50)
+ ->map(fn ($path) => ['domain' => $domain] + $path->toArray())
->all();
$breakdowns = [];
foreach ($this->breakdownDimensions as $dimension) {
- $breakdowns[$dimension] = $client->breakdown($key, $dimension, $from, $to, 10)
+ $breakdowns[$dimension] = $client->breakdown($key, $dimension, $from, $to, 50)
->map(fn ($row) => $row->toArray())
->all();
}
@@ -90,19 +104,50 @@ class Analytics extends Component
$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,
- ],
- ]);
+ // Per-bucket status series; absent on older Sentinel builds (empty → donut fallback).
+ // Isolated so a series hiccup never errors the rest of the widget.
+ try {
+ $this->series = $client->series($key, $this->range)
+ ->map(fn ($bucket) => $bucket->toArray())
+ ->all();
+ } catch (\Throwable $e) {
+ $this->series = [];
+ }
+ $this->hasSeries = $this->series !== [];
+
+ $this->dispatch("refreshChartData-{$this->chartId}-status", $this->chartPayload());
} catch (\Throwable $e) {
handleError($e, $this);
}
}
+ /**
+ * Payload for the status chart: the stacked-area time series when available,
+ * plus the donut totals as a fallback for older Sentinel builds.
+ *
+ * @return array<string, mixed>
+ */
+ protected function chartPayload(): array
+ {
+ return [
+ 'hasSeries' => $this->hasSeries,
+ 'range' => $this->range,
+ 'seriesData' => [
+ $this->overview['s2xx'] ?? 0,
+ $this->overview['s3xx'] ?? 0,
+ $this->overview['s4xx'] ?? 0,
+ $this->overview['s5xx'] ?? 0,
+ ],
+ 'timeSeries' => [
+ 'categories' => array_column($this->series, 'bucket'),
+ 's2xx' => array_column($this->series, 's2xx'),
+ 's3xx' => array_column($this->series, 's3xx'),
+ 's4xx' => array_column($this->series, 's4xx'),
+ 's5xx' => array_column($this->series, 's5xx'),
+ ],
+ ];
+ }
+
public function errorRate(): float
{
if (! $this->overview || (int) ($this->overview['requests'] ?? 0) === 0) {
@@ -128,6 +173,17 @@ class Analytics extends Component
return app(SentinelTrafficClient::class, ['server' => $this->application->destination->server]);
}
+ /**
+ * Primary domain host for this application (first configured FQDN), or null when
+ * none is set — used to present paths as "domain + path" with an openable link.
+ */
+ protected function applicationDomain(): ?string
+ {
+ $first = collect($this->application->fqdns)->first();
+
+ return $first ? (parse_url($first, PHP_URL_HOST) ?: null) : null;
+ }
+
/**
* @return array{0: string, 1: string}
*/
diff --git a/app/Livewire/Server/Analytics.php b/app/Livewire/Server/Analytics.php
deleted file mode 100644
index 394b7bf5d9..0000000000
--- a/app/Livewire/Server/Analytics.php
+++ /dev/null
@@ -1,219 +0,0 @@
-<?php
-
-namespace App\Livewire\Server;
-
-use App\Actions\Server\ConfigureTrafficAnalytics;
-use App\Models\Application;
-use App\Models\Server;
-use App\Services\SentinelTrafficClient;
-use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
-use Livewire\Component;
-
-class Analytics extends Component
-{
- use AuthorizesRequests;
-
- public Server $server;
-
- public string $chartId = 'server-analytics';
-
- public string $range = '24h';
-
- public bool $enabled = false;
-
- // Realtime refresh. On by default for the 24h range; the 60s cadence matches the
- // SentinelTrafficClient cache TTL and Sentinel's per-minute rollups, so polling
- // faster returns identical data. Auto-paused (control disabled) for 7d/30d.
- public bool $live = true;
-
- public ?array $overview = null;
-
- public array $topPaths = [];
-
- /** @var array<string, array<int, array<string, mixed>>> */
- public array $breakdowns = [];
-
- /** @var array<int, array<string, mixed>> */
- public array $leaderboard = [];
-
- public ?string $attribution = null;
-
- /** @var array<int, string> */
- protected array $breakdownDimensions = ['country', 'referer', 'browser', 'os', 'device'];
-
- public function mount(string $server_uuid)
- {
- try {
- $this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
- } catch (\Throwable $e) {
- return handleError($e, $this);
- }
-
- $this->enabled = (bool) $this->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 toggleLive(): void
- {
- if ($this->range !== '24h') {
- return;
- }
- $this->live = ! $this->live;
- }
-
- /**
- * Whether this server can run traffic analytics at all (Swarm/Build cannot).
- */
- public function isEligibleForTrafficAnalytics(): bool
- {
- return ! $this->server->isSwarm() && ! $this->server->isBuildServer();
- }
-
- public function enableTrafficAnalytics(): void
- {
- try {
- $this->authorize('update', $this->server);
- if (! $this->isEligibleForTrafficAnalytics()) {
- $this->dispatch('error', 'Traffic analytics is not supported on Swarm/Build servers.');
-
- return;
- }
- ConfigureTrafficAnalytics::run($this->server, true);
- $this->server->refresh();
- $this->enabled = true;
- $this->dispatch('success', 'Traffic analytics enabled. Restarting proxy and Sentinel.');
- $this->loadData();
- } catch (\Throwable $e) {
- handleError($e, $this);
- }
- }
-
- /**
- * Realtime polling is only armed when the user has it on and the range is 24h.
- */
- public function isLivePollable(): bool
- {
- return $this->live && $this->range === '24h';
- }
-
- public function loadData(): void
- {
- if (! $this->enabled) {
- return;
- }
-
- try {
- [$from, $to] = $this->window();
- $client = $this->trafficClient();
-
- $this->overview = $client->overview(null, $from, $to)->toArray();
- $this->topPaths = $client->paths(null, $from, $to, 20)
- ->map(fn ($path) => $path->toArray())
- ->all();
-
- $breakdowns = [];
- foreach ($this->breakdownDimensions as $dimension) {
- $breakdowns[$dimension] = $client->breakdown(null, $dimension, $from, $to, 10)
- ->map(fn ($row) => $row->toArray())
- ->all();
- }
- $this->breakdowns = $breakdowns;
-
- $this->attribution = $client->attribution();
-
- $this->leaderboard = $this->loadLeaderboard($client, $from, $to);
-
- $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);
- }
-
- /**
- * @return array<int, array<string, mixed>>
- */
- private function loadLeaderboard(SentinelTrafficClient $client, string $from, string $to): array
- {
- $rows = [];
-
- foreach ($client->apps() as $uuid) {
- if (! is_string($uuid) || $uuid === '') {
- continue;
- }
-
- $overview = $client->overview($uuid, $from, $to)->toArray();
-
- $rows[] = [
- 'uuid' => $uuid,
- 'name' => Application::ownedByCurrentTeam()->whereUuid($uuid)->first()?->name ?? $uuid,
- 'requests' => (int) ($overview['requests'] ?? 0),
- 'bandwidth' => (int) ($overview['bytesIn'] ?? 0) + (int) ($overview['bytesOut'] ?? 0),
- ];
- }
-
- usort($rows, fn ($a, $b) => $b['requests'] <=> $a['requests']);
-
- return array_slice($rows, 0, 10);
- }
-
- protected function trafficClient(): SentinelTrafficClient
- {
- return app(SentinelTrafficClient::class, ['server' => $this->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.server.analytics');
- }
-}
diff --git a/app/Services/SentinelTrafficClient.php b/app/Services/SentinelTrafficClient.php
index 7faa95f2a7..e42caa1f99 100644
--- a/app/Services/SentinelTrafficClient.php
+++ b/app/Services/SentinelTrafficClient.php
@@ -5,6 +5,7 @@ namespace App\Services;
use App\Data\Traffic\TrafficBreakdownData;
use App\Data\Traffic\TrafficOverviewData;
use App\Data\Traffic\TrafficPathData;
+use App\Data\Traffic\TrafficSeriesBucketData;
use App\Models\Server;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
@@ -15,7 +16,7 @@ class SentinelTrafficClient
/** @var array<int, string> */
private const ALLOWED_DIMENSIONS = [
- 'status', 'method', 'country', 'referer', 'browser', 'os', 'device', 'protocol', 'scheme', 'tls', 'cache', 'bot',
+ 'status', 'method', 'country', 'referer', 'browser', 'os', 'device', 'protocol', 'scheme', 'tls', 'cache', 'bot', 'agent', 'ip', 'useragent',
];
public function __construct(protected Server $server) {}
@@ -84,6 +85,33 @@ class SentinelTrafficClient
return collect($rows)->map(fn ($r) => TrafficBreakdownData::fromSentinel($r));
}
+ /**
+ * Per-bucket status-class time series for the stacked-area chart.
+ *
+ * The series endpoints take a single `range` knob (24h/7d/30d) rather than
+ * from/to, and always return a fixed-length, zero-filled array when present.
+ * An older Sentinel without the route answers 404 (empty/non-array body);
+ * we return an empty collection in that case so callers can gracefully fall
+ * back to the donut instead of surfacing an error.
+ *
+ * @return Collection<int, TrafficSeriesBucketData>
+ */
+ public function series(?string $appKey, string $range = '24h'): Collection
+ {
+ if ($appKey !== null) {
+ $this->assertSafeKey($appKey);
+ }
+ $range = in_array($range, ['24h', '7d', '30d'], true) ? $range : '24h';
+ $path = $appKey ? "/app/{$appKey}/traffic/series" : '/traffic/series';
+ $rows = json_decode($this->raw($this->url($path, ['range' => $range])), true);
+
+ if (! is_array($rows) || $rows === []) {
+ return collect();
+ }
+
+ return collect($rows)->map(fn ($r) => TrafficSeriesBucketData::fromSentinel($r));
+ }
+
public function apps(): array
{
return json_decode($this->raw($this->url('/traffic/apps')), true) ?? [];
diff --git a/bootstrap/helpers/proxy.php b/bootstrap/helpers/proxy.php
index 3fb4c7831c..b67e2d2980 100644
--- a/bootstrap/helpers/proxy.php
+++ b/bootstrap/helpers/proxy.php
@@ -23,6 +23,11 @@ function traefikAccessLogCommands(bool $enabled): array
'--accesslog.fields.headers.names.Cf-Cache-Status=keep',
'--accesslog.fields.headers.names.Cf-Verified-Bot=keep',
'--accesslog.fields.headers.names.Cf-Ray=keep',
+ // Kept so Sentinel can resolve the real client IP behind a non-Cloudflare
+ // reverse proxy (leftmost X-Forwarded-For entry) and report User-Agents/referrers.
+ '--accesslog.fields.headers.names.X-Forwarded-For=keep',
+ '--accesslog.fields.headers.names.User-Agent=keep',
+ '--accesslog.fields.headers.names.Referer=keep',
];
}
@@ -342,15 +347,16 @@ function generateDefaultProxyConfiguration(Server $server, array $custom_command
if (isDev()) {
$config['services']['traefik']['command'][] = '--api.insecure=true';
$config['services']['traefik']['command'][] = '--log.level=debug';
- $config['services']['traefik']['command'][] = '--accesslog.filepath=/traefik/access.log';
$config['services']['traefik']['command'][] = '--accesslog.bufferingsize=100';
$config['services']['traefik']['volumes'][] = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/:/traefik';
} else {
$config['services']['traefik']['command'][] = '--api.insecure=false';
$config['services']['traefik']['volumes'][] = "{$proxy_path}:/traefik";
- foreach (traefikAccessLogCommands($server->isTrafficAnalyticsEnabled()) as $cmd) {
- $config['services']['traefik']['command'][] = $cmd;
- }
+ }
+ // Access logging + analytics header capture (JSON log, real-IP/UA/referrer headers)
+ // applies to both dev and production so traffic analytics can be exercised locally.
+ foreach (traefikAccessLogCommands($server->isTrafficAnalyticsEnabled()) as $cmd) {
+ $config['services']['traefik']['command'][] = $cmd;
}
if ($server->isSwarm()) {
data_forget($config, 'services.traefik.container_name');
diff --git a/bootstrap/helpers/shared.php b/bootstrap/helpers/shared.php
index 6fed29d67b..15cee733f2 100644
--- a/bootstrap/helpers/shared.php
+++ b/bootstrap/helpers/shared.php
@@ -4799,6 +4799,79 @@ function countryFlagEmoji(?string $a2): string
return $flag;
}
+/**
+ * Resolve an ISO 3166-1 alpha-2 code to a flag image URL (flagcdn.com).
+ *
+ * Emoji flags do not render on most Linux/Windows browsers, so the analytics
+ * views render an <img> instead. Returns null for null/invalid codes so callers
+ * can fall back to a globe icon.
+ */
+function countryFlagUrl(?string $a2, string $size = '24x18'): ?string
+{
+ if (! is_string($a2)) {
+ return null;
+ }
+
+ $code = strtolower(trim($a2));
+
+ if (preg_match('/^[a-z]{2}$/', $code) !== 1) {
+ return null;
+ }
+
+ return "https://flagcdn.com/{$size}/{$code}.png";
+}
+
+/**
+ * Extract the bare host from a referer value (full URL or bare host), dropping
+ * a leading "www.". Returns null when there is no usable host (e.g. direct hits).
+ */
+function refererHost(?string $referer): ?string
+{
+ if (! is_string($referer) || trim($referer) === '') {
+ return null;
+ }
+
+ $referer = trim($referer);
+ $withScheme = str_contains($referer, '://') ? $referer : 'http://'.$referer;
+ $host = parse_url($withScheme, PHP_URL_HOST) ?: null;
+
+ if (! $host) {
+ return null;
+ }
+
+ $host = strtolower($host);
+
+ return str_starts_with($host, 'www.') ? substr($host, 4) : $host;
+}
+
+/**
+ * Favicon URL for a host, served by DuckDuckGo's icon proxy (no API key, no
+ * hotlink-referrer leakage). Used to decorate referrer rows in analytics.
+ */
+function refererFaviconUrl(string $host): string
+{
+ return 'https://icons.duckduckgo.com/ip3/'.rawurlencode($host).'.ico';
+}
+
+/**
+ * Map Sentinel's lowercase woothee device category to a friendly, capitalized
+ * label (e.g. "pc" -> "Desktop", "smartphone" -> "Mobile").
+ */
+function deviceLabel(?string $device): string
+{
+ $value = strtolower(trim((string) $device));
+
+ return match ($value) {
+ '' => 'Unknown',
+ 'pc' => 'Desktop',
+ 'smartphone' => 'Mobile',
+ 'mobilephone' => 'Mobile',
+ 'appliance' => 'Appliance',
+ 'crawler' => 'Bot',
+ default => Str::title($value),
+ };
+}
+
/**
* Resolve an ISO 3166-1 alpha-2 country code to its English country name.
*
diff --git a/resources/views/components/application/configuration-sidebar.blade.php b/resources/views/components/application/configuration-sidebar.blade.php
index 34c1880783..7c92362ec5 100644
--- a/resources/views/components/application/configuration-sidebar.blade.php
+++ b/resources/views/components/application/configuration-sidebar.blade.php
@@ -159,7 +159,7 @@
'Resource Limits' => 'cpu',
'Resource Operations' => 'server-update',
'Metrics' => 'graph',
- 'Analytics' => 'network',
+ 'Analytics' => 'analytics',
'Tags' => 'tags',
'Danger Zone' => 'shield-alert',
];
diff --git a/resources/views/components/forms/listbox.blade.php b/resources/views/components/forms/listbox.blade.php
index 531d32660c..3ae5f4bedc 100644
--- a/resources/views/components/forms/listbox.blade.php
+++ b/resources/views/components/forms/listbox.blade.php
@@ -52,7 +52,7 @@
return found ? found.label : @js($placeholder);
},
choose(option) {
- if (option.disabled) return;
+ if (option.header || option.disabled) return;
this.open = false;
if (String(option.value) === String(this.value)) return;
this.value = option.value;
@@ -123,16 +123,27 @@
{{ $emptyText }}
</div>
<template x-for="option in options" :key="String(option.value)">
- <button type="button" class="listbox-option" role="option"
- :class="{ 'listbox-option-disabled': option.disabled }"
- :aria-selected="String(option.value) === String(value)" @click="choose(option)">
- <span class="truncate" x-text="option.label"></span>
- <svg x-show="String(option.value) === String(value)" xmlns="http://www.w3.org/2000/svg"
- fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"
- class="size-3.5 shrink-0">
- <path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
- </svg>
- </button>
+ <div>
+ {{-- Non-selectable group header (options with header: true). Each header is the
+ only child of its x-for wrapper, so `first:` can't target it — the divider
+ is an unconditional top border, which reads as a separator between groups. --}}
+ <template x-if="option.header">
+ <div class="mt-1 border-t border-neutral-100 px-3 pt-2 pb-1 text-[10px] font-semibold tracking-wide text-neutral-400 uppercase dark:border-white/[0.06] dark:text-fg-faint"
+ x-text="option.label"></div>
+ </template>
+ <template x-if="!option.header">
+ <button type="button" class="listbox-option" role="option"
+ :class="{ 'listbox-option-disabled': option.disabled }"
+ :aria-selected="String(option.value) === String(value)" @click="choose(option)">
+ <span class="truncate" x-text="option.label"></span>
+ <svg x-show="String(option.value) === String(value)" xmlns="http://www.w3.org/2000/svg"
+ fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"
+ class="size-3.5 shrink-0">
+ <path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
+ </svg>
+ </button>
+ </template>
+ </div>
</template>
</div>
</template>
@@ -149,16 +160,25 @@
{{ $emptyText }}
</div>
<template x-for="option in options" :key="String(option.value)">
- <button type="button" class="listbox-option" role="option"
- :class="{ 'listbox-option-disabled': option.disabled }"
- :aria-selected="String(option.value) === String(value)" @click="choose(option)">
- <span class="truncate" x-text="option.label"></span>
- <svg x-show="String(option.value) === String(value)" xmlns="http://www.w3.org/2000/svg"
- fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"
- class="size-3.5 shrink-0">
- <path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
- </svg>
- </button>
+ <div>
+ {{-- Non-selectable group header (options with header: true). --}}
+ <template x-if="option.header">
+ <div class="mt-1 border-t border-neutral-100 px-3 pt-2 pb-1 text-[10px] font-semibold tracking-wide text-neutral-400 uppercase dark:border-white/[0.06] dark:text-fg-faint"
+ x-text="option.label"></div>
+ </template>
+ <template x-if="!option.header">
+ <button type="button" class="listbox-option" role="option"
+ :class="{ 'listbox-option-disabled': option.disabled }"
+ :aria-selected="String(option.value) === String(value)" @click="choose(option)">
+ <span class="truncate" x-text="option.label"></span>
+ <svg x-show="String(option.value) === String(value)" xmlns="http://www.w3.org/2000/svg"
+ fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"
+ class="size-3.5 shrink-0">
+ <path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
+ </svg>
+ </button>
+ </template>
+ </div>
</template>
</div>
@endif
diff --git a/resources/views/components/navbar.blade.php b/resources/views/components/navbar.blade.php
index e9cb6e4c26..5e160532d4 100644
--- a/resources/views/components/navbar.blade.php
+++ b/resources/views/components/navbar.blade.php
@@ -87,6 +87,14 @@
<span class="menu-item-label" :class="collapsed && 'lg:hidden'">Projects</span>
</a>
</li>
+ <li>
+ <a title="Analytics" {{ wireNavigate() }}
+ class="{{ request()->is('analytics') ? 'menu-item menu-item-active' : 'menu-item' }}"
+ :class="collapsed && 'lg:justify-center lg:px-0'" href="{{ route('analytics') }}">
+ <x-reicon name="analytics" class="menu-item-icon" />
+ <span class="menu-item-label" :class="collapsed && 'lg:hidden'">Analytics</span>
+ </a>
+ </li>
@can('canAccessTerminal')
<li>
<a title="Terminal"
diff --git a/resources/views/components/reicon.blade.php b/resources/views/components/reicon.blade.php
index d02fd2af9d..5d3fe5f9c6 100644
--- a/resources/views/components/reicon.blade.php
+++ b/resources/views/components/reicon.blade.php
@@ -8,6 +8,7 @@
$icons = [
'cloud' => '<path d="M7.5 19.25h9.75a4.5 4.5 0 0 0 .62-8.96A6.25 6.25 0 0 0 5.8 8.65 5.25 5.25 0 0 0 7.5 19.25Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>',
'code' => '<path d="m8.5 7-5 5 5 5M15.5 7l5 5-5 5M13.5 4l-3 16" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>',
+ 'analytics' => '<path d="M5 3v14a2 2 0 0 0 2 2h14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M9 17v-3.5M13 17v-7M17 17v-10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>',
'mail' => '<path fill-rule="evenodd" clip-rule="evenodd" d="M5.5 3.25h13A4.25 4.25 0 0 1 22.75 7.5v9a4.25 4.25 0 0 1-4.25 4.25h-13A4.25 4.25 0 0 1 1.25 16.5v-9A4.25 4.25 0 0 1 5.5 3.25Zm-2.75 4.5v8.75a2.75 2.75 0 0 0 2.75 2.75h13a2.75 2.75 0 0 0 2.75-2.75V7.75l-6.6 5.13a4.25 4.25 0 0 1-5.3 0l-6.6-5.13Zm18.4-1.3A2.75 2.75 0 0 0 18.5 4.75h-13a2.75 2.75 0 0 0-2.65 1.7l7.42 5.77a2.75 2.75 0 0 0 3.46 0l7.42-5.77Z" fill="currentColor"/>',
'dashboard' => '<path d="M9 17.25C8.58579 17.25 8.25 17.5858 8.25 18C8.25 18.4142 8.58579 18.75 9 18.75H15C15.4142 18.75 15.75 18.4142 15.75 18C15.75 17.5858 15.4142 17.25 15 17.25H9Z" fill="currentColor"/><path fill-rule="evenodd" clip-rule="evenodd" d="M12 1.25C11.2919 1.25 10.6485 1.45282 9.95055 1.79224C9.27585 2.12035 8.49642 2.60409 7.52286 3.20832L5.45628 4.4909C4.53509 5.06261 3.79744 5.5204 3.2289 5.95581C2.64015 6.40669 2.18795 6.86589 1.86131 7.46263C1.53535 8.05812 1.38857 8.69174 1.31819 9.4407C1.24999 10.1665 1.24999 11.0541 1.25 12.1672V13.7799C1.24999 15.6837 1.24998 17.1866 1.4027 18.3616C1.55937 19.567 1.88856 20.5401 2.63236 21.3094C3.37958 22.0824 4.33046 22.4277 5.50761 22.5914C6.64849 22.75 8.10556 22.75 9.94185 22.75H14.0581C15.8944 22.75 17.3515 22.75 18.4924 22.5914C19.6695 22.4277 20.6204 22.0824 21.3676 21.3094C22.1114 20.5401 22.4406 19.567 22.5973 18.3616C22.75 17.1866 22.75 15.6838 22.75 13.7799V12.1672C22.75 11.0541 22.75 10.1665 22.6818 9.4407C22.6114 8.69174 22.4646 8.05812 22.1387 7.46263C21.8121 6.86589 21.3599 6.40669 20.7711 5.95581C20.2026 5.5204 19.4649 5.06262 18.5437 4.49091L16.4771 3.20831C15.5036 2.60409 14.7241 2.12034 14.0494 1.79224C13.3515 1.45282 12.7081 1.25 12 1.25ZM8.27953 4.50412C9.29529 3.87371 10.0095 3.43153 10.6065 3.1412C11.1882 2.85833 11.6002 2.75 12 2.75C12.3998 2.75 12.8118 2.85833 13.3935 3.14119C13.9905 3.43153 14.7047 3.87371 15.7205 4.50412L17.7205 5.74537C18.6813 6.34169 19.3559 6.76135 19.8591 7.1467C20.3487 7.52164 20.6303 7.83106 20.8229 8.18285C21.0162 8.53589 21.129 8.94865 21.1884 9.58104C21.2492 10.2286 21.25 11.0458 21.25 12.2039V13.725C21.25 15.6959 21.2485 17.1012 21.1098 18.1683C20.9736 19.2163 20.717 19.8244 20.2892 20.2669C19.8649 20.7058 19.2871 20.9664 18.2858 21.1057C17.2602 21.2483 15.9075 21.25 14 21.25H10C8.09247 21.25 6.73983 21.2483 5.71422 21.1057C4.71286 20.9664 4.13514 20.7058 3.71079 20.2669C3.28301 19.8244 3.02642 19.2163 2.89019 18.1683C2.75149 17.1012 2.75 15.6959 2.75 13.725V12.2039C2.75 11.0458 2.75076 10.2286 2.81161 9.58104C2.87103 8.94865 2.98385 8.53589 3.17709 8.18285C3.36965 7.83106 3.65133 7.52164 4.14092 7.1467C4.6441 6.76135 5.31869 6.34169 6.27953 5.74537L8.27953 4.50412Z" fill="currentColor"/>',
'projects' => '<path d="M5 10H7C9 10 10 9 10 7V5C10 3 9 2 7 2H5C3 2 2 3 2 5V7C2 9 3 10 5 10Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/><path d="M17 10H19C21 10 22 9 22 7V5C22 3 21 2 19 2H17C15 2 14 3 14 5V7C14 9 15 10 17 10Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/><path d="M17 22H19C21 22 22 21 22 19V17C22 15 21 14 19 14H17C15 14 14 15 14 17V19C14 21 15 22 17 22Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 22H7C9 22 10 21 10 19V17C10 15 9 14 7 14H5C3 14 2 15 2 17V19C2 21 3 22 5 22Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>',
diff --git a/resources/views/components/server/sidebar.blade.php b/resources/views/components/server/sidebar.blade.php
index d6f45d2ba3..d0254054be 100644
--- a/resources/views/components/server/sidebar.blade.php
+++ b/resources/views/components/server/sidebar.blade.php
@@ -129,14 +129,6 @@
'group' => 'Operations',
'visible' => $server->isFunctional(),
],
- [
- 'label' => 'Analytics',
- 'route' => 'server.analytics',
- 'active' => $activeMenu === 'analytics',
- 'icon' => 'graph',
- 'group' => 'Operations',
- 'visible' => $server->isFunctional(),
- ],
[
'label' => 'Security',
'route' => 'server.security.patches',
diff --git a/resources/views/livewire/analytics.blade.php b/resources/views/livewire/analytics.blade.php
new file mode 100644
index 0000000000..6d551658b7
--- /dev/null
+++ b/resources/views/livewire/analytics.blade.php
@@ -0,0 +1,259 @@
+<?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 = [
+ 'referer' => 'Referrers',
+ 'browser' => 'Browsers',
+ 'os' => 'Operating systems',
+ 'device' => 'Devices',
+];
+
+$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>';
+
+$serverListboxOptions = array_merge(
+ [['value' => '', 'label' => 'All servers']],
+ collect($serverOptions)->map(fn ($name, $uuid) => ['value' => $uuid, 'label' => $name])->values()->all(),
+);
+$appListboxOptions = array_merge(
+ [['value' => '', 'label' => 'All applications']],
+ $appGroupedOptions,
+);
+?>
+<div class="flex w-full min-w-0 flex-col gap-6">
+ <x-slot:title>
+ Analytics | Coolify
+ </x-slot>
+
+ {{-- Header --}}
+ <div class="flex flex-col gap-4">
+ <div class="flex items-center gap-3">
+ <span class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-600 dark:bg-white/[0.06] dark:text-fg-dim">
+ <x-reicon name="analytics" class="size-5" />
+ </span>
+ <div class="min-w-0">
+ <h1 class="text-[16px]! leading-5! font-semibold! text-black dark:text-fg">Analytics</h1>
+ <p class="mt-0.5 text-[12px] text-neutral-500 dark:text-fg-faint">
+ Request traffic across every application and server, reported by Sentinel.
+ </p>
+ </div>
+ </div>
+
+ @if ($servers->isNotEmpty() && $overview)
+ <div class="flex flex-wrap items-center gap-2">
+ <div class="w-full sm:w-52">
+ <x-forms.listbox id="serverUuid" live :options="$serverListboxOptions" placeholder="All servers" />
+ </div>
+ {{-- Re-key on the server filter so the application listbox re-initializes with the
+ newly-scoped options (and reset value) instead of showing stale Alpine state. --}}
+ <div class="w-full sm:w-52" wire:key="app-filter-{{ $serverUuid }}">
+ <x-forms.listbox id="appUuid" live :options="$appListboxOptions" placeholder="All applications" />
+ </div>
+
+ <div class="flex items-center gap-2 sm:ml-auto">
+ @include('livewire.traffic._live-toggle')
+ <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>
+ </div>
+ </div>
+ @endif
+ </div>
+
+ {{-- Nudge: enabled-eligible servers that haven't turned traffic analytics on yet. --}}
+ @if (! empty($eligibleDisabledServers))
+ <div x-data="{ dismissed: localStorage.getItem('traffic-nudge-{{ $nudgeKey }}') === '1' }" x-show="!dismissed" x-cloak
+ class="flex items-start gap-3 rounded-xl border border-neutral-200 bg-white px-4 py-3 shadow-sm dark:border-white/[0.08] dark:bg-white/[0.025]">
+ <div class="min-w-0 flex-1">
+ <p class="text-[12px] font-semibold text-black dark:text-fg">
+ {{ count($eligibleDisabledServers) === 1 ? '1 server can start collecting traffic analytics' : count($eligibleDisabledServers).' servers can start collecting traffic analytics' }}
+ </p>
+ <p class="mt-0.5 text-[11px] text-neutral-500 dark:text-fg-dim">
+ Enabling regenerates the proxy config and restarts the proxy + Sentinel (a brief blip).
+ Works with Traefik &amp; Caddy.
+ </p>
+ </div>
+ <div class="flex shrink-0 items-center gap-2">
+ @if (count($eligibleDisabledServers) === 1)
+ <a class="button" href="{{ route('server.sentinel', ['server_uuid' => $eligibleDisabledServers[0]['uuid']]) }}" {{ wireNavigate() }}>
+ Enable on {{ \Illuminate\Support\Str::limit($eligibleDisabledServers[0]['name'], 16) }}
+ </a>
+ @else
+ <a class="button" href="{{ route('server.index') }}" {{ wireNavigate() }}>
+ View servers
+ </a>
+ @endif
+ <button type="button" title="Dismiss"
+ @click="dismissed = true; localStorage.setItem('traffic-nudge-{{ $nudgeKey }}', '1')"
+ class="flex h-6 w-6 items-center justify-center rounded-md text-neutral-400 transition-colors hover:text-black dark:text-fg-faint dark:hover:text-fg">
+ <svg class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
+ <path stroke-linecap="round" stroke-linejoin="round" d="M6 6l12 12M6 18L18 6" />
+ </svg>
+ </button>
+ </div>
+ </div>
+ @endif
+
+ @if ($servers->isEmpty())
+ <x-empty size="sm" title="Traffic analytics is not enabled"
+ description="Enable Sentinel traffic analytics on a server to see request analytics here."
+ icon-name="analytics">
+ <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 filters and range. Try a different range or check back shortly."
+ icon-name="analytics" />
+ @else
+ @if ($this->isLivePollable())
+ <div wire:poll.60s="loadData" class="hidden"></div>
+ @endif
+
+ {{-- KPIs --}}
+ <x-application.settings-section id="analytics-overview-section" title="Overview"
+ helper="Aggregate request volume for the selected filters and range.">
+ <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; 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; 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>
+ </x-application.settings-section>
+
+ {{-- Traffic over time (stacked area), or a status donut when Sentinel lacks /traffic/series. --}}
+ <x-application.settings-section id="analytics-status-section" title="Traffic"
+ helper="Request volume by status class over time for the selected range.">
+ @include('livewire.traffic._status-chart')
+ </x-application.settings-section>
+
+ {{-- Top applications + Top paths side by side (paths span full width when filtered to one app). --}}
+ <div @class(['grid grid-cols-1 gap-6', 'lg:grid-cols-2' => $appUuid === ''])>
+ @if ($appUuid === '')
+ <x-application.settings-section id="analytics-apps-section" title="Top applications"
+ helper="Applications ranked by request volume. Open one for its analytics." flush>
+ @if (empty($topApps))
+ <x-empty size="sm" title="No application data"
+ description="No per-application requests were recorded for the selected range."
+ icon-name="unordered-list" />
+ @else
+ <div x-data="{ page: 0, per: 10, total: {{ count($topApps) }} }">
+ @foreach ($topApps as $row)
+ @php $appHref = $row['link'] ?? null; @endphp
+ <{{ $appHref ? 'a' : 'div' }} wire:key="analytics-app-{{ $row['uuid'] }}"
+ @if ($appHref) href="{{ $appHref }}" {{ wireNavigate() }} @endif
+ x-show="{{ $loop->index }} >= page * per && {{ $loop->index }} < (page + 1) * per"
+ @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]',
+ 'transition-colors hover:bg-neutral-50 dark:hover:bg-white/[0.03]' => $appHref,
+ ])>
+ <span class="flex min-w-0 flex-1 items-baseline gap-1.5">
+ <span class="truncate text-[12px] text-black dark:text-fg">{{ $row['name'] }}</span>
+ @if (! empty($row['domain']))
+ <span class="hidden truncate text-[11px] text-neutral-400 sm:inline dark:text-fg-faint">{{ $row['domain'] }}</span>
+ @endif
+ </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>
+ @if ($appHref)
+ <svg class="size-3.5 shrink-0 text-neutral-300 dark:text-fg-faint" viewBox="0 0 24 24"
+ fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
+ <path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
+ </svg>
+ @endif
+ </{{ $appHref ? 'a' : 'div' }}>
+ @endforeach
+ @include('livewire.traffic._pager')
+ </div>
+ @endif
+ </x-application.settings-section>
+ @endif
+
+ <x-application.settings-section id="analytics-paths-section" title="Top paths"
+ helper="Most requested paths for the selected range." flush>
+ @include('livewire.traffic._paths-list', ['paths' => $topPaths])
+ </x-application.settings-section>
+ </div>
+
+ {{-- Countries --}}
+ <x-application.settings-section id="analytics-country-section" title="Countries"
+ helper="Request volume by visitor country for the selected range." flush>
+ @include('livewire.traffic._geo', [
+ 'countries' => data_get($breakdowns, 'country', []),
+ 'attribution' => $attribution,
+ ])
+ </x-application.settings-section>
+
+ {{-- Referrers / browsers / OS / devices / AI agents, two per row. --}}
+ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
+ @foreach ($dimensionLabels as $dimension => $label)
+ @include('livewire.traffic._breakdown-section', [
+ 'dimension' => $dimension,
+ 'label' => $label,
+ 'rows' => data_get($breakdowns, $dimension, []),
+ ])
+ @endforeach
+ @include('livewire.traffic._breakdown-section', [
+ 'dimension' => 'agent',
+ 'label' => 'AI agents & bots',
+ 'rows' => data_get($breakdowns, 'agent', []),
+ 'helper' => 'Bot and AI-crawler traffic (GPTBot, ClaudeBot, Googlebot, …) by request count.',
+ ])
+ @include('livewire.traffic._breakdown-section', [
+ 'dimension' => 'ip',
+ 'label' => 'Top IPs',
+ 'rows' => data_get($breakdowns, 'ip', []),
+ 'helper' => 'Busiest client IPs (real visitor IP, resolved behind Cloudflare / reverse proxies).',
+ ])
+ </div>
+
+ {{-- User agents (full width — raw UA strings are long). --}}
+ @include('livewire.traffic._breakdown-section', [
+ 'dimension' => 'useragent',
+ 'label' => 'Top user agents',
+ 'rows' => data_get($breakdowns, 'useragent', []),
+ 'helper' => 'Most frequent raw User-Agent strings for the selected range.',
+ ])
+ @endif
+</div>
diff --git a/resources/views/livewire/project/application/analytics.blade.php b/resources/views/livewire/project/application/analytics.blade.php
index dc3bbcd07c..2362346eba 100644
--- a/resources/views/livewire/project/application/analytics.blade.php
+++ b/resources/views/livewire/project/application/analytics.blade.php
@@ -86,94 +86,14 @@ $analyticsServerUuid = $application->destination?->server?->uuid;
</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 cssVar = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
- const statusColors = () => [
- cssVar('--chart-status-2xx'),
- cssVar('--chart-status-3xx'),
- cssVar('--chart-status-4xx'),
- cssVar('--chart-status-5xx'),
- ];
-
- 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 id="analytics-status-section" title="Traffic"
+ helper="Request volume by status class over time for the selected range.">
+ @include('livewire.traffic._status-chart')
</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
+ @include('livewire.traffic._paths-list', ['paths' => $topPaths])
</x-application.settings-section>
<x-application.settings-section id="analytics-country-section" title="Countries"
@@ -184,21 +104,35 @@ $analyticsServerUuid = $application->destination?->server?->uuid;
])
</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
- </x-application.settings-section>
- @endforeach
+ {{-- Referrers / browsers / OS / devices / AI agents, two per row. --}}
+ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
+ @foreach ($dimensionLabels as $dimension => $label)
+ @include('livewire.traffic._breakdown-section', [
+ 'dimension' => $dimension,
+ 'label' => $label,
+ 'rows' => data_get($breakdowns, $dimension, []),
+ ])
+ @endforeach
+ @include('livewire.traffic._breakdown-section', [
+ 'dimension' => 'agent',
+ 'label' => 'AI agents & bots',
+ 'rows' => data_get($breakdowns, 'agent', []),
+ 'helper' => 'Bot and AI-crawler traffic (GPTBot, ClaudeBot, Googlebot, …) by request count.',
+ ])
+ @include('livewire.traffic._breakdown-section', [
+ 'dimension' => 'ip',
+ 'label' => 'Top IPs',
+ 'rows' => data_get($breakdowns, 'ip', []),
+ 'helper' => 'Busiest client IPs (real visitor IP, resolved behind Cloudflare / reverse proxies).',
+ ])
+ </div>
+
+ {{-- User agents (full width — raw UA strings are long). --}}
+ @include('livewire.traffic._breakdown-section', [
+ 'dimension' => 'useragent',
+ 'label' => 'Top user agents',
+ 'rows' => data_get($breakdowns, 'useragent', []),
+ 'helper' => 'Most frequent raw User-Agent strings for the selected range.',
+ ])
@endif
</div>
diff --git a/resources/views/livewire/server/analytics.blade.php b/resources/views/livewire/server/analytics.blade.php
deleted file mode 100644
index 33c77df9e7..0000000000
--- a/resources/views/livewire/server/analytics.blade.php
+++ /dev/null
@@ -1,254 +0,0 @@
-<?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 = [
- 'referer' => 'Referrers',
- 'browser' => 'Browsers',
- 'os' => 'Operating systems',
- 'device' => 'Devices',
-];
-?>
-<div>
- <x-slot:title>
- {{ data_get_str($server, 'name')->limit(10) }} > Analytics | Coolify
- </x-slot>
-
- <livewire:server.navbar :server="$server" />
-
- <div
- class="server-settings-workspace application-settings-workspace mt-4 grid w-full max-w-[1180px] min-w-0 gap-8 lg:mt-0 xl:grid-cols-[210px_minmax(0,1fr)] xl:gap-10">
- <x-server.sidebar :server="$server" activeMenu="analytics" />
-
- <div class="application-settings-form flex w-full flex-col gap-6">
- @if (! $enabled)
- <x-application.settings-section id="analytics-section" title="Analytics"
- helper="Inspect traffic statistics reported by Sentinel across all applications on this server.">
- <x-slot:actions>
- <a class="button" href="{{ route('server.sentinel', ['server_uuid' => $server->uuid]) }}"
- {{ wireNavigate() }}>
- Server settings
- <x-external-link />
- </a>
- </x-slot:actions>
-
- <div class="flex flex-col gap-4 px-4 py-4">
- <div class="flex flex-col gap-1">
- <h3 class="text-[13px] font-semibold text-black dark:text-fg">
- Turn on traffic analytics for this server
- </h3>
- <p class="text-[12px] text-neutral-500 dark:text-fg-dim">
- See request volume, status codes, top paths, and visitor geography for every
- application on this server. Here's exactly what enabling does:
- </p>
- </div>
-
- @include('livewire.traffic._enable-benefits')
-
- @if ($this->isEligibleForTrafficAnalytics())
- <div>
- <button type="button" wire:click="enableTrafficAnalytics" class="button"
- wire:loading.attr="disabled" wire:target="enableTrafficAnalytics">
- <span wire:loading.remove wire:target="enableTrafficAnalytics">Enable traffic analytics</span>
- <span wire:loading wire:target="enableTrafficAnalytics">Enabling…</span>
- </button>
- </div>
- @else
- <p class="text-[12px] font-medium text-amber-600 dark:text-amber-400">
- Traffic analytics is not available on Swarm or Build-pack servers.
- </p>
- @endif
- </div>
- </x-application.settings-section>
- @elseif (! $overview)
- <x-application.settings-section id="analytics-section" title="Analytics"
- helper="Inspect traffic statistics reported by Sentinel across all applications on this server.">
- <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
- @if ($this->isLivePollable())
- <div wire:poll.60s="loadData" class="hidden"></div>
- @endif
-
- <x-application.settings-section id="analytics-range-section" title="Analytics"
- helper="Inspect traffic statistics reported by Sentinel across all applications on this server.">
- <x-slot:actions>
- <div class="flex items-center gap-2">
- @include('livewire.traffic._live-toggle')
- <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>
- </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 cssVar = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
- const statusColors = () => [
- cssVar('--chart-status-2xx'),
- cssVar('--chart-status-3xx'),
- cssVar('--chart-status-4xx'),
- cssVar('--chart-status-5xx'),
- ];
-
- 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-leaderboard-section" title="Top applications"
- helper="Applications on this server ranked by request volume for the selected range." flush>
- @forelse ($leaderboard as $row)
- <div wire:key="analytics-leaderboard-{{ $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
- </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>
-
- <x-application.settings-section id="analytics-country-section" title="Countries"
- helper="Request volume by visitor country for the selected range." flush>
- @include('livewire.traffic._geo', [
- 'countries' => data_get($breakdowns, 'country', []),
- 'attribution' => $attribution,
- ])
- </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
- </x-application.settings-section>
- @endforeach
- @endif
- </div>
- </div>
-</div>
diff --git a/resources/views/livewire/traffic/_breakdown-section.blade.php b/resources/views/livewire/traffic/_breakdown-section.blade.php
new file mode 100644
index 0000000000..e3d56bc453
--- /dev/null
+++ b/resources/views/livewire/traffic/_breakdown-section.blade.php
@@ -0,0 +1,54 @@
+{{--
+ One breakdown dimension rendered as a paginated settings-section. Handles the
+ per-dimension presentation: referrers get a DuckDuckGo favicon + an openable
+ external link (rel="noopener noreferrer nofollow", new tab), devices are mapped
+ to friendly capitalized labels, and Sentinel's `__other__` overflow bucket reads
+ as "Other". Expects `$dimension`, `$label`, `$rows` in scope; optional `$helper`.
+
+ @param string $dimension Sentinel dimension key (referer, device, agent, …)
+ @param string $label Section title
+ @param iterable $rows breakdown rows: ['value', 'requests', 'bytesOut']
+ @param ?string $helper optional section helper text
+--}}
+@php
+ $rows = $rows ?? [];
+ $helper = $helper ?? 'Top '.strtolower($label).' by request count for the selected range.';
+@endphp
+<x-application.settings-section id="analytics-{{ $dimension }}-section" :title="$label" :helper="$helper" flush>
+ @if (empty($rows))
+ <x-empty size="sm" title="No data"
+ description="No {{ strtolower($label) }} data for the selected range." icon-name="network" />
+ @else
+ <div x-data="{ page: 0, per: 10, total: {{ count($rows) }} }">
+ @foreach ($rows as $row)
+ @php
+ $value = (string) ($row['value'] ?? '');
+ $isOther = $value === '__other__';
+ $host = ! $isOther && $dimension === 'referer' ? refererHost($value) : null;
+ $display = $isOther
+ ? 'Other'
+ : match ($dimension) {
+ 'device' => deviceLabel($value),
+ 'referer' => $host ?? 'Direct / none',
+ default => $value !== '' ? $value : 'Unknown',
+ };
+ @endphp
+ <div wire:key="analytics-{{ $dimension }}-{{ $loop->index }}"
+ x-show="{{ $loop->index }} >= page * per && {{ $loop->index }} < (page + 1) * per"
+ 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]">
+ @if ($dimension === 'referer' && $host)
+ <img src="{{ refererFaviconUrl($host) }}" alt="" loading="lazy" width="16" height="16"
+ class="size-4 shrink-0 rounded-sm" onerror="this.style.visibility='hidden'">
+ <a href="https://{{ $host }}" target="_blank" rel="noopener noreferrer nofollow"
+ class="min-w-0 flex-1 truncate text-[12px] text-black hover:underline dark:text-fg">{{ $display }}</a>
+ @else
+ <span class="min-w-0 flex-1 truncate text-[12px] text-black dark:text-fg" title="{{ $display }}">{{ $display }}</span>
+ @endif
+ <span class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ number_format((int) ($row['requests'] ?? 0)) }} req</span>
+ <span class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ formatBytes((int) ($row['bytesOut'] ?? 0)) }}</span>
+ </div>
+ @endforeach
+ @include('livewire.traffic._pager')
+ </div>
+ @endif
+</x-application.settings-section>
diff --git a/resources/views/livewire/traffic/_enable-benefits.blade.php b/resources/views/livewire/traffic/_enable-benefits.blade.php
deleted file mode 100644
index df48dd3fed..0000000000
--- a/resources/views/livewire/traffic/_enable-benefits.blade.php
+++ /dev/null
@@ -1,23 +0,0 @@
-{{--
- Shared explainer for what enabling traffic analytics actually does. Kept in one
- place so the server analytics nudge, the dashboard nudge, and the application
- General-page nudge stay consistent about the side effects (proxy + Sentinel restart).
---}}
-<ul class="flex flex-col gap-1.5 text-[12px] text-neutral-600 dark:text-fg-dim">
- <li class="flex items-start gap-2">
- <span class="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-neutral-400 dark:bg-fg-faint"></span>
- <span>Regenerates the proxy config and <span class="font-medium text-black dark:text-fg">restarts the proxy</span> (a brief blip for in-flight connections).</span>
- </li>
- <li class="flex items-start gap-2">
- <span class="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-neutral-400 dark:bg-fg-faint"></span>
- <span><span class="font-medium text-black dark:text-fg">Restarts Sentinel</span> and mounts a <span class="font-medium text-black dark:text-fg">read-only</span> access-log volume.</span>
- </li>
- <li class="flex items-start gap-2">
- <span class="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-neutral-400 dark:bg-fg-faint"></span>
- <span>Adds <span class="font-medium text-black dark:text-fg">visitor geography</span> — which countries your traffic comes from.</span>
- </li>
- <li class="flex items-start gap-2">
- <span class="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-neutral-400 dark:bg-fg-faint"></span>
- <span>Works with <span class="font-medium text-black dark:text-fg">Traefik &amp; Caddy</span>; not available on Swarm or Build-pack servers.</span>
- </li>
-</ul>
diff --git a/resources/views/livewire/traffic/_geo.blade.php b/resources/views/livewire/traffic/_geo.blade.php
index 2ee292c333..60d8b01253 100644
--- a/resources/views/livewire/traffic/_geo.blade.php
+++ b/resources/views/livewire/traffic/_geo.blade.php
@@ -1,10 +1,10 @@
{{--
Shared geo visualization for traffic analytics: an inline public-domain world
- choropleth (see _world-map.blade.php) plus a ranked country list. Driven by the
- `country` breakdown collection; each row is ['value' => ISO-A2, 'requests', 'bytesOut'].
- Colors come from the --chart-geo-* tokens (light + dark) so the map, bars, and
- legend share one source. Consumed by the server + application analytics views and
- the dashboard summary.
+ choropleth (see _world-map.blade.php) plus a ranked, paginated country list.
+ Driven by the `country` breakdown collection; each row is
+ ['value' => ISO-A2, 'requests', 'bytesOut']. Colors come from the --chart-geo-*
+ tokens (light + dark) so the map, bars, and legend share one source. Consumed by
+ the server, application and global analytics views and the dashboard summary.
@param iterable $countries country-breakdown rows
@param ?string $attribution optional Sentinel attribution note
@@ -33,6 +33,16 @@
$bucketMap[$r['value']] = min(5, max(1, $bucket));
}
+ // Per-country payload for the map hover tooltip, keyed by ISO-A2.
+ $geoTip = [];
+ foreach ($known as $r) {
+ $geoTip[$r['value']] = [
+ 'name' => countryName($r['value']),
+ 'requests' => $r['requests'],
+ 'bytesOut' => formatBytes($r['bytesOut']),
+ ];
+ }
+
$countryRows = $known->values();
if ($unknown->isNotEmpty()) {
$countryRows->push([
@@ -56,7 +66,8 @@
icon-name="network" />
@else
{{-- Bucket fills are server-rendered as scoped CSS so theme + range changes stay
- in sync with no JS; the map subtree is wire:ignore'd to skip morph churn on polls. --}}
+ in sync with no JS; the map subtree is wire:ignore'd to skip morph churn on polls.
+ The :hover rule highlights whichever country is under the cursor. --}}
<style>
[data-geo-map="{{ $mapId }}"] svg { width: 100%; height: auto; display: block; }
[data-geo-map="{{ $mapId }}"] svg path {
@@ -64,40 +75,94 @@
stroke: var(--chart-geo-stroke);
stroke-width: 0.4;
stroke-linejoin: round;
+ transition: filter 0.1s ease;
+ }
+ [data-geo-map="{{ $mapId }}"] svg path:hover {
+ filter: brightness(1.25);
+ stroke: var(--chart-geo-stroke);
+ stroke-width: 0.9;
+ cursor: default;
}
@foreach ($bucketMap as $a2 => $bucket)
[data-geo-map="{{ $mapId }}"] svg path#{{ $a2 }} { fill: var(--chart-geo-{{ $bucket }}); }
@endforeach
</style>
- <div class="border-b border-neutral-200 px-4 py-3 dark:border-white/[0.07]">
+ {{-- Alpine reads the fresh tooltip payload from a morph-updated JSON node on each
+ move (rather than a one-time x-data literal) so it stays in sync after polls. --}}
+ <div class="relative border-b border-neutral-200 px-4 py-3 dark:border-white/[0.07]"
+ x-data="{
+ tip: { show: false, x: 0, y: 0, name: '', requests: '', bytes: '' },
+ move(e) {
+ const path = e.target.closest('path');
+ if (!path || !path.id) { this.tip.show = false; return; }
+ let data = {};
+ try { data = JSON.parse(this.$refs.geodata.textContent || '{}'); } catch (_) {}
+ const d = data[path.id];
+ this.tip.name = d ? d.name : path.id;
+ this.tip.requests = d ? Number(d.requests).toLocaleString() : null;
+ this.tip.bytes = d ? d.bytesOut : null;
+ this.tip.x = e.clientX;
+ this.tip.y = e.clientY;
+ this.tip.show = true;
+ },
+ }" @mousemove="move($event)" @mouseleave="tip.show = false">
+ <script type="application/json" x-ref="geodata">{!! json_encode($geoTip, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) !!}</script>
+
<div data-geo-map="{{ $mapId }}" wire:ignore
- class="mx-auto max-w-[720px] overflow-hidden rounded-lg bg-neutral-50 dark:bg-white/[0.02]">
+ class="w-full overflow-hidden rounded-lg bg-neutral-50 dark:bg-white/[0.02]">
@include('livewire.traffic._world-map')
</div>
+
+ <div x-show="tip.show" x-cloak x-transition.opacity.duration.100ms
+ :style="`left: ${tip.x + 14}px; top: ${tip.y + 14}px;`"
+ class="pointer-events-none fixed z-[100] rounded-lg border border-neutral-700 bg-neutral-900 px-2.5 py-1.5 text-white shadow-lg dark:border-white/10 dark:bg-raised">
+ <div class="text-[12px] font-medium" x-text="tip.name"></div>
+ <template x-if="tip.requests !== null">
+ <div class="mt-0.5 text-[11px] text-neutral-300 dark:text-fg-dim">
+ <span x-text="tip.requests"></span> req · <span x-text="tip.bytes"></span>
+ </div>
+ </template>
+ <template x-if="tip.requests === null">
+ <div class="mt-0.5 text-[11px] text-neutral-400 dark:text-fg-faint">No requests in range</div>
+ </template>
+ </div>
</div>
- <div>
- @foreach ($countryRows as $row)
- @php
- $isUnknown = $row['value'] === '';
- $bucket = $isUnknown ? null : ($bucketMap[$row['value']] ?? 1);
- $width = min(100, round(($row['requests'] / $maxRequests) * 100, 1));
- $barColor = $isUnknown ? 'var(--chart-geo-empty)' : "var(--chart-geo-{$bucket})";
- @endphp
- <div wire:key="geo-country-{{ $mapId }}-{{ $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="shrink-0 text-[14px] leading-none" aria-hidden="true">{{ countryFlagEmoji($isUnknown ? null : $row['value']) }}</span>
- <span class="min-w-0 flex-1 truncate text-[12px] text-black dark:text-fg">
- {{ $isUnknown ? 'Unknown' : countryName($row['value']) }}
- </span>
- <div class="hidden h-1.5 w-24 shrink-0 overflow-hidden rounded-full bg-neutral-100 sm:block dark:bg-white/[0.06]">
- <div class="h-full rounded-full" style="width: {{ $width }}%; background-color: {{ $barColor }};"></div>
+ <div x-data="{ page: 0, per: 10, total: {{ $countryRows->count() }} }">
+ <div>
+ @foreach ($countryRows as $row)
+ @php
+ $isUnknown = $row['value'] === '';
+ $bucket = $isUnknown ? null : ($bucketMap[$row['value']] ?? 1);
+ $width = min(100, round(($row['requests'] / $maxRequests) * 100, 1));
+ $barColor = $isUnknown ? 'var(--chart-geo-empty)' : "var(--chart-geo-{$bucket})";
+ @endphp
+ <div wire:key="geo-country-{{ $mapId }}-{{ $loop->index }}"
+ x-show="{{ $loop->index }} >= page * per && {{ $loop->index }} < (page + 1) * per"
+ 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]">
+ @php $flagUrl = $isUnknown ? null : countryFlagUrl($row['value']); @endphp
+ @if ($flagUrl)
+ <img src="{{ $flagUrl }}" srcset="{{ countryFlagUrl($row['value'], '48x36') }} 2x" alt=""
+ loading="lazy" width="20" height="15"
+ class="h-[15px] w-5 shrink-0 rounded-[2px] object-cover ring-1 ring-black/5 dark:ring-white/10"
+ onerror="this.style.visibility='hidden'">
+ @else
+ <span class="shrink-0 text-[14px] leading-none" aria-hidden="true">🌐</span>
+ @endif
+ <span class="min-w-0 flex-1 truncate text-[12px] text-black dark:text-fg">
+ {{ $isUnknown ? 'Unknown' : countryName($row['value']) }}
+ </span>
+ <div class="hidden h-1.5 w-24 shrink-0 overflow-hidden rounded-full bg-neutral-100 sm:block dark:bg-white/[0.06]">
+ <div class="h-full rounded-full" style="width: {{ $width }}%; background-color: {{ $barColor }};"></div>
+ </div>
+ <span class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ number_format($row['requests']) }} req</span>
+ <span class="hidden shrink-0 text-[12px] text-neutral-500 sm:inline dark:text-fg-dim">{{ formatBytes($row['bytesOut']) }}</span>
</div>
- <span class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ number_format($row['requests']) }} req</span>
- <span class="hidden shrink-0 text-[12px] text-neutral-500 sm:inline dark:text-fg-dim">{{ formatBytes($row['bytesOut']) }}</span>
- </div>
- @endforeach
+ @endforeach
+ </div>
+
+ @include('livewire.traffic._pager')
@if (! empty($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">
diff --git a/resources/views/livewire/traffic/_pager.blade.php b/resources/views/livewire/traffic/_pager.blade.php
new file mode 100644
index 0000000000..73aa17cc9b
--- /dev/null
+++ b/resources/views/livewire/traffic/_pager.blade.php
@@ -0,0 +1,23 @@
+{{--
+ Client-side "top 10" pager footer for traffic lists. Expects an enclosing
+ Alpine scope that defines reactive `page` (0-based), `per` (page size) and
+ `total` (row count). Rows themselves are toggled with x-show on their index;
+ this partial only renders the summary + prev/next controls, and hides itself
+ when everything fits on one page.
+--}}
+<div x-show="total > per" x-cloak
+ class="flex items-center justify-between gap-3 border-t border-neutral-200 px-4 py-2 dark:border-white/[0.07]">
+ <span class="text-[11px] text-neutral-500 dark:text-fg-faint"
+ x-text="`${page * per + 1}–${Math.min((page + 1) * per, total)} of ${total.toLocaleString()}`"></span>
+ <div class="flex items-center gap-1">
+ <button type="button" @click="page = Math.max(0, page - 1)" :disabled="page === 0"
+ class="flex h-6 items-center rounded-md px-2 text-[11px] font-medium text-neutral-500 transition-colors hover:text-black disabled:cursor-not-allowed disabled:opacity-30 dark:text-fg-faint dark:hover:text-fg">
+ Prev
+ </button>
+ <button type="button" @click="page = Math.min(Math.ceil(total / per) - 1, page + 1)"
+ :disabled="(page + 1) * per >= total"
+ class="flex h-6 items-center rounded-md px-2 text-[11px] font-medium text-neutral-500 transition-colors hover:text-black disabled:cursor-not-allowed disabled:opacity-30 dark:text-fg-faint dark:hover:text-fg">
+ Next
+ </button>
+ </div>
+</div>
diff --git a/resources/views/livewire/traffic/_paths-list.blade.php b/resources/views/livewire/traffic/_paths-list.blade.php
new file mode 100644
index 0000000000..fbeee59175
--- /dev/null
+++ b/resources/views/livewire/traffic/_paths-list.blade.php
@@ -0,0 +1,40 @@
+{{--
+ Paginated "top paths" list. Each row shows the owning domain (when known) above
+ the path, and links the path to its live URL (new tab, rel="noopener noreferrer
+ nofollow"). Expects `$paths` in scope; optional `$keyPrefix` to namespace wire:keys.
+
+ @param iterable $paths path rows: ['path', 'domain'?, 'requests', 'bytesOut', 'p95']
+ @param ?string $keyPrefix wire:key prefix (default "analytics-path")
+--}}
+@php
+ $paths = $paths ?? [];
+ $keyPrefix = $keyPrefix ?? 'analytics-path';
+@endphp
+@if (empty($paths))
+ <x-empty size="sm" title="No path data" description="No requests were recorded for the selected range."
+ icon-name="unordered-list" />
+@else
+ <div x-data="{ page: 0, per: 10, total: {{ count($paths) }} }">
+ @foreach ($paths as $path)
+ @php
+ $domain = $path['domain'] ?? null;
+ $pathStr = (string) ($path['path'] ?? '');
+ $href = $domain ? 'https://'.$domain.$pathStr : null;
+ @endphp
+ <div wire:key="{{ $keyPrefix }}-{{ $loop->index }}"
+ x-show="{{ $loop->index }} >= page * per && {{ $loop->index }} < (page + 1) * per"
+ 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]">
+ @if ($href)
+ <a href="{{ $href }}" target="_blank" rel="noopener noreferrer nofollow"
+ class="min-w-0 flex-1 truncate font-mono text-[12px] text-black hover:underline dark:text-fg">@if ($domain)<span class="text-neutral-400 dark:text-fg-faint">{{ $domain }}</span>@endif{{ $pathStr }}</a>
+ @else
+ <span class="min-w-0 flex-1 truncate font-mono text-[12px] text-black dark:text-fg">@if ($domain)<span class="text-neutral-400 dark:text-fg-faint">{{ $domain }}</span>@endif{{ $pathStr }}</span>
+ @endif
+ <span class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ number_format((int) ($path['requests'] ?? 0)) }} req</span>
+ <span class="shrink-0 text-[12px] text-neutral-500 dark:text-fg-dim">{{ formatBytes((int) ($path['bytesOut'] ?? 0)) }}</span>
+ <span class="hidden shrink-0 text-[12px] text-neutral-500 sm:inline dark:text-fg-dim">p95 {{ number_format((float) ($path['p95'] ?? 0), 1) }} ms</span>
+ </div>
+ @endforeach
+ @include('livewire.traffic._pager')
+ </div>
+@endif
diff --git a/resources/views/livewire/traffic/_status-chart.blade.php b/resources/views/livewire/traffic/_status-chart.blade.php
new file mode 100644
index 0000000000..a25f9fda78
--- /dev/null
+++ b/resources/views/livewire/traffic/_status-chart.blade.php
@@ -0,0 +1,144 @@
+{{--
+ Status-class chart. Renders a stacked area chart of per-bucket 2xx/3xx/4xx/5xx
+ counts over time when Sentinel exposes the /traffic/series endpoint, and falls
+ back to a status donut when it does not (older Sentinel returns 404, so the host
+ component dispatches `hasSeries: false`). Colors read from the shared --chart-status-*
+ design tokens. Expects `$chartId` in scope.
+--}}
+<div wire:ignore id="{!! $chartId !!}-status" class="min-h-[220px] w-full"></div>
+
+@script
+<script>
+ (() => {
+ checkTheme();
+
+ const el = document.getElementById('{!! $chartId !!}-status');
+ const cssVar = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ const statusColors = () => [
+ cssVar('--chart-status-2xx'),
+ cssVar('--chart-status-3xx'),
+ cssVar('--chart-status-4xx'),
+ cssVar('--chart-status-5xx'),
+ ];
+ const gridColor = () => cssVar('--chart-geo-empty') || 'rgba(128,128,128,0.15)';
+
+ const legend = () => ({
+ position: 'bottom',
+ labels: {
+ colors: textColor,
+ },
+ });
+
+ const buildDonut = () => new ApexCharts(el, {
+ 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: legend(),
+ noData: {
+ text: 'Loading status codes…',
+ style: { color: textColor },
+ },
+ tooltip: {
+ y: {
+ formatter: value => `${value.toLocaleString()} requests`,
+ },
+ },
+ });
+
+ // `24h` buckets are hourly, `7d`/`30d` daily — pick a matching axis/tooltip format.
+ const timeFormat = range => (range === '24h' ? 'HH:mm' : 'dd MMM');
+
+ const buildArea = () => new ApexCharts(el, {
+ chart: {
+ height: 220,
+ type: 'area',
+ stacked: true,
+ toolbar: { show: false },
+ zoom: { enabled: false },
+ animations: { enabled: false },
+ background: 'transparent',
+ },
+ series: [],
+ colors: statusColors(),
+ dataLabels: { enabled: false },
+ stroke: { width: 2, curve: 'smooth' },
+ fill: {
+ type: 'gradient',
+ gradient: { opacityFrom: 0.35, opacityTo: 0.05 },
+ },
+ xaxis: {
+ type: 'datetime',
+ labels: { style: { colors: textColor }, datetimeUTC: false },
+ axisBorder: { show: false },
+ axisTicks: { show: false },
+ },
+ yaxis: {
+ labels: {
+ style: { colors: textColor },
+ formatter: value => Math.round(value).toLocaleString(),
+ },
+ },
+ grid: { borderColor: gridColor() },
+ legend: legend(),
+ noData: {
+ text: 'Loading status codes…',
+ style: { color: textColor },
+ },
+ tooltip: {
+ y: {
+ formatter: value => `${value.toLocaleString()} requests`,
+ },
+ },
+ });
+
+ let chart = buildDonut();
+ let mode = 'donut';
+ chart.render();
+
+ Livewire.on('refreshChartData-{!! $chartId !!}-status', payload => {
+ checkTheme();
+ const data = Array.isArray(payload) ? payload[0] : payload;
+ const wantArea = !!(data && data.hasSeries && data.timeSeries);
+ const nextMode = wantArea ? 'area' : 'donut';
+
+ if (nextMode !== mode) {
+ chart.destroy();
+ chart = nextMode === 'area' ? buildArea() : buildDonut();
+ chart.render();
+ mode = nextMode;
+ }
+
+ if (nextMode === 'area') {
+ chart.updateOptions({
+ colors: statusColors(),
+ grid: { borderColor: gridColor() },
+ legend: legend(),
+ xaxis: {
+ type: 'datetime',
+ categories: data.timeSeries.categories,
+ labels: { style: { colors: textColor }, datetimeUTC: false, format: timeFormat(data.range) },
+ },
+ tooltip: { x: { format: timeFormat(data.range) } },
+ });
+ chart.updateSeries([
+ { name: '2xx', data: data.timeSeries.s2xx },
+ { name: '3xx', data: data.timeSeries.s3xx },
+ { name: '4xx', data: data.timeSeries.s4xx },
+ { name: '5xx', data: data.timeSeries.s5xx },
+ ]);
+ } else {
+ chart.updateOptions({ colors: statusColors(), legend: legend() });
+ chart.updateSeries(data.seriesData);
+ }
+ });
+ })();
+</script>
+@endscript
diff --git a/routes/web.php b/routes/web.php
index cea551cee7..d388aa0c1b 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -5,6 +5,7 @@ use App\Http\Controllers\OauthController;
use App\Http\Controllers\ProfileAvatarController;
use App\Http\Controllers\UploadController;
use App\Livewire\Admin\Index as AdminIndex;
+use App\Livewire\Analytics;
use App\Livewire\Boarding\Index as BoardingIndex;
use App\Livewire\Dashboard;
use App\Livewire\Destination\Index as DestinationIndex;
@@ -49,7 +50,6 @@ use App\Livewire\Security\CloudTokens;
use App\Livewire\Security\PrivateKey\Index as SecurityPrivateKeyIndex;
use App\Livewire\Security\PrivateKey\Show as SecurityPrivateKeyShow;
use App\Livewire\Server\Advanced as ServerAdvanced;
-use App\Livewire\Server\Analytics as ServerAnalytics;
use App\Livewire\Server\CaCertificate\Show as CaCertificateShow;
use App\Livewire\Server\Charts as ServerCharts;
use App\Livewire\Server\CloudflareTunnel;
@@ -147,6 +147,7 @@ Route::middleware(['auth', 'verified'])->group(function () {
});
Route::get('/', Dashboard::class)->name('dashboard');
+ Route::get('/analytics', Analytics::class)->name('analytics');
Route::get('/admin', AdminIndex::class)->name('admin.index');
Route::get('/onboarding', BoardingIndex::class)->name('onboarding');
@@ -359,7 +360,6 @@ Route::middleware(['auth', 'verified'])->group(function () {
Route::get('/destinations', ServerDestinations::class)->name('server.destinations');
Route::get('/log-drains', LogDrains::class)->name('server.log-drains');
Route::get('/metrics', ServerCharts::class)->name('server.metrics');
- Route::get('/analytics', ServerAnalytics::class)->name('server.analytics');
Route::get('/danger', DeleteServer::class)->name('server.delete');
Route::get('/transfer', ServerTransfer::class)->name('server.transfer');
Route::get('/proxy', ProxyShow::class)->name('server.proxy');
diff --git a/tests/Feature/TrafficAnalytics/AnalyticsFormattingTest.php b/tests/Feature/TrafficAnalytics/AnalyticsFormattingTest.php
new file mode 100644
index 0000000000..f1c285f19f
--- /dev/null
+++ b/tests/Feature/TrafficAnalytics/AnalyticsFormattingTest.php
@@ -0,0 +1,34 @@
+<?php
+
+// Presentation helpers for the analytics views (items: flags, referrer favicons,
+// device capitalization).
+
+it('maps woothee device categories to friendly capitalized labels', function () {
+ expect(deviceLabel('pc'))->toBe('Desktop');
+ expect(deviceLabel('smartphone'))->toBe('Mobile');
+ expect(deviceLabel('mobilephone'))->toBe('Mobile');
+ expect(deviceLabel('crawler'))->toBe('Bot');
+ expect(deviceLabel('tablet'))->toBe('Tablet');
+ expect(deviceLabel(''))->toBe('Unknown');
+ expect(deviceLabel(null))->toBe('Unknown');
+});
+
+it('extracts a bare host from referer URLs and bare hosts, dropping www', function () {
+ expect(refererHost('https://www.google.com/search?q=x'))->toBe('google.com');
+ expect(refererHost('http://news.ycombinator.com'))->toBe('news.ycombinator.com');
+ expect(refererHost('example.com'))->toBe('example.com');
+ expect(refererHost(''))->toBeNull();
+ expect(refererHost(null))->toBeNull();
+});
+
+it('builds a duckduckgo favicon url for a host', function () {
+ expect(refererFaviconUrl('example.com'))->toBe('https://icons.duckduckgo.com/ip3/example.com.ico');
+});
+
+it('builds a flagcdn image url for valid ISO codes only', function () {
+ expect(countryFlagUrl('US'))->toBe('https://flagcdn.com/24x18/us.png');
+ expect(countryFlagUrl('de', '48x36'))->toBe('https://flagcdn.com/48x36/de.png');
+ expect(countryFlagUrl('ZZZ'))->toBeNull();
+ expect(countryFlagUrl(''))->toBeNull();
+ expect(countryFlagUrl(null))->toBeNull();
+});
diff --git a/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php b/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php
index 4525520539..dabce44521 100644
--- a/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php
+++ b/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php
@@ -43,7 +43,16 @@ function fakeAnalyticsResponses(): array
'unique_visitors' => 320,
]),
'/traffic/paths' => json_encode([
- ['path' => '/', 'requests' => 500, 'bytes_out' => 12000, 'p50' => 10.0, 'p95' => 30.0],
+ ['path' => '/', 'app' => 'app-key', 'requests' => 500, 'bytes_out' => 12000, 'p50' => 10.0, 'p95' => 30.0],
+ ]),
+ '/traffic/breakdown/agent' => json_encode([
+ ['value' => 'ClaudeBot', 'requests' => 90, 'bytes_out' => 2000],
+ ]),
+ '/traffic/breakdown/ip' => json_encode([
+ ['value' => '198.51.100.42', 'requests' => 60, 'bytes_out' => 1200],
+ ]),
+ '/traffic/breakdown/useragent' => json_encode([
+ ['value' => 'Mozilla/5.0 (Macintosh) PerAppAgent/2.0', 'requests' => 55, 'bytes_out' => 1100],
]),
'/traffic/breakdown/country' => json_encode([
['value' => 'US', 'requests' => 600, 'bytes_out' => 15000],
@@ -60,6 +69,10 @@ function fakeAnalyticsResponses(): array
'/traffic/breakdown/device' => json_encode([
['value' => 'Desktop', 'requests' => 800, 'bytes_out' => 20000],
]),
+ '/traffic/series' => json_encode([
+ ['bucket' => 1_700_000_000_000, 's2xx' => 40, 's3xx' => 2, 's4xx' => 1, 's5xx' => 0],
+ ['bucket' => 1_700_003_600_000, 's2xx' => 60, 's3xx' => 3, 's4xx' => 2, 's5xx' => 1],
+ ]),
'/traffic/attribution' => json_encode(['attribution' => 'GeoIP data by MaxMind']),
];
}
@@ -124,6 +137,60 @@ it('renders KPIs from a mocked traffic client when analytics is enabled', functi
->assertSee('GeoIP data by MaxMind');
});
+it('loads the per-app status time series when Sentinel exposes the series endpoint', 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()
+ ->assertSet('hasSeries', true)
+ ->assertSet('series', [
+ ['bucket' => 1_700_000_000_000, 's2xx' => 40, 's3xx' => 2, 's4xx' => 1, 's5xx' => 0],
+ ['bucket' => 1_700_003_600_000, 's2xx' => 60, 's3xx' => 3, 's4xx' => 2, 's5xx' => 1],
+ ])
+ ->assertDispatched('refreshChartData-application-analytics-status');
+});
+
+it('decorates per-app paths with the app domain and surfaces AI agents', function () {
+ $application = makeAnalyticsApplication($this->team, $this->privateKey, $this->environment, true);
+ $application->update(['fqdn' => 'https://api.example.com']);
+
+ $fake = new FakeAnalyticsTrafficClient($application->destination->server);
+ $fake->responses = fakeAnalyticsResponses();
+ app()->bind(SentinelTrafficClient::class, fn () => $fake);
+
+ $component = Livewire::test(Analytics::class, ['application' => $application])
+ ->assertOk()
+ ->assertSee('api.example.com')
+ ->assertSee('AI agents & bots')
+ ->assertSee('ClaudeBot')
+ ->assertSee('Top IPs')
+ ->assertSee('198.51.100.42')
+ ->assertSee('Top user agents')
+ ->assertSee('PerAppAgent/2.0');
+
+ expect($component->instance()->topPaths[0]['domain'])->toBe('api.example.com');
+});
+
+it('falls back to the donut for the per-app chart when the series endpoint is absent', function () {
+ $application = makeAnalyticsApplication($this->team, $this->privateKey, $this->environment, true);
+
+ $responses = fakeAnalyticsResponses();
+ unset($responses['/traffic/series']);
+
+ $fake = new FakeAnalyticsTrafficClient($application->destination->server);
+ $fake->responses = $responses;
+ app()->bind(SentinelTrafficClient::class, fn () => $fake);
+
+ Livewire::test(Analytics::class, ['application' => $application])
+ ->assertOk()
+ ->assertSet('hasSeries', false)
+ ->assertSet('series', []);
+});
+
it('shows an empty state when traffic analytics is disabled for the server', function () {
$application = makeAnalyticsApplication($this->team, $this->privateKey, $this->environment, false);
diff --git a/tests/Feature/TrafficAnalytics/ChartTokensTest.php b/tests/Feature/TrafficAnalytics/ChartTokensTest.php
index 4dd5df00b2..a84db8e3cb 100644
--- a/tests/Feature/TrafficAnalytics/ChartTokensTest.php
+++ b/tests/Feature/TrafficAnalytics/ChartTokensTest.php
@@ -27,7 +27,7 @@ it('defines the chart design tokens in the app stylesheet', function () {
it('no longer hardcodes status color hex arrays in the analytics views', function () {
$views = [
- base_path('resources/views/livewire/server/analytics.blade.php'),
+ base_path('resources/views/livewire/analytics.blade.php'),
base_path('resources/views/livewire/project/application/analytics.blade.php'),
];
@@ -36,6 +36,15 @@ it('no longer hardcodes status color hex arrays in the analytics views', functio
expect($contents)->not->toContain('statusColorsLight');
expect($contents)->not->toContain('statusColorsDark');
- expect($contents)->toContain('--chart-status-2xx');
+ // The chart lives in the shared partial; the views just pull it in.
+ expect($contents)->toContain("@include('livewire.traffic._status-chart')");
}
});
+
+it('reads status colors from design tokens in the shared status-chart partial', function () {
+ $partial = file_get_contents(base_path('resources/views/livewire/traffic/_status-chart.blade.php'));
+
+ expect($partial)->not->toContain('statusColorsLight');
+ expect($partial)->not->toContain('statusColorsDark');
+ expect($partial)->toContain('--chart-status-2xx');
+});
diff --git a/tests/Feature/TrafficAnalytics/GeoVisualizationTest.php b/tests/Feature/TrafficAnalytics/GeoVisualizationTest.php
index f5a35579ad..6dd99e039d 100644
--- a/tests/Feature/TrafficAnalytics/GeoVisualizationTest.php
+++ b/tests/Feature/TrafficAnalytics/GeoVisualizationTest.php
@@ -1,6 +1,6 @@
<?php
-use App\Livewire\Server\Analytics;
+use App\Livewire\Analytics;
use App\Models\PrivateKey;
use App\Models\Server;
use App\Models\Team;
@@ -75,7 +75,7 @@ it('renders resolved country names and the choropleth map when country data is p
]);
app()->bind(SentinelTrafficClient::class, fn () => $fake);
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
+ Livewire::test(Analytics::class)
->assertOk()
->assertSee('Countries')
->assertSee('United States')
@@ -96,7 +96,7 @@ it('collapses unresolvable country codes into a single Unknown row', function ()
]);
app()->bind(SentinelTrafficClient::class, fn () => $fake);
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
+ Livewire::test(Analytics::class)
->assertOk()
->assertSee('United States')
->assertSee('Unknown');
@@ -109,7 +109,7 @@ it('shows a plain no-data state when no country data has been recorded', functio
$fake->responses = fakeGeoResponses([]);
app()->bind(SentinelTrafficClient::class, fn () => $fake);
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
+ Livewire::test(Analytics::class)
->assertOk()
->assertSee('Countries')
->assertSee('No country data for the selected range');
diff --git a/tests/Feature/TrafficAnalytics/GlobalAnalyticsTest.php b/tests/Feature/TrafficAnalytics/GlobalAnalyticsTest.php
new file mode 100644
index 0000000000..e1e0be88fa
--- /dev/null
+++ b/tests/Feature/TrafficAnalytics/GlobalAnalyticsTest.php
@@ -0,0 +1,284 @@
+<?php
+
+use App\Livewire\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 FakeGlobalAnalyticsTrafficClient 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 fakeGlobalAnalyticsResponses(array $appUuids = []): array
+{
+ return [
+ '/traffic/apps' => json_encode($appUuids),
+ '/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' => '/', 'app' => $appUuids[0] ?? '', 'requests' => 500, 'bytes_out' => 12000, 'p50' => 10.0, 'p95' => 30.0],
+ ]),
+ '/traffic/breakdown/agent' => json_encode([
+ ['value' => 'GPTBot', 'requests' => 120, 'bytes_out' => 3000],
+ ]),
+ '/traffic/breakdown/ip' => json_encode([
+ ['value' => '203.0.113.7', 'requests' => 80, 'bytes_out' => 2000],
+ ]),
+ '/traffic/breakdown/useragent' => json_encode([
+ ['value' => 'Mozilla/5.0 (X11; Linux x86_64) TestAgent/1.0', 'requests' => 70, 'bytes_out' => 1500],
+ ]),
+ '/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/series' => json_encode([
+ ['bucket' => 1_700_000_000_000, 's2xx' => 40, 's3xx' => 2, 's4xx' => 1, 's5xx' => 0],
+ ['bucket' => 1_700_003_600_000, 's2xx' => 60, 's3xx' => 3, 's4xx' => 2, 's5xx' => 1],
+ ]),
+ '/traffic/attribution' => json_encode(['attribution' => 'GeoIP data by MaxMind']),
+ ];
+}
+
+beforeEach(function () {
+ Server::flushIdentityMap();
+ $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::factory()->create(['team_id' => $this->team->id]);
+});
+
+function bootEnabledGlobalServer(): Server
+{
+ $server = Server::factory()->create([
+ 'team_id' => test()->team->id,
+ 'private_key_id' => test()->privateKey->id,
+ ]);
+ $server->settings->is_traffic_analytics_enabled = true;
+ $server->settings->save();
+
+ return $server;
+}
+
+it('renders a team-wide analytics summary across enabled servers', function () {
+ $server = bootEnabledGlobalServer();
+
+ $project = Project::factory()->create(['team_id' => $this->team->id]);
+ $environment = Environment::factory()->create(['project_id' => $project->id]);
+ $destination = StandaloneDocker::where('server_id', $server->id)->first()
+ ?? StandaloneDocker::factory()->create(['server_id' => $server->id, 'network' => 'coolify-test']);
+
+ $application = Application::factory()->create([
+ 'name' => 'Global Leaderboard App',
+ 'environment_id' => $environment->id,
+ 'destination_id' => $destination->id,
+ 'destination_type' => StandaloneDocker::class,
+ ]);
+
+ $fake = new FakeGlobalAnalyticsTrafficClient($server);
+ $fake->responses = fakeGlobalAnalyticsResponses([$application->uuid]);
+ app()->bind(SentinelTrafficClient::class, fn () => $fake);
+
+ Livewire::test(Analytics::class)
+ ->assertOk()
+ ->assertSee('Analytics')
+ ->assertSee('1,000')
+ ->assertSee('Top applications')
+ ->assertSee('Global Leaderboard App')
+ ->assertSee('Top paths')
+ ->assertSee('Countries')
+ ->assertSee('United States')
+ ->assertSee('GeoIP data by MaxMind')
+ ->assertSet('serverOptions', [$server->uuid => $server->name])
+ ->assertSet('appOptions', [$application->uuid => 'Global Leaderboard App']);
+});
+
+it('shows path domains, links top apps to analytics, groups by project, and surfaces AI agents', function () {
+ $server = bootEnabledGlobalServer();
+
+ $project = Project::factory()->create(['team_id' => $this->team->id, 'name' => 'Storefront']);
+ $environment = Environment::factory()->create(['project_id' => $project->id]);
+ $destination = StandaloneDocker::where('server_id', $server->id)->first()
+ ?? StandaloneDocker::factory()->create(['server_id' => $server->id, 'network' => 'coolify-test']);
+
+ $application = Application::factory()->create([
+ 'name' => 'Shop',
+ 'fqdn' => 'https://shop.example.com',
+ 'environment_id' => $environment->id,
+ 'destination_id' => $destination->id,
+ 'destination_type' => StandaloneDocker::class,
+ ]);
+
+ $fake = new FakeGlobalAnalyticsTrafficClient($server);
+ $fake->responses = fakeGlobalAnalyticsResponses([$application->uuid]);
+ app()->bind(SentinelTrafficClient::class, fn () => $fake);
+
+ $analyticsUrl = route('project.application.analytics', [
+ 'project_uuid' => $project->uuid,
+ 'environment_uuid' => $environment->uuid,
+ 'application_uuid' => $application->uuid,
+ ]);
+
+ $component = Livewire::test(Analytics::class)
+ ->assertOk()
+ ->assertSee('shop.example.com') // domain shown on the path row
+ ->assertSee($analyticsUrl, false) // top-app row links to its analytics page
+ ->assertSee('AI agents & bots')
+ ->assertSee('GPTBot')
+ ->assertSee('Top IPs')
+ ->assertSee('203.0.113.7')
+ ->assertSee('Top user agents')
+ ->assertSee('TestAgent/1.0');
+
+ // Path rows carry the resolved domain, top-app rows carry the domain + analytics link.
+ expect($component->instance()->topPaths[0]['domain'])->toBe('shop.example.com');
+ expect($component->instance()->topApps[0]['domain'])->toBe('shop.example.com');
+ expect($component->instance()->topApps[0]['link'])->toBe($analyticsUrl);
+
+ // The application listbox is grouped under a project header.
+ $grouped = $component->instance()->appGroupedOptions;
+ expect(collect($grouped)->firstWhere('header', true))->not->toBeNull();
+ expect(collect($grouped)->firstWhere('label', 'Storefront')['header'] ?? null)->toBeTrue();
+ expect(collect($grouped)->firstWhere('value', $application->uuid)['label'])->toBe('Shop');
+});
+
+it('builds a stacked status time series when Sentinel exposes the series endpoint', function () {
+ $server = bootEnabledGlobalServer();
+
+ $fake = new FakeGlobalAnalyticsTrafficClient($server);
+ $fake->responses = fakeGlobalAnalyticsResponses();
+ app()->bind(SentinelTrafficClient::class, fn () => $fake);
+
+ Livewire::test(Analytics::class)
+ ->assertOk()
+ ->assertSet('hasSeries', true)
+ ->assertSet('series', [
+ ['bucket' => 1_700_000_000_000, 's2xx' => 40, 's3xx' => 2, 's4xx' => 1, 's5xx' => 0],
+ ['bucket' => 1_700_003_600_000, 's2xx' => 60, 's3xx' => 3, 's4xx' => 2, 's5xx' => 1],
+ ])
+ ->assertDispatched('refreshChartData-global-analytics-status');
+});
+
+it('falls back to the donut when Sentinel lacks the series endpoint', function () {
+ $server = bootEnabledGlobalServer();
+
+ // Same responses minus the series entry — an older Sentinel returns 404 (empty body).
+ $responses = fakeGlobalAnalyticsResponses();
+ unset($responses['/traffic/series']);
+
+ $fake = new FakeGlobalAnalyticsTrafficClient($server);
+ $fake->responses = $responses;
+ app()->bind(SentinelTrafficClient::class, fn () => $fake);
+
+ Livewire::test(Analytics::class)
+ ->assertOk()
+ ->assertSet('hasSeries', false)
+ ->assertSet('series', []);
+});
+
+it('does not disclose another team application name for a sentinel-reported uuid', function () {
+ $server = bootEnabledGlobalServer();
+
+ $otherTeam = Team::factory()->create();
+ $otherProject = Project::factory()->create(['team_id' => $otherTeam->id]);
+ $otherEnvironment = Environment::factory()->create(['project_id' => $otherProject->id]);
+ $otherServer = Server::factory()->create(['team_id' => $otherTeam->id]);
+ $otherDestination = StandaloneDocker::factory()->create(['server_id' => $otherServer->id, 'network' => 'other-team-test']);
+
+ $otherTeamApplication = Application::factory()->create([
+ 'name' => 'Secret Other Team App',
+ 'environment_id' => $otherEnvironment->id,
+ 'destination_id' => $otherDestination->id,
+ 'destination_type' => StandaloneDocker::class,
+ ]);
+
+ $fake = new FakeGlobalAnalyticsTrafficClient($server);
+ $fake->responses = fakeGlobalAnalyticsResponses([$otherTeamApplication->uuid]);
+ app()->bind(SentinelTrafficClient::class, fn () => $fake);
+
+ Livewire::test(Analytics::class)
+ ->assertOk()
+ ->assertDontSee('Secret Other Team App')
+ ->assertSee($otherTeamApplication->uuid);
+});
+
+it('scopes the view to a single application and hides the leaderboard when filtered by app', function () {
+ $server = bootEnabledGlobalServer();
+
+ $project = Project::factory()->create(['team_id' => $this->team->id]);
+ $environment = Environment::factory()->create(['project_id' => $project->id]);
+ $destination = StandaloneDocker::where('server_id', $server->id)->first()
+ ?? StandaloneDocker::factory()->create(['server_id' => $server->id, 'network' => 'coolify-test']);
+
+ $application = Application::factory()->create([
+ 'name' => 'Filtered App',
+ 'environment_id' => $environment->id,
+ 'destination_id' => $destination->id,
+ 'destination_type' => StandaloneDocker::class,
+ ]);
+
+ $fake = new FakeGlobalAnalyticsTrafficClient($server);
+ $fake->responses = fakeGlobalAnalyticsResponses([$application->uuid]);
+ app()->bind(SentinelTrafficClient::class, fn () => $fake);
+
+ Livewire::test(Analytics::class)
+ ->set('appUuid', $application->uuid)
+ ->assertOk()
+ ->assertSee('1,000')
+ ->assertSee('Top paths')
+ ->assertDontSee('Top applications');
+});
+
+it('shows the not-enabled empty state when no server has traffic analytics on', function () {
+ $server = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => $this->privateKey->id,
+ ]);
+ $server->settings->is_traffic_analytics_enabled = false;
+ $server->settings->save();
+
+ Livewire::test(Analytics::class)
+ ->assertOk()
+ ->assertSee('Traffic analytics is not enabled')
+ ->assertDontSee('Unique visitors');
+});
diff --git a/tests/Feature/TrafficAnalytics/LiveRefreshTest.php b/tests/Feature/TrafficAnalytics/LiveRefreshTest.php
index f006b8c842..25fa8df74f 100644
--- a/tests/Feature/TrafficAnalytics/LiveRefreshTest.php
+++ b/tests/Feature/TrafficAnalytics/LiveRefreshTest.php
@@ -1,6 +1,6 @@
<?php
-use App\Livewire\Server\Analytics;
+use App\Livewire\Analytics;
use App\Models\PrivateKey;
use App\Models\Server;
use App\Models\Team;
@@ -55,7 +55,7 @@ function bootLiveServer(): Server
it('polls for realtime data by default at the 24h range', function () {
$server = bootLiveServer();
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
+ Livewire::test(Analytics::class)
->assertOk()
->assertSet('live', true)
->assertSeeHtml('wire:poll.60s')
@@ -65,7 +65,7 @@ it('polls for realtime data by default at the 24h range', function () {
it('stops polling when live is toggled off', function () {
$server = bootLiveServer();
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
+ Livewire::test(Analytics::class)
->assertSeeHtml('wire:poll.60s')
->call('toggleLive')
->assertSet('live', false)
@@ -75,7 +75,7 @@ it('stops polling when live is toggled off', function () {
it('disables realtime polling for the 7d and 30d ranges', function () {
$server = bootLiveServer();
- $component = Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
+ $component = Livewire::test(Analytics::class)
->call('setRange', '7d')
->assertDontSeeHtml('wire:poll.60s');
@@ -90,7 +90,7 @@ it('disables realtime polling for the 7d and 30d ranges', function () {
it('re-arms polling when returning to the 24h range', function () {
$server = bootLiveServer();
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
+ Livewire::test(Analytics::class)
->call('setRange', '7d')
->assertDontSeeHtml('wire:poll.60s')
->call('setRange', '24h')
diff --git a/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php b/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php
index 6c12041194..5e7438ec16 100644
--- a/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php
+++ b/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php
@@ -102,3 +102,50 @@ it('accepts every known dimension and rejects unknown ones', function () {
expect(fn () => $client->breakdown(null, 'not-a-real-dimension', 'a', 'b'))
->toThrow(InvalidArgumentException::class);
});
+
+it('builds the server-wide series url with the range knob', function () {
+ $server = Server::factory()->create(['team_id' => $this->team->id]);
+ $client = new FakeTrafficClient($server);
+ $client->response = json_encode([
+ ['bucket' => 1_700_000_000_000, 's2xx' => 5, 's3xx' => 1, 's4xx' => 0, 's5xx' => 0],
+ ]);
+
+ $rows = $client->series(null, '7d');
+
+ expect($rows)->toHaveCount(1)
+ ->and($rows->first()->bucket)->toBe(1_700_000_000_000)
+ ->and($rows->first()->s2xx)->toBe(5);
+ expect($client->captured[0])->toContain('/api/traffic/series')
+ ->toContain('range=7d')->not->toContain('/app/');
+});
+
+it('builds the per-app series url and defaults an unknown range to 24h', function () {
+ $server = Server::factory()->create(['team_id' => $this->team->id]);
+ $client = new FakeTrafficClient($server);
+ $client->response = json_encode([]);
+
+ $client->series('cm2abc123xyz456uuid', 'bogus');
+
+ expect($client->captured[0])->toContain('/api/app/cm2abc123xyz456uuid/traffic/series')
+ ->toContain('range=24h');
+});
+
+it('returns an empty series when the endpoint is absent (older Sentinel 404)', function () {
+ $server = Server::factory()->create(['team_id' => $this->team->id]);
+ $client = new FakeTrafficClient($server);
+
+ // Empty body / unparseable / empty array all mean "no series" → donut fallback.
+ foreach (['', 'Not Found', '{}', '[]'] as $body) {
+ $client->response = $body;
+ expect($client->series(null, '24h'))->toBeEmpty();
+ }
+});
+
+it('rejects a malicious app key for the series endpoint', function () {
+ $server = Server::factory()->create(['team_id' => $this->team->id]);
+ $client = new FakeTrafficClient($server);
+
+ expect(fn () => $client->series("x'; rm -rf /; '", '24h'))
+ ->toThrow(InvalidArgumentException::class);
+ expect($client->captured)->toBeEmpty();
+});
diff --git a/tests/Feature/TrafficAnalytics/ServerAnalyticsTest.php b/tests/Feature/TrafficAnalytics/ServerAnalyticsTest.php
deleted file mode 100644
index d3306748fe..0000000000
--- a/tests/Feature/TrafficAnalytics/ServerAnalyticsTest.php
+++ /dev/null
@@ -1,167 +0,0 @@
-<?php
-
-use App\Livewire\Server\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 FakeServerAnalyticsTrafficClient 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 fakeServerAnalyticsResponses(array $appUuids = []): array
-{
- return [
- '/traffic/apps' => json_encode($appUuids),
- '/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,
- ]);
-});
-
-it('renders server-wide analytics with a per-app leaderboard when enabled', function () {
- $server = Server::factory()->create([
- 'team_id' => $this->team->id,
- 'private_key_id' => $this->privateKey->id,
- ]);
- $server->settings->is_traffic_analytics_enabled = true;
- $server->settings->save();
-
- $project = Project::factory()->create(['team_id' => $this->team->id]);
- $environment = Environment::factory()->create(['project_id' => $project->id]);
- $destination = StandaloneDocker::where('server_id', $server->id)->first()
- ?? StandaloneDocker::factory()->create(['server_id' => $server->id, 'network' => 'coolify-test']);
-
- $application = Application::factory()->create([
- 'name' => 'Leaderboard App',
- 'environment_id' => $environment->id,
- 'destination_id' => $destination->id,
- 'destination_type' => StandaloneDocker::class,
- ]);
-
- $fake = new FakeServerAnalyticsTrafficClient($server);
- $fake->responses = fakeServerAnalyticsResponses([$application->uuid]);
- app()->bind(SentinelTrafficClient::class, fn () => $fake);
-
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
- ->assertOk()
- ->assertSee('Requests')
- ->assertSee('1,000')
- ->assertSee('Unique visitors')
- ->assertSee('Error rate')
- ->assertSee('/')
- ->assertSee('US')
- ->assertSee('GeoIP data by MaxMind')
- ->assertSee('Leaderboard App');
-});
-
-it('does not disclose another team application name for a sentinel-reported uuid', function () {
- $server = Server::factory()->create([
- 'team_id' => $this->team->id,
- 'private_key_id' => $this->privateKey->id,
- ]);
- $server->settings->is_traffic_analytics_enabled = true;
- $server->settings->save();
-
- $otherTeam = Team::factory()->create();
- $otherProject = Project::factory()->create(['team_id' => $otherTeam->id]);
- $otherEnvironment = Environment::factory()->create(['project_id' => $otherProject->id]);
- $otherServer = Server::factory()->create(['team_id' => $otherTeam->id]);
- $otherDestination = StandaloneDocker::factory()->create(['server_id' => $otherServer->id, 'network' => 'other-team-test']);
-
- $otherTeamApplication = Application::factory()->create([
- 'name' => 'Secret Other Team App',
- 'environment_id' => $otherEnvironment->id,
- 'destination_id' => $otherDestination->id,
- 'destination_type' => StandaloneDocker::class,
- ]);
-
- $fake = new FakeServerAnalyticsTrafficClient($server);
- $fake->responses = fakeServerAnalyticsResponses([$otherTeamApplication->uuid]);
- app()->bind(SentinelTrafficClient::class, fn () => $fake);
-
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
- ->assertOk()
- ->assertDontSee('Secret Other Team App')
- ->assertSee($otherTeamApplication->uuid);
-});
-
-it('shows an empty state when traffic analytics is disabled for the server', function () {
- $server = Server::factory()->create([
- 'team_id' => $this->team->id,
- 'private_key_id' => $this->privateKey->id,
- ]);
- $server->settings->is_traffic_analytics_enabled = false;
- $server->settings->save();
-
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
- ->assertOk()
- ->assertSee('Analytics')
- ->assertDontSee('Unique visitors');
-});
diff --git a/tests/Feature/TrafficAnalytics/TraefikAccessLogTest.php b/tests/Feature/TrafficAnalytics/TraefikAccessLogTest.php
index 1246c1af04..bddc577095 100644
--- a/tests/Feature/TrafficAnalytics/TraefikAccessLogTest.php
+++ b/tests/Feature/TrafficAnalytics/TraefikAccessLogTest.php
@@ -13,5 +13,8 @@ it('returns JSON access log + Cloudflare header capture flags when enabled', fun
->toContain('--accesslog.fields.headers.names.Cf-Ipcountry=keep')
->toContain('--accesslog.fields.headers.names.Cf-Cache-Status=keep')
->toContain('--accesslog.fields.headers.names.Cf-Verified-Bot=keep')
- ->toContain('--accesslog.fields.headers.names.Cf-Ray=keep');
+ ->toContain('--accesslog.fields.headers.names.Cf-Ray=keep')
+ ->toContain('--accesslog.fields.headers.names.X-Forwarded-For=keep')
+ ->toContain('--accesslog.fields.headers.names.User-Agent=keep')
+ ->toContain('--accesslog.fields.headers.names.Referer=keep');
});
diff --git a/tests/Feature/TrafficAnalytics/TrafficNudgeTest.php b/tests/Feature/TrafficAnalytics/TrafficNudgeTest.php
index 902562239c..c82a93578e 100644
--- a/tests/Feature/TrafficAnalytics/TrafficNudgeTest.php
+++ b/tests/Feature/TrafficAnalytics/TrafficNudgeTest.php
@@ -1,26 +1,15 @@
<?php
-use App\Actions\Server\ConfigureTrafficAnalytics;
use App\Livewire\Dashboard\TrafficAnalytics as DashboardTrafficAnalytics;
-use App\Livewire\Server\Analytics;
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 NudgeEmptyTrafficClient extends SentinelTrafficClient
-{
- protected function raw(string $url): string
- {
- return '[]';
- }
-}
-
beforeEach(function () {
Server::flushIdentityMap();
$this->team = Team::factory()->create();
@@ -43,44 +32,6 @@ function disabledServer(): Server
return $server;
}
-it('renders the server analytics nudge while traffic analytics is disabled', function () {
- $server = disabledServer();
-
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
- ->assertOk()
- ->assertSee('Turn on traffic analytics for this server')
- ->assertSee('restarts the proxy')
- ->assertSee('Enable traffic analytics');
-});
-
-it('enables traffic analytics from the server nudge and hides it', function () {
- ConfigureTrafficAnalytics::partialMock()->shouldReceive('handle')->once()->andReturnUsing(function ($server, $enable) {
- $server->settings->is_traffic_analytics_enabled = $enable;
- $server->settings->save();
- });
-
- $server = disabledServer();
- app()->bind(SentinelTrafficClient::class, fn () => new NudgeEmptyTrafficClient($server));
-
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
- ->assertSee('Turn on traffic analytics for this server')
- ->call('enableTrafficAnalytics')
- ->assertHasNoErrors()
- ->assertSet('enabled', true)
- ->assertDontSee('Turn on traffic analytics for this server');
-});
-
-it('shows the ineligible note instead of an enable button on a swarm server', function () {
- $server = disabledServer();
- $server->settings->is_swarm_manager = true;
- $server->settings->save();
-
- Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])
- ->assertOk()
- ->assertSee('not available on Swarm or Build-pack servers')
- ->assertDontSee('Enable traffic analytics');
-});
-
it('shows the dashboard nudge when an eligible server has analytics disabled', function () {
disabledServer();
diff --git a/tests/v4/Browser/TrafficAnalyticsTest.php b/tests/v4/Browser/TrafficAnalyticsTest.php
index d2d1ae8e06..ad4ba0a194 100644
--- a/tests/v4/Browser/TrafficAnalyticsTest.php
+++ b/tests/v4/Browser/TrafficAnalyticsTest.php
@@ -33,16 +33,15 @@ it('shows the disabled empty state on the application analytics tab', function (
->screenshot(filename: 'application-analytics-disabled-empty-state');
});
-it('shows the disabled empty state on the server analytics tab', function () {
+it('shows the disabled empty state on the global analytics page', function () {
loginAndSkipBoarding();
- $server = $this->stack['server'];
+ $page = visit('/analytics');
- $page = visit("/server/{$server->uuid}/analytics");
-
- $page->assertSee('Traffic analytics is not enabled')
- ->assertSee('Enable Sentinel traffic analytics for this server to start collecting request analytics.')
- ->screenshot(filename: 'server-analytics-disabled-empty-state');
+ $page->assertSee('Analytics')
+ ->assertSee('Traffic analytics is not enabled')
+ ->assertSee('Enable Sentinel traffic analytics on a server to see request analytics here.')
+ ->screenshot(filename: 'global-analytics-disabled-empty-state');
});
it('shows the disabled empty state on the dashboard traffic widget', function () {