Skip to main content

Crate laravel_pulse

Crate laravel_pulse 

Source
Expand description

§Pulse for Laravel Rust

laravel-pulse is a port of laravel/pulse to Laravel Rust. It gives you at-a-glance insights into your application’s performance and usage: slow requests, slow queries, slow jobs, exceptions, queue throughput, your servers’ CPU, memory and disk, and your most active users, on Pulse’s dashboard at /pulse.

[!NOTE] This is a community port maintained by Rivervo. It is not an official Laravel package. It follows laravel/pulse 1.11.0: the same three tables and migration, the same bucketed aggregates (periods of 60, 360, 1440 and 10080 minutes with count, min, max, sum and avg), entry types, keys and environment variables, so a Rust and a PHP application can share one Pulse database. All credit for the design goes to Taylor Otwell and the package’s contributors.

§Installation

cargo add laravel-pulse

Register the service provider in src/app.rs, then run your migrations, which create the pulse_values, pulse_entries and pulse_aggregates tables:

ⓘ
use laravel_pulse::PulseServiceProvider;

Application::configure()
    .with_providers(|providers| {
        providers.add(PulseServiceProvider::new().user::<User>());
    })
laravel migrate

Pulse stores its data in MySQL, MariaDB, PostgreSQL or SQLite, as in PHP. Enable your driver on laravel-rust, or with this crate’s sqlite, postgres or mysql feature.

Run pulse:check on each server to record its CPU, memory and disk usage:

laravel pulse:check

§Configuration

PulseConfig holds config/pulse.php’s settings with the same environment variables and defaults: PULSE_ENABLED, PULSE_PATH, PULSE_STORAGE_DRIVER, PULSE_STORAGE_KEEP, PULSE_DB_CONNECTION, PULSE_INGEST_DRIVER, PULSE_INGEST_BUFFER, PULSE_INGEST_KEEP, PULSE_REDIS_CONNECTION and PULSE_CACHE_DRIVER. Each recorder has a section of its own, as the recorders array holds them in PHP, with the same variables:

RecorderSectionVariables
ServersServersConfigPULSE_SERVER_NAME, PULSE_SERVER_DIRECTORIES
SlowRequestsSlowRequestsConfigPULSE_SLOW_REQUESTS_ENABLED, _SAMPLE_RATE, _THRESHOLD
UserRequestsUserRequestsConfigPULSE_USER_REQUESTS_ENABLED, _SAMPLE_RATE
ExceptionsExceptionsConfigPULSE_EXCEPTIONS_ENABLED, _SAMPLE_RATE, _LOCATION
SlowQueriesSlowQueriesConfigPULSE_SLOW_QUERIES_ENABLED, _SAMPLE_RATE, _THRESHOLD, _LOCATION, _MAX_QUERY_LENGTH
SlowJobsSlowJobsConfigPULSE_SLOW_JOBS_ENABLED, _SAMPLE_RATE, _THRESHOLD
QueuesQueuesConfigPULSE_QUEUES_ENABLED, _SAMPLE_RATE
CacheInteractionsCacheInteractionsConfigPULSE_CACHE_INTERACTIONS_ENABLED, _SAMPLE_RATE
SlowOutgoingRequestsSlowOutgoingRequestsConfigPULSE_SLOW_OUTGOING_REQUESTS_ENABLED, _SAMPLE_RATE, _THRESHOLD
UserJobsUserJobsConfigPULSE_USER_JOBS_ENABLED, _SAMPLE_RATE

The ignore lists take PHP regular expressions with their delimiters, such as /^App\\Jobs\\Sync/ or #^/api#, and default to PHP’s: the dashboard and Telescope for the request recorders, and Pulse’s and Telescope’s tables for slow queries. PHP’s per-pattern thresholds are the thresholds lists, such as vec![("#^/admin#".into(), 500), ("default".into(), 2000)]. Change them in src/app.rs:

ⓘ
Application::configure()
    .with_config(|config, _| {
        config.section_mut::<SlowRequestsConfig>().ignore.push("#^/health#".to_owned());
        config.section_mut::<SlowJobsConfig>().thresholds = vec![("#^App\\\\Jobs\\\\Import#".to_owned(), 30_000)];
    })

§Dashboard

§Authorization

The dashboard is at /pulse (PULSE_PATH). As in PHP, the viewPulse gate lets only the local environment in until you define it:

ⓘ
PulseServiceProvider::new().gate(|request| {
    Box::pin(async move {
        let Ok(auth) = laravel::auth::Auth::<User>::of(request).await else { return false };
        auth.user().await.ok().flatten().is_some_and(|user| user.email == "admin@example.com")
    })
})

Each application keeps its own gate, so several applications in one process (such as parallel tests) don’t share it.

PulseServiceProvider::ignore_routes() leaves the route out, so you can register laravel_pulse::dashboard yourself, behind the Authorize middleware or your own.

§Content Security Policy

When the request has a CSP nonce, the dashboard’s <style> and <script> tags and the font stylesheet’s <link> carry it as nonce="...", as Laravel’s Vite helper does for stylesheets. Without one, they have no nonce attribute. The nonce is Laravel Rust’s per-request laravel::view::csp_nonce(), which laravel-csp’s middleware sets, or laravel::view::use_csp_nonce(..) in your own middleware. PHP’s Pulse has no nonce setting.

The page has no inline event handlers or style attributes: the cards’ sort selects submit through the page’s script, and the Queues card’s legend colors are classes in its stylesheet. A strict policy still needs fonts.bunny.net in font-src for the Figtree font, and data: in img-src for the favicon.

§Cards

The dashboard has PHP’s cards in PHP’s layout, with Pulse’s own stylesheet: Servers, Application Usage, Queues, Cache, Slow Queries, Exceptions, Slow Requests, Slow Jobs and Slow Outgoing Requests, the period selector (1h, 6h, 24h, 7d) and each card’s sort, kept in the query string as PHP’s #[Url] properties are. Cards refresh every 5 seconds.

§Users

PulseServiceProvider::user::<User>() records the logged-in user of each request and shows users on the Application Usage card by their model’s name, email and avatar fields, with a Gravatar when there’s no avatar, as PHP’s Users resolver does. To show users your own way, as Pulse::users() does, return their fields by ID:

ⓘ
PulseServiceProvider::new().users(|ids| async move {
    // ids: Vec<String> → IndexMap<String, serde_json::Value> of {"name", "email", "avatar"}
    load_users(ids).await
})

§Capturing entries

RecorderRecordsLaravel Rust hook
ServersCPU, memory and disk of each server, every 15 seconds of pulse:checkSharedBeat event
Slow Requestsrequests slower than the threshold, by method, route and handlerglobal middleware
User Requestsrequests per logged-in userweb and api middleware
Exceptionsreported errors, by type and locationerrors().report_all
Slow Queriesqueries slower than the threshold, by SQL and call siteDatabaseManager::listen
Slow Jobsjob attempts slower than the thresholdJobProcessed event
Queuesprocessed, released and failed jobs per connection and queueJobProcessed event
Cache Interactions— (blocked, see below)—
Slow Outgoing Requests— (blocked, see below)—
User Jobs— (blocked, see below)—

Servers::detectCpuUsing() and detectMemoryUsing() are detect_cpu_using(|| ..) and detect_memory_using(|| (total_mb, used_mb)) on the provider. pulse:check dispatches SharedBeat every second on each server and IsolatedBeat on one server only; listen to them to record your own server metrics.

§Recorders blocked by missing framework events

Laravel Rust 0.2 doesn’t dispatch the events these recorders listen to in PHP, so they can’t record yet. Their settings exist, and their cards show whatever data a PHP application writes to a shared database:

  • Cache Interactions listens to CacheHit and CacheMissed; Laravel Rust’s cache dispatches no events.
  • Slow Outgoing Requests listens to the HTTP client’s ResponseReceived and ConnectionFailed; Laravel Rust’s HTTP client dispatches no events yet. An upstream change adding laravel::http::client::events::ResponseReceived and ConnectionFailed is in progress; this recorder lands once it’s released.
  • User Jobs listens to JobQueued; Laravel Rust’s queue has no event for dispatching a job.
  • Queues’ queued and processing lines need JobQueued and JobProcessing, which don’t exist either. Its processed, released and failed lines are recorded from JobProcessed’s outcome.

§Recording your own entries

Pulse::record() and Pulse::set() work as in PHP. Pick the aggregates on the returned entry; it’s buffered at the end of the statement:

ⓘ
use laravel_pulse::Pulse;

Pulse::record("user_sale", user.id.to_string(), Some(amount)).sum().count();
Pulse::set("deployment", "web", commit_sha);

Pulse::lazy(), filter(), ignore(), start_recording(), stop_recording(), flush(), report() and handle_exceptions_using() match PHP’s, and values(), graph(), aggregate(), aggregate_types(), aggregate_total() / aggregate_totals() read what’s stored, for your own pages.

§Performance

  • Sampling: each recorder’s sample_rate records only that share of events; the dashboard shows counts scaled back up with a ~. Queues sample by job, so a job’s events are sampled together.
  • Trimming: stored data is kept for PULSE_STORAGE_KEEP (at most 7 days); trimming runs after an ingest by the [1, 1000] lottery and every 10 minutes in pulse:work.
  • Redis ingest: with the redis feature and PULSE_INGEST_DRIVER=redis, requests add their entries to the laravel:pulse:ingest stream, and pulse:work moves them to the database.
  • Handling errors: Pulse drops errors from recording and ingesting, as in PHP; Pulse::handle_exceptions_using(|error| ..) lets you see them.

§Commands

laravel pulse:check            # each server, under a process monitor; --once for one beat
laravel pulse:work             # with the redis ingest; --stop-when-empty
laravel pulse:restart          # stop running check and work commands after the current beat
laravel pulse:clear --type=exception   # or pulse:purge; --force in production

§Differences from PHP

  • The dashboard is rendered on the server. Laravel Rust has no Livewire, so cards aren’t Livewire components: the page refreshes its cards every 5 seconds instead of wire:poll, selectors are links and forms, and the graphs are inline SVG instead of Chart.js. Its time zone is UTC.
  • viewPulse is a callback on the provider, since Laravel Rust authorizes with policies rather than named gates.
  • Users come from .user::<User>() or .users(..). The request’s user is the one logged in when the request reaches its route, so a login or logout during that request isn’t counted for it, and PHP’s Logout listener has no counterpart.
  • Slow requests’ “via” is the route’s handler path, such as app::http::handlers::users::show, in place of PHP’s controller action. The duration covers the whole request; Pulse ingests at the end of each request before the response is returned (PHP ingests after sending it), and early, as background work, when the buffer is over PULSE_INGEST_BUFFER.
  • Exceptions are keyed by the error’s type name and the place it was created, from Rust’s Location, in place of the PHP class and first application stack frame.
  • Slow queries’ location is the query’s call site.
  • Slow jobs time each attempt with JobProcessed’s duration. Laravel Rust’s Debounced outcome (a job replaced before it ran) has no PHP counterpart and isn’t recorded; a job deleted for missing models counts as processed, as PHP’s JobProcessed does.
  • CPU, memory and disk come from the sysinfo crate in place of top, /proc/meminfo and disk_*_space(); the first CPU reading waits 200ms. Memory used is total less available, as PHP reads it on Linux. The server’s key is Str::slug() of its name, without PHP’s transliteration of non-ASCII letters.
  • The Redis stream holds JSON in place of PHP’s serialize(), and keys have no Redis prefix, so PHP and Rust workers don’t share a stream. A whole number in PULSE_INGEST_KEEP keeps that many stream items.
  • MySQL and MariaDB upserts use VALUES(), PHP’s default without use_upsert_alias.

§Not yet ported (planned for a later release)

  • Customizing the dashboard: publishing it, card cols, rows, expand and ignore-after, custom cards and Pulse::css(); PULSE_DOMAIN and the pulse.middleware list.
  • The Cache Interactions, Slow Outgoing Requests and User Jobs recorders and Queues’ queued and processing, once Laravel Rust dispatches their events, with the groups settings and Pulse::defaultVendorCacheKeys().
  • Running the migration on PULSE_DB_CONNECTION; it runs on the default connection, while reads and writes use PULSE_DB_CONNECTION.
  • A Redis stream PHP’s pulse:work can read.
  • about command details.

§License

MIT. See LICENSE.md.

Structs§

AggregateRow
A key’s aggregates, as Pulse::aggregate returns them. Only the requested aggregates are set.
AggregateTypesRow
A key’s aggregate per type, as Pulse::aggregate_types returns it.
Authorize
Http\Middleware\Authorize: a 403 unless the viewPulse gate allows the request.
CacheInteractionsConfig
Recorders\CacheInteractions. Laravel Rust’s cache dispatches no events yet, so the recorder can’t record; the settings are here so the dashboard’s card reads them as in PHP.
Entry
A recorded entry: a row of pulse_entries and the aggregates it adds to.
ExceptionsConfig
Recorders\Exceptions.
IsolatedBeat
Dispatched every second on only one of the servers that run pulse:check, the one holding the lock: IsolatedBeat. Listen to it to record something once for the whole application.
PendingEntry
The entry that Pulse::record returns. Choose its aggregates, as ->max()->count() does in PHP; the entry is buffered when this is dropped, at the end of the statement:
PendingValue
The value that Pulse::set returns; it’s buffered when this is dropped.
Pulse
Pulse: the Pulse facade.
PulseConfig
config/pulse.php without its recorders.
PulseServiceProvider
Registers Pulse’s configuration, migration, recorders, dashboard and pulse:* commands:
QueuesConfig
Recorders\Queues.
RecordRequests
Records each request’s duration and user, then ingests Pulse’s buffer: the SlowRequests and UserRequests recorders and whenRequestLifecycleIsLongerThan(-1, ingest). Added as global middleware, so the duration covers the whole request.
RememberRoute
Remembers the matched route and the logged-in user’s ID for RecordRequests. Added to the web and api groups, so it runs after the route matched and the session started.
ServersConfig
Recorders\Servers.
SharedBeat
Dispatched every second on each server that runs pulse:check: SharedBeat. Listen to it to record something on every server.
SlowJobsConfig
Recorders\SlowJobs.
SlowOutgoingRequestsConfig
Recorders\SlowOutgoingRequests. Laravel Rust’s HTTP client dispatches no events yet, so the recorder can’t record; the settings are here so the dashboard’s card reads them as in PHP.
SlowQueriesConfig
Recorders\SlowQueries.
SlowRequestsConfig
Recorders\SlowRequests.
StoredValue
A row of pulse_values, as Pulse::values returns it.
UserCard
How the dashboard shows a user: Users::find()’s object.
UserJobsConfig
Recorders\UserJobs. Laravel Rust’s queue dispatches no event when a job is queued yet, so the recorder can’t record; the settings are here so the dashboard’s card reads them as in PHP.
UserRequestsConfig
Recorders\UserRequests.
Value
A value: a row of pulse_values, which keeps the latest value per type and key.

Enums§

Aggregate
An aggregation Pulse keeps for an entry in pulse_aggregates.
Item
An entry or a value waiting to be ingested.

Constants§

PERIODS
The aggregate periods, in minutes: an hour, 6 hours, 24 hours and 7 days.

Functions§

dashboard
GET /pulse: the dashboard.
view_pulse
The viewPulse gate: the gate given to PulseServiceProvider::gate, or only in the local environment, as PHP’s default definition.

Type Aliases§

DetectCpu
Servers::detectCpuUsing(): the CPU usage in percent.
DetectMemory
Servers::detectMemoryUsing(): the total and used memory in megabytes.
Gate
Decides who may open the dashboard: the viewPulse gate.
Graph
Graph points by key, then by type, then by bucket time (Y-m-d H:i:s, UTC): 60 points each.