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,sumandavg), 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
- Configuration
- Dashboard
- Capturing entries
- Recording your own entries
- Performance
- Commands
- Differences from PHP
- Not yet ported (planned for a later release)
- License
§Installation
cargo add laravel-pulseRegister 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 migratePulse 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:
| Recorder | Section | Variables |
|---|---|---|
Servers | ServersConfig | PULSE_SERVER_NAME, PULSE_SERVER_DIRECTORIES |
SlowRequests | SlowRequestsConfig | PULSE_SLOW_REQUESTS_ENABLED, _SAMPLE_RATE, _THRESHOLD |
UserRequests | UserRequestsConfig | PULSE_USER_REQUESTS_ENABLED, _SAMPLE_RATE |
Exceptions | ExceptionsConfig | PULSE_EXCEPTIONS_ENABLED, _SAMPLE_RATE, _LOCATION |
SlowQueries | SlowQueriesConfig | PULSE_SLOW_QUERIES_ENABLED, _SAMPLE_RATE, _THRESHOLD, _LOCATION, _MAX_QUERY_LENGTH |
SlowJobs | SlowJobsConfig | PULSE_SLOW_JOBS_ENABLED, _SAMPLE_RATE, _THRESHOLD |
Queues | QueuesConfig | PULSE_QUEUES_ENABLED, _SAMPLE_RATE |
CacheInteractions | CacheInteractionsConfig | PULSE_CACHE_INTERACTIONS_ENABLED, _SAMPLE_RATE |
SlowOutgoingRequests | SlowOutgoingRequestsConfig | PULSE_SLOW_OUTGOING_REQUESTS_ENABLED, _SAMPLE_RATE, _THRESHOLD |
UserJobs | UserJobsConfig | PULSE_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
| Recorder | Records | Laravel Rust hook |
|---|---|---|
| Servers | CPU, memory and disk of each server, every 15 seconds of pulse:check | SharedBeat event |
| Slow Requests | requests slower than the threshold, by method, route and handler | global middleware |
| User Requests | requests per logged-in user | web and api middleware |
| Exceptions | reported errors, by type and location | errors().report_all |
| Slow Queries | queries slower than the threshold, by SQL and call site | DatabaseManager::listen |
| Slow Jobs | job attempts slower than the threshold | JobProcessed event |
| Queues | processed, released and failed jobs per connection and queue | JobProcessed 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
CacheHitandCacheMissed; Laravel Rust’s cache dispatches no events. - Slow Outgoing Requests listens to the HTTP client’s
ResponseReceivedandConnectionFailed; Laravel Rust’s HTTP client dispatches no events yet. An upstream change addinglaravel::http::client::events::ResponseReceivedandConnectionFailedis 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’
queuedandprocessinglines needJobQueuedandJobProcessing, which don’t exist either. Itsprocessed,releasedandfailedlines are recorded fromJobProcessed’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_raterecords 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 inpulse:work. - Redis ingest: with the
redisfeature andPULSE_INGEST_DRIVER=redis, requests add their entries to thelaravel:pulse:ingeststream, andpulse:workmoves 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. viewPulseis 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’sLogoutlistener 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 overPULSE_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’sDebouncedoutcome (a job replaced before it ran) has no PHP counterpart and isn’t recorded; a job deleted for missing models counts asprocessed, as PHP’sJobProcesseddoes. - CPU, memory and disk come from the
sysinfocrate in place oftop,/proc/meminfoanddisk_*_space(); the first CPU reading waits 200ms. Memory used is total less available, as PHP reads it on Linux. The server’s key isStr::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 inPULSE_INGEST_KEEPkeeps that many stream items. - MySQL and MariaDB upserts use
VALUES(), PHP’s default withoutuse_upsert_alias.
§Not yet ported (planned for a later release)
- Customizing the dashboard: publishing it, card
cols,rows,expandandignore-after, custom cards andPulse::css();PULSE_DOMAINand thepulse.middlewarelist. - The Cache Interactions, Slow Outgoing Requests and User Jobs recorders and Queues’
queuedandprocessing, once Laravel Rust dispatches their events, with thegroupssettings andPulse::defaultVendorCacheKeys(). - Running the migration on
PULSE_DB_CONNECTION; it runs on the default connection, while reads and writes usePULSE_DB_CONNECTION. - A Redis stream PHP’s
pulse:workcan read. aboutcommand details.
§License
MIT. See LICENSE.md.
Structs§
- Aggregate
Row - A key’s aggregates, as
Pulse::aggregatereturns them. Only the requested aggregates are set. - Aggregate
Types Row - A key’s aggregate per type, as
Pulse::aggregate_typesreturns it. - Authorize
Http\Middleware\Authorize: a403unless theviewPulsegate allows the request.- Cache
Interactions Config 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_entriesand the aggregates it adds to. - Exceptions
Config Recorders\Exceptions.- Isolated
Beat - 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. - Pending
Entry - The entry that
Pulse::recordreturns. Choose its aggregates, as->max()->count()does in PHP; the entry is buffered when this is dropped, at the end of the statement: - Pending
Value - The value that
Pulse::setreturns; it’s buffered when this is dropped. - Pulse
- Pulse: the
Pulsefacade. - Pulse
Config config/pulse.phpwithout itsrecorders.- Pulse
Service Provider - Registers Pulse’s configuration, migration, recorders, dashboard and
pulse:*commands: - Queues
Config Recorders\Queues.- Record
Requests - Records each request’s duration and user, then ingests Pulse’s buffer: the
SlowRequestsandUserRequestsrecorders andwhenRequestLifecycleIsLongerThan(-1, ingest). Added as global middleware, so the duration covers the whole request. - Remember
Route - Remembers the matched route and the logged-in user’s ID for
RecordRequests. Added to thewebandapigroups, so it runs after the route matched and the session started. - Servers
Config Recorders\Servers.- Shared
Beat - Dispatched every second on each server that runs
pulse:check:SharedBeat. Listen to it to record something on every server. - Slow
Jobs Config Recorders\SlowJobs.- Slow
Outgoing Requests Config 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.- Slow
Queries Config Recorders\SlowQueries.- Slow
Requests Config Recorders\SlowRequests.- Stored
Value - A row of
pulse_values, asPulse::valuesreturns it. - User
Card - How the dashboard shows a user:
Users::find()’s object. - User
Jobs Config 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.- User
Requests Config 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
viewPulsegate: the gate given toPulseServiceProvider::gate, or only in thelocalenvironment, as PHP’s default definition.
Type Aliases§
- Detect
Cpu Servers::detectCpuUsing(): the CPU usage in percent.- Detect
Memory Servers::detectMemoryUsing(): the total and used memory in megabytes.- Gate
- Decides who may open the dashboard: the
viewPulsegate. - Graph
- Graph points by key, then by type, then by bucket time (
Y-m-d H:i:s, UTC): 60 points each.