Skip to content
perfbaseorgPublic

About

Drupal integration for Perfbase - the PHP profiling service that helps you understand and optimize your application's performance.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Perfbase

Perfbase for Drupal

Drupal integration for Perfbase.

Packagist Version License CI PHP Version Drupal Version

This module is a thin adapter over perfbase/php-sdk. It connects Drupal runtime lifecycles to the Perfbase profiler and ingestion API without implementing its own transport, trace format, or profiler runtime.

What It Supports

This module currently profiles:

  • HTTP requests
  • Drupal cron runs
  • Core Queue API worker execution
  • Symfony console commands dispatched through Drupal's event dispatcher (see Console for the Drush caveat)

This module does not currently add dedicated support for:

  • Messenger workers
  • Batch API execution
  • Install/update hook specific instrumentation
  • Drupal-specific render/entity/cache enrichment beyond what the Perfbase extension already captures

Requirements

  • PHP >=8.1 <8.7 (Drupal 11 itself requires PHP 8.3+)
  • Drupal ^10.3 || ^11.0
  • Composer
  • Perfbase PHP extension installed and enabled
  • A valid Perfbase API key

Installation

Install the module with Composer:

composer require perfbase/drupal

Enable the module:

drush en perfbase

Or enable it through the Drupal admin UI.

Configuration

The module stores runtime configuration in Drupal config as perfbase.settings.

Configuration is resolved in this order:

  1. module defaults
  2. saved Drupal config
  3. settings.php overrides

That resolution logic is implemented in src/Config/ConfigResolver.php.

Admin UI

The settings form is available at:

/admin/config/development/perfbase

The form is implemented in src/Form/PerfbaseSettingsForm.php.

Minimum Required Settings

At minimum, production installs should set:

  • enabled: true
  • api_key: <your Perfbase API key>

Recommended starting values:

  • sample_rate: 0.1
  • profile_http: true
  • exclude_admin_routes: true
  • profile_console: false
  • profile_cron: true
  • profile_queue: true
  • debug: false
  • log_errors: true

settings.php Overrides

Use settings.php for deployment-time overrides that should win over saved config:

$settings['perfbase'] = [
  'enabled' => TRUE,
  'api_key' => 'pb_live_xxxxx',
  'api_url' => 'https://ingress.perfbase.cloud',
  'sample_rate' => 0.10,
  'exclude_admin_routes' => TRUE,
  'profile_http_status_codes' => [...range(200, 299), ...range(500, 599)],
  'profile_http' => TRUE,
  'profile_console' => FALSE,
  'profile_cron' => TRUE,
  'profile_queue' => TRUE,
  'environment' => 'production',
  'app_version' => '2026.04.08',
];

Values set here always win over saved config. The settings form shows them as disabled and leaves them untouched when it saves, so an API key kept in settings.php is never copied into stored configuration or into a config export. Remove the override to edit a value through the form.

Configuration Reference

Key Type Default Notes
enabled bool false Module is effectively disabled until this is true and api_key is non-empty
debug bool false Re-throws profiler exceptions instead of failing open
log_errors bool true Logs profiler/runtime failures when not in debug mode
api_key string '' Required for submission
api_url string https://ingress.perfbase.cloud Override for self-hosted or non-default receiver endpoints
timeout int 10 Submission timeout in seconds; invalid or non-positive values fall back to 10
proxy string '' Optional outbound proxy URL (http, https, socks5, socks5h)
flags int FeatureFlags::DefaultFlags (16775265) Perfbase feature flags bitmask; see Feature Flags
sample_rate float 0.1 Value from 0.0 to 1.0
exclude_admin_routes bool true Drop traces for routes with Drupal's _admin_route option (/admin/* paths and entity edit forms)
profile_http_status_codes int[] 200-299, 500-599 Only HTTP responses with these status codes are submitted; add 404 if you want to keep not-found traces
profile_http bool true Enables HTTP request profiling
profile_console bool false Enables console / Drush profiling
profile_cron bool true Enables cron profiling
profile_queue bool true Enables core Queue API profiling
environment string '' Optional environment label
app_version string '' Optional application version label
include map * per context Include filters for http, console, cron, and queue
exclude map empty per context Exclude filters for http, console, cron, and queue

Persisted defaults are defined in config/install/perfbase.settings.yml, and runtime fallbacks are resolved in src/Config/ConfigResolver.php.

Values from settings.php may be strings (for example read from environment variables): timeout and flags accept integer strings, and an empty api_url or proxy falls back to the default / no proxy.

Feature Flags

flags is passed to the SDK and the Perfbase extension. The admin form shows one checkbox per flag. The default is the SDK's FeatureFlags::DefaultFlags: every feature except per-function CPU time and memory allocation tracking.

Flag Notes
UsePreciseClock Opt-in. High-resolution wall timing on hosts without a fast default clock
TrackCpuTime Opt-in. Per-function CPU time (adds a syscall per call)
TrackMemoryAllocation Per-function memory allocation
TrackExceptions, TrackErrors Exception throws and PHP errors/warnings
TrackMagicMethods Magic method call counts
TrackFileCompilation, TrackOpcache include/require compilation and OPcache statistics
TrackPdo, TrackMongodb, TrackElasticsearch Database and search queries
TrackCaches Redis and Memcached
TrackHttp Outbound HTTP (cURL, Guzzle)
TrackMail, TrackFileOperations, TrackStreams, TrackProc, TrackProcessList Mail, file I/O, stream errors (PHP 8.6+), process execution and a process-list snapshot

A mask of 0, or one containing only the opt-in flags, means "every feature except the opt-in flags" plus any opt-in flags set. Any mask containing a regular flag enables exactly those features. Sites still on the old shipped default (8145) are moved to the current default by the perfbase_post_update_refresh_default_flags post-update (drush updatedb).

Filtering

Each supported context has include and exclude filters:

  • http
  • console
  • cron
  • queue

Supported filter forms:

  • * or .* for match-all
  • /regex/ expressions
  • shell-style glob patterns

Example:

include:
  http:
    - 'GET /admin/*'
  console:
    - 'cache:*'
  cron:
    - 'cron.run'
  queue:
    - 'my_worker'

exclude:
  http:
    - 'GET /healthz'
  console:
    - 'list'

Matching is implemented in src/Support/FilterMatcher.php.

Lifecycle Wiring

HTTP

HTTP profiling is wired through Symfony kernel events:

  • kernel.request
  • kernel.response
  • kernel.exception
  • kernel.terminate

The trace starts on kernel.request (priority 1000), before routing. Route-based decisions are applied when the request terminates: the admin-route exclusion, include filters (which may name routes), and the status-code allowlist all decide whether the trace is submitted or discarded. Exclude filters that already match the request path skip profiling up front.

Implementation:

Console

Console command profiling subscribes to Symfony console events on Drupal's event dispatcher:

  • console.command
  • console.error
  • console.terminate

Drush dispatches console events through its own event dispatcher, not Drupal's, so Drush commands are not traced as console commands even with profile_console: true. Cron and queue work started from Drush (drush cron, drush queue:run) is still traced by the cron and queue integrations.

Implementation:

Cron

Cron profiling is implemented by decorating Drupal’s cron service and wrapping run().

Implementation:

Queue

Queue profiling is implemented by replacing plugin.manager.queue_worker with a Perfbase-aware queue worker manager and wrapping worker instances returned by createInstance().

Implementation:

Queue item exceptions (including SuspendQueueException and RequeueException) are rethrown unchanged, even in debug mode.

Nested Contexts

Drupal nests these contexts: automated cron runs during an HTTP request's kernel.terminate, and cron processes queue items. Only the outermost context traces; nested work is recorded as part of its trace. For example, queue items processed by drush cron are part of the cron trace, while drush queue:run produces one trace per queue item.

Naming and Attributes

The module keeps span names and action values low-cardinality. Span names are fixed by lifecycle (http, cli, cron, and queue; earlier releases named the console span artisan), while the action attribute carries the route, command, cron task, or queue worker identity:

  • HTTP action is METHOD route-path (for example GET /node/{node}), falling back to the route name or a normalized path with numeric and UUID segments replaced
  • console action uses the command name
  • cron action is cron.run
  • queue action uses the queue worker plugin ID

http_url is the full request URL including the query string, passed through the SDK's UrlSanitizer: values of credential-looking parameters (token, password, api_key, signature, nonce, session IDs, email, and similar) are replaced with REDACTED, and user info and fragments are dropped. The hash in one-time login links (/user/reset/{uid}/{timestamp}/{hash}) is also redacted. action never contains the query string.

Common attributes include:

  • source
  • action
  • environment
  • app_version
  • hostname
  • php_version

HTTP requests also attach:

  • http_method
  • http_url
  • http_status_code
  • user_ip
  • user_agent
  • user_id for authenticated users (from Drupal's current_user)
  • drupal.route_name when available

Queue traces also attach queue (the worker plugin ID); console traces attach exit_code and drupal.command. Any trace whose work threw attaches exception (the message).

By default, traces for Drupal admin routes are discarded. You can disable that with exclude_admin_routes: false if you want admin traffic included.

By default, only responses in the configured profile_http_status_codes allowlist are submitted. The runtime default is 200-299 plus 500-599, so 404s are dropped unless you add them explicitly.

Naming logic is implemented in src/Support/SpanNaming.php.

Runtime Behavior

  • The module is fail-open in production mode: profiling and submission errors (including PerfbaseException from submitTrace()) are caught and never change the response or the application's exception.
  • After a failed or rejected submission the trace data is discarded, so it cannot leak into the next trace of a long-running process.
  • Profiling errors are logged when log_errors is enabled.
  • Debug mode rethrows exceptions so integration issues are visible during development.
  • Submission occurs through the shared SDK and uses the installed Perfbase PHP extension.

Shared runtime services:

Production Notes

  • Use settings.php for API keys and deployment-controlled overrides.
  • Keep debug disabled in production.
  • Start with a conservative sample_rate and increase as needed.
  • Exclude health checks, noisy admin paths, or high-volume commands if they are not useful to retain.
  • If you use a custom receiver, set api_url explicitly.

Validation

Current package validation includes:

  • PHPUnit
  • PHPStan level 9 with Drupal-aware analysis
  • PHPCS with Drupal coding standards
  • GitHub Actions on Drupal 10.x with PHP 8.1, and Drupal 11.x with PHP 8.3, 8.5 and 8.6
  • Non-blocking GitHub Actions rows for the upcoming Drupal 11.5 (PHP 8.3) and Drupal 12.0 (PHP 8.5 and 8.6) pre-releases. A failing pre-release row does not fail the workflow.

The current suite focuses on unit coverage plus fixture-backed wiring checks. It is not yet a full booted-Drupal kernel test suite. Passing against a pre-release does not by itself declare support for it: the drupal/core constraint and core_version_requirement are widened only once a release has been checked on a real site.

Development

Install dependencies:

composer install

Run the full validation stack:

composer run lint

Run individual checks:

composer run test
composer run phpstan
composer run phpcs
XDEBUG_MODE=coverage vendor/bin/phpunit -c phpunit.xml --coverage-text

This package keeps Drupal scaffold output for fixture-based validation under tests/fixtures/drupal/web.

Documentation

Full documentation is available at perfbase.com/docs.

License

Apache-2.0. See LICENSE.txt.

About

Drupal integration for Perfbase - the PHP profiling service that helps you understand and optimize your application's performance.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages