Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# FlightPHP APM

This repository is the `flightphp/apm` Composer library. It is not a Flight skeleton. There is no `app/config/routes.php`.

## Public API

Do not change these:

- Method signatures on `flight\Apm`, `flight\apm\CustomEvent`, `LoggerInterface`, `PresenterInterface`, and the reader and writer interfaces
- Flight event names the collector listens for
- The metrics array passed to `LoggerInterface::log()`
- CLI command names: `apm:init`, `apm:worker`, `apm:dashboard`, `apm:migrate`, `apm:purge`, `apm:config-migrate`
- Existing `apm` config keys

Adding a return key, a dashboard route, or an optional config key is fine. `WriterCommonTrait` is unused. Leave it in place.

`addPdoConnection()` accepts a `PDO`. `PdoWrapper` is deprecated upstream. Do not require a newer Flight type.

## Storage

SQLite and MySQL/MariaDB only. Schema changes are new files under `src/apm/migration/{sqlite,mysql}/dest/`. Do not edit a migration that has already shipped.

`apm:migrate` records filenames in one flat list shared by the source and destination databases. A new file needs a unique name, such as `0006-dest-indexes.sql`.

`request_dt` and `event_dt` are UTC strings from `gmdate`. Format chart labels with `gmdate`. Purge cutoffs use UTC.

Dashboard queries live in `src/apm/presenter/PresenterAbstract.php`. Filter the request window with a join or `EXISTS` on `apm_requests.request_dt`, not by loading every row into PHP.

## Dashboard

`dashboard/` is Bootstrap 5, Chart.js, and vanilla JavaScript. There is no build step. `php vendor/bin/runway apm:dashboard` serves `dashboard/index.php` as the router script so `/apm/dashboard` hits Flight and `/css` and `/js` still serve as files.

Optional basic auth reads `apm.dashboard_auth.user` and `apm.dashboard_auth.password`. If either is empty, the dashboard stays open.

## Bots

`Apm::isBot()` is a case-insensitive substring list. It includes search crawlers and LLM crawlers (GPTBot, ClaudeBot, PerplexityBot, SearxNG, and the rest in that method). `Google-Extended` is a robots.txt token, not a User-Agent, so it is not in the list. Add new agents there when a vendor publishes a new token.

## Tests and docs

Tests live in `tests/`. Do not commit `coverage/`.

The English docs page is `content/v3/en/awesome-plugins/apm.md` in the `flightphp-docs` repository. Update it when dashboard behavior or the upgrade steps change. Production upgrade steps also live in this repo's README under "Upgrading a production server".

Read the installed Flight core and the Flight docs before using a Flight API.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,39 @@ FlightPHP APM currently supports the following databases for storing metrics:
- **SQLite3**
- **MySQL/MariaDB**

## Upgrading a production server

Index changes ship as new SQL files. They do not rewrite collected rows. The worker can stay up while they run. On a large MySQL or MariaDB database, the new indexes still take a lock-light but heavy read of `apm_requests`, so run the migrate during a quiet period.

1. Back up the destination database. For SQLite, copy the destination file. For MySQL or MariaDB, `mysqldump` the APM schema.
2. Deploy the new package (`composer update flightphp/apm`).
3. From the application root, run:

```bash
php vendor/bin/runway apm:migrate
```

SQLite runs `src/apm/migration/sqlite/dest/0006-dest-indexes.sql`. MySQL and MariaDB run `src/apm/migration/mysql/dest/0002-dest-indexes.sql`. `apm:migrate` records filenames in the runway config and skips a file it has already applied. The same command is safe to run again.

`request_dt` is stored in UTC. `apm:purge` now compares against a UTC cutoff. Check the kept window the first time you purge after upgrading if the server timezone is not UTC.

The dashboard in this release adds latency and status charts, route and error filters, a custom time range, a hide-bots switch, and optional basic auth. Set `apm.dashboard_auth` when the dashboard is reachable beyond localhost:

```json
{
"apm": {
"dashboard_auth": {
"user": "apm",
"password": "change-me"
}
}
}
```

Leave `user` or `password` empty to keep the dashboard open. The built-in PHP server is still a development server. Put a reverse proxy in front of it on a production host.

Request IDs in `X-Flight-Request-Id` now match `request_token` on the stored row. Bot detection also marks LLM crawlers and metasearch agents such as GPTBot, ClaudeBot, PerplexityBot, and SearxNG.

## Documentation

Want the full scoop? Check out the [FlightPHP APM Documentation](https://docs.flightphp.com/awesome-plugins/apm) for setup details, worker options, dashboard tricks, and more!
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
},
"scripts": {
"test": "phpunit",
"test-coverage": "XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-html=coverage --coverage-clover=clover.xml && vendor/bin/coverage-check clover.xml 100",
"test-coverage": "XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-clover=clover.xml",
"beautify": "phpcbf --standard=phpcs.xml",
"phpcs": "phpcs --standard=phpcs.xml"
}
Expand Down
89 changes: 86 additions & 3 deletions dashboard/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,12 @@
}

[data-theme="dark"] .badge {
color: #ffffff; /* Ensure badge text is always white */
background-color: var(--badge-primary); /* Use primary badge color */
color: #ffffff;
}

[data-theme="dark"] .badge.text-dark,
[data-theme="dark"] .badge.bg-warning {
color: #212529;
}

[data-theme="dark"] .table {
Expand Down Expand Up @@ -151,7 +155,7 @@ body {
}

.card:hover {
transform: translateY(-5px);
transform: none;
}

.card-header {
Expand Down Expand Up @@ -414,3 +418,82 @@ body {
overflow: hidden;
text-overflow: ellipsis;
}

.dashboard-header {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: flex-end;
gap: 1rem;
}

.dashboard-controls {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 0.75rem;
}

.custom-range {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
}

.stat-label {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--badge-secondary);
}

.stat-value {
font-size: 1.35rem;
font-weight: 650;
}

.chart-panel {
height: 280px;
}

.chart-panel canvas {
width: 100% !important;
height: 100% !important;
}

.request-table {
max-height: none;
}

.clickable-row {
cursor: pointer;
}

.waterfall-track {
background: var(--border-color);
border-radius: 4px;
height: 8px;
width: 100%;
}

.waterfall-bar {
background: var(--badge-primary);
border-radius: 4px;
height: 8px;
}

.trace-block {
white-space: pre-wrap;
font-family: monospace;
font-size: 0.8rem;
max-height: 240px;
overflow: auto;
}

@media (max-width: 768px) {
.dashboard-controls,
.dashboard-controls .form-select,
.dashboard-controls .form-control {
width: 100%;
}
}
109 changes: 92 additions & 17 deletions dashboard/index.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
<?php

// since this is a composer package, we need to find the correct autoload.php file
// from some various locations
// Built-in server router: real files (css, js) are served as-is.
if (PHP_SAPI === 'cli-server') {
$requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$file = __DIR__ . $requestPath;
if ($requestPath !== '/' && is_file($file)) {
return false;
}
}

use flight\apm\presenter\PresenterFactory;

Expand All @@ -26,6 +32,7 @@

$app = Flight::app();

$runwayConfig = [];
if (file_exists($appRootPath . '/app/config/config.php') === true) {
$config = require($appRootPath . '/app/config/config.php');
$runwayConfig = $config['runway'] ?? [];
Expand All @@ -37,9 +44,25 @@
if (empty($runwayConfig) && file_exists($appRootPath . '/.runway-config.json') === true) {
$runwayConfig = json_decode(file_get_contents($appRootPath . '/.runway-config.json'), true);
}

$auth = $runwayConfig['apm']['dashboard_auth'] ?? null;
if (is_array($auth) && !empty($auth['user']) && isset($auth['password']) && $auth['password'] !== '') {
$givenUser = $_SERVER['PHP_AUTH_USER'] ?? '';
$givenPass = $_SERVER['PHP_AUTH_PW'] ?? '';
$userOk = hash_equals((string) $auth['user'], (string) $givenUser);
$passOk = hash_equals((string) $auth['password'], (string) $givenPass);
if ($userOk === false || $passOk === false) {
header('WWW-Authenticate: Basic realm="APM Dashboard"');
header('HTTP/1.1 401 Unauthorized');
echo 'Authentication required';
return;
}
}

$presenter = PresenterFactory::create($runwayConfig);

function calculateThreshold($range) {
function calculateThreshold($range)
{
$map = [
'last_hour' => '-1 hour',
'last_day' => '-1 day',
Expand All @@ -48,33 +71,85 @@ function calculateThreshold($range) {
return gmdate('Y-m-d H:i:s', strtotime($map[$range] ?? '-1 hour'));
}

function queryData(): array
{
$query = Flight::request()->query;
if (is_object($query) && method_exists($query, 'getData')) {
return $query->getData();
}
return (array) $query;
}

function resolveWindow(array $query): array
{
$range = (string) ($query['range'] ?? 'last_hour');
$from = (string) ($query['from'] ?? '');
$until = (string) ($query['until'] ?? '');
$stamp = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/';
if ($range === 'custom' && preg_match($stamp, $from) === 1) {
if (preg_match($stamp, $until) !== 1) {
$until = gmdate('Y-m-d H:i:s');
}
return [$range, $from, $until];
}
return [$range === 'custom' ? 'last_hour' : $range, calculateThreshold($range), ''];
}

function workerBacklog(array $runwayConfig): ?int
{
$apm = $runwayConfig['apm'] ?? [];
$dsn = $apm['source_db_dsn'] ?? '';
if ($dsn === '') {
return null;
}
try {
$pdo = new PDO($dsn, $apm['source_db_user'] ?? null, $apm['source_db_pass'] ?? null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$count = $pdo->query('SELECT COUNT(*) FROM apm_metrics_log')->fetchColumn();
return $count === false ? null : (int) $count;
} catch (Throwable $e) {
return null;
}
}

$app->route('GET /apm/dashboard', function () use ($app) {
$app->render('dashboard');
});

// Modified to only return widget data (no requests or pagination)
$app->route('GET /apm/data/dashboard', function () use ($app, $presenter) {
$range = Flight::request()->query['range'] ?? 'last_hour';
$threshold = calculateThreshold($range);
$data = $presenter->getDashboardData($threshold);
$app->route('GET /apm/data/dashboard', function () use ($app, $presenter, $runwayConfig) {
$query = queryData();
[$range, $threshold, $until] = resolveWindow($query);
$filters = $presenter->filtersFromQuery($query);
$filters['until'] = $until;
$filters['range'] = $range;
$data = $presenter->getDashboardData($threshold, $range, $filters);
$data['workerBacklog'] = workerBacklog($runwayConfig);
$app->json($data);
});

// New endpoint specifically for request log data with enhanced custom events search
$app->route('GET /apm/data/requests', function () use ($app, $presenter) {
$range = Flight::request()->query['range'] ?? 'last_hour';
$threshold = calculateThreshold($range);
$page = max(1, (int) (Flight::request()->query['page'] ?? 1));
$query = queryData();
[$range, $threshold, $until] = resolveWindow($query);
$page = max(1, (int) ($query['page'] ?? 1));
$perPage = 50;
$search = Flight::request()->query['search'] ?? '';
$data = $presenter->getRequestsData($threshold, $page, $perPage, $search);
$filters = $presenter->filtersFromQuery($query);
$filters['until'] = $until;
$filters['range'] = $range;
// The bundled page sends details=0 and loads a row when it is opened.
$includeDetails = (string) ($query['details'] ?? '1') !== '0';
$data = $presenter->getRequestsData($threshold, $page, $perPage, '', $includeDetails, $filters);
$app->json($data);
});

// New endpoint to retrieve available event keys for filtering
$app->route('GET /apm/data/requests/@id', function ($id) use ($app, $presenter) {
$app->json($presenter->getRequestDetails((int) $id));
});

$app->route('GET /apm/data/event-keys', function () use ($app, $presenter) {
$range = Flight::request()->query['range'] ?? 'last_hour';
$threshold = calculateThreshold($range);
$query = queryData();
[$range, $threshold] = resolveWindow($query);
$eventKeys = $presenter->getEventKeys($threshold);
$app->json(['event_keys' => $eventKeys]);
});
Expand Down
Loading