Skip to main content

Crate laravel_horizon

Crate laravel_horizon 

Source
Expand description

§Horizon for Laravel Rust

laravel-horizon is a port of laravel/horizon to Laravel Rust. It runs your Redis queue workers from one code-driven configuration, balances worker processes between queues, records every job, its tags and its failures in Redis, keeps throughput and runtime metrics, and shows all of it in Horizon’s dashboard.

[!NOTE] This is a community port maintained by Rivervo. It is not an official Laravel package. It follows laravel/horizon 5.52.0: the same dashboard (the package’s compiled Vue app, unchanged), the same /horizon/api JSON endpoints, Redis keys, configuration, balancing, trimming, metrics, tags and horizon:* commands, with Rust naming. All credit for the design goes to Taylor Otwell and the package’s contributors.

§Installation

Horizon works with Redis queues, so enable Laravel’s redis feature, then add the crate:

cargo add laravel-rust --features redis
cargo add laravel-horizon

Register the service provider in src/app.rs:

ⓘ
use laravel_horizon::HorizonServiceProvider;

Application::configure()
    .with_providers(|providers| {
        providers.add(HorizonServiceProvider::new());
    })

and send your jobs to Redis:

QUEUE_CONNECTION=redis
REDIS_URL=redis://127.0.0.1:6379

There is nothing to migrate: Horizon keeps everything in Redis. The dashboard is at /horizon.

The provider registers Horizon’s own redis queue driver, as PHP Horizon replaces Laravel’s Redis connector. It stores jobs exactly as Laravel Rust’s Redis driver does (the same keys), so queue:work, queue:clear and queue sizes keep working, and it records each job in Horizon as it’s pushed, reserved and released.

§Configuration

HorizonConfig holds config/horizon.php with the same environment variables: HORIZON_NAME, HORIZON_DOMAIN, HORIZON_PATH (horizon), HORIZON_PREFIX (the slug of APP_NAME followed by _horizon:) and HORIZON_ENV. Change the rest in src/app.rs, or with the provider’s configure:

ⓘ
use laravel_horizon::{Balance, HorizonConfig, SupervisorConfig};

Application::configure().with_config(|config, _| {
    let horizon = config.section_mut::<HorizonConfig>();
    horizon.use_connection = "default".into(); // `use`
    horizon.trim.recent = 60;                  // minutes
    horizon.trim.failed = 10080;
    horizon.silenced = vec!["app::jobs::Heartbeat".into()];
    horizon.environment(
        "production",
        [(
            "supervisor-1",
            SupervisorConfig::new()
                .connection("redis")
                .queue(["high", "default"])
                .balance(Balance::Auto)
                .min_processes(1)
                .max_processes(10)
                .balance_max_shift(1)
                .balance_cooldown(3)
                .memory(128),
        )],
    );
})
PHP (config/horizon.php)Rust (HorizonConfig)Default
name, domain, path, prefix, envname, domain, path, prefix, envfrom the environment variables above
useuse_connectiondefault
waitswaitsredis:default → 60
trim.recent, pending, completed, recent_failed, failed, monitoredtrim.*60, 60, 60, 10080, 10080, 10080
silenced, silenced_tagssilenced, silenced_tags (job names, tags)empty
metrics.trim_snapshots.job, .queuetrim_snapshots.job, .queue24, 24
metrics.snapshot_locksnapshot_lock300
fast_terminationfast_terminationfalse
memory_limitmemory_limit (MB)64
defaultsdefaultssupervisor-1 as in PHP
environmentsenvironmentsproduction and local as in PHP

A supervisor’s options in environments fall back to the same supervisor’s defaults, as array_replace_recursive does. Environments are matched in order with * wildcards, and horizon starts the first environment that matches --environment, HORIZON_ENV or APP_ENV.

SupervisorConfig has connection, queue, balance (Balance::Off, Simple, Auto), auto_scaling_strategy (Time, Size, Log), min_processes, max_processes, balance_max_shift, balance_cooldown, max_time, max_jobs, memory, tries, timeout, sleep and nice.

§Balancing

Each supervisor runs worker processes: your application’s own binary running queue:work <connection> --queue=<queues>, one job at a time, restarted when it exits. With Balance::Off, one pool of processes works the supervisor’s queues in order. With Balance::Simple, each queue gets an equal pool. With Balance::Auto, the processes move every balance_cooldown seconds, by at most balance_max_shift, to the queues with the most work, measured by the time their jobs take to clear (Time), their number of jobs (Size) or its logarithm (Log), between min_processes and max_processes. The scaling is PHP’s AutoScaler, line for line.

§Dashboard authorization

As in PHP, the dashboard opens only in the local environment until you say who may open it, Horizon::auth():

ⓘ
HorizonServiceProvider::new().auth(|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 == "taylor@laravel.com")
    })
})

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

The dashboard is served under the web middleware group, on HORIZON_DOMAIN when it’s set.

§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. With another CSP middleware, set it with laravel::view::use_csp_nonce(..) or with PHP’s Horizon::cspNonce():

ⓘ
laravel_horizon::csp_nonce(&nonce); // for the current request

The nonce alone isn’t enough for a strict policy. As in PHP, the dashboard’s Vue app compiles its templates in the browser, which needs 'unsafe-eval' in script-src, and the page loads the Figtree font from fonts.bunny.net (font-src; the stylesheet itself carries the nonce). Its favicon is a data: image (img-src).

§Running Horizon

Run the master supervisor in the foreground, under systemd or Supervisor in production:

laravel horizon
laravel horizon --environment=production
laravel horizon:status          # exits 0 when running, 1 when paused, 2 when inactive
laravel horizon:pause           # signals this machine's masters (USR2)
laravel horizon:continue        # (CONT)
laravel horizon:terminate       # (TERM) — run it on every deploy; --wait with fast_termination
laravel horizon:list            # the running machines
laravel horizon:clear redis --queue=emails
laravel horizon:snapshot        # schedule it every five minutes
laravel horizon:clear-metrics

Schedule the snapshot that fills the metrics graphs:

ⓘ
#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.command("horizon:snapshot").every_five_minutes();
}

§Tags

Jobs get tags as they’re pushed. In PHP a job’s tags() method gives them; here the provider takes a function of the job’s name and data:

ⓘ
HorizonServiceProvider::new().tags(|name, data| match name {
    "app::jobs::RenderVideo" => vec![format!("video:{}", data["video_id"])],
    _ => Vec::new(),
})

Monitor a tag from the dashboard’s Monitoring screen to keep its jobs for trim.monitored minutes. Failed jobs are tagged failed:{tag} too, and jobs with a tag in silenced_tags, or a name in silenced or registered with laravel_horizon::silence_jobs([...]) (for packages, whatever the order of the providers), show under Silenced instead of Completed. Inside the application, silence_jobs silences the names for that application only; called outside any application (such as in a provider’s register), it can’t reach one, so the names apply to every application in the process. In register, use laravel_horizon::silence_jobs_in(app.config(), [...]) to silence them for that application only. The provider’s tags(..) and spawn_workers_with(..) also belong to its own application.

§Metrics

Every job that completes adds its runtime to its job’s and its queue’s throughput and average runtime. horizon:snapshot stores them, with each queue’s wait time, keeps the last trim_snapshots of each, and starts the counts again. The dashboard’s jobs per minute, maximum runtime and throughput, wait times and the metrics graphs read them.

§Long waits

Once a minute, the master supervisor works out how long each queue its supervisors work takes to clear, as the dashboard’s wait times do, and dispatches laravel_horizon::events::LongWaitDetected for each queue whose wait is over its waits threshold. A queue without a threshold has 60 seconds, and a threshold of 0 turns the check off for that queue. As in PHP, a Redis lock lets only one machine check each minute. Listen for the event to be told about it:

ⓘ
use laravel::event::Event;
use laravel_horizon::events::LongWaitDetected;

Application::configure()
    .with_events(|events, _| {
        events.listen(|event: Event<LongWaitDetected>| async move {
            tracing::warn!(
                "Queue {}:{} has a wait of {} seconds",
                event.connection, event.queue, event.seconds
            );
        });
    })

§Differences from PHP

  • Workers. PHP runs each supervisor as its own horizon:supervisor process, whose workers run horizon:work. Here the supervisors are part of the horizon process, which loops them every second, and each worker is a process of your binary running Laravel Rust’s queue:work with --sleep, --max-jobs and --max-time (under nice -n when nice is set). A supervisor’s pid in the dashboard is the master’s. HorizonServiceProvider::spawn_workers_with replaces how workers start, as WorkerCommandString::$command does.
  • tries and timeout don’t reach the workers: Laravel Rust’s queue:work has no --tries or --timeout; they’re set on each job with #[job(tries = .., timeout = ..)]. The supervisor keeps them in its options, and timeout is how long a scaled-down worker may take to exit before it’s killed, as in PHP.
  • memory is checked by the supervisor, which asks a worker over the limit to finish its job and exit, and starts it again; PHP’s worker checks itself.
  • Pausing. Laravel Rust’s worker can’t pause, so horizon:pause asks each worker to finish its job and exit, and horizon:continue starts them again. The supervisor keeps its process count while paused.
  • Tags come from the provider’s tags(..) function instead of a job’s tags() method, and there’s no automatic tagging of Eloquent models.
  • Job data. The dashboard shows the job’s data as Laravel Rust stores it (JSON), not PHP’s serialized command, so the “delayed until” line from the serialized command isn’t shown.
  • Recording never fails a dispatch: if Horizon can’t write its record, it logs a warning, and the job stays queued.
  • The dashboard’s monitor, stop-monitoring and retry actions run at once rather than as queued MonitorTag, StopMonitoringTag and RetryFailedJob jobs. A retry gets a new ID and retry_of, and its dispatched_at is reset so a retry_for window starts again, as PHP resets retryUntil.
  • Horizon’s own data is on the Redis connection use_connection with prefix before each key, as PHP’s horizon connection.
  • horizon:terminate also stores Laravel Rust’s queue:restart signal, as PHP stores illuminate:queue:restart.
  • Laravel Rust has no maintenance mode, so the dashboard has no maintenance banner. Horizon needs Unix: the master is managed with signals, as in PHP.

§Not yet ported (planned for a later release)

  • Long-wait notifications: the mail, Slack and SMS notification PHP’s SendNotification sends for LongWaitDetected, and the Horizon::routeMailNotificationsTo/routeSlackNotificationsTo/routeSmsNotificationsTo settings. The event itself is dispatched (see Long waits).
  • The Batches screen and its API (/api/batches), over Laravel Rust’s job batches.
  • horizon:supervisor, horizon:work, horizon:supervisors, horizon:supervisor-status, horizon:pause-supervisor, horizon:continue-supervisor, horizon:forget, horizon:purge, horizon:timeout, horizon:listen, horizon:install, horizon:publish, and the Redis command queue they use.
  • The events MasterSupervisorLooped, SupervisorLooped, WorkerProcessRestarting, UnableToLaunchProcess and the others in Laravel\Horizon\Events, as Laravel Rust events.
  • Horizon::night(), proxy_path, MasterSupervisor::determineNameUsing(), and Redis Cluster hash-tagged prefixes.

§License

MIT. See LICENSE.md.

Modules§

events
The events Horizon dispatches, as Laravel Rust events: Laravel\Horizon\Events.
repositories
The repositories Horizon keeps its data in, on its Redis connection.
supervisor
The master supervisor and its supervisors: MasterSupervisor, Supervisor, ProcessPool, WorkerProcess and AutoScaler.

Structs§

Authenticate
Authenticate: a 403 unless check allows the request.
HorizonConfig
The package’s settings: config/horizon.php, with the same environment variables and defaults.
HorizonJob
A job HorizonRedisQueue reserved for a worker.
HorizonRedisQueue
Horizon’s redis queue driver: Laravel Rust’s Redis queue, recording each job in Horizon.
HorizonServiceProvider
Registers the HorizonConfig section, Horizon’s redis queue driver, the listeners that record jobs and metrics, the dashboard and the horizon commands:
JobPayload
A job’s payload, decoded: JobPayload.
ProvisioningPlan
The supervisors each environment starts: ProvisioningPlan.
SupervisorConfig
One supervisor’s options in defaults or environments. Options left None come from the supervisor’s defaults, as array_replace_recursive does in PHP.
SupervisorOptions
A supervisor’s settings: SupervisorOptions.
Trim
How many minutes Horizon keeps each list of jobs: trim.
TrimSnapshots
How many metric snapshots Horizon keeps: metrics.trim_snapshots.

Enums§

AutoScalingStrategy
How auto balancing measures a queue’s work: the autoScalingStrategy option.
Balance
How a supervisor shares its processes among its queues: the balance option.

Functions§

check
Horizon::check(): the auth() callback, or only in the local environment.
csp_nonce
Horizon::cspNonce(): sets the Content Security Policy nonce that the dashboard’s <style>, <script> and stylesheet <link> tags carry, for the current request.
is_recording
Whether Horizon records the jobs of the queue connection connection: those using the redis driver, which Horizon replaces.
retry_failed_job
Pushes the failed job id again under a new ID, and records the retry on it: RetryFailedJob. Does nothing when no failed job has the ID.
silence_jobs
Silences jobs by name, as silenced does, for the current application: a package can call it at any time, whatever the order of the providers, as PHP packages push to horizon.silenced in their boot. Horizon checks these names alongside HorizonConfig::silenced.
silence_jobs_in
Silences jobs by name for the application whose configuration is config, such as from a provider’s register with app.config(). Without Horizon’s provider in that application, it does nothing.
silenced_job_names
The job names silence_jobs silenced: the current application’s and those silenced outside any application.

Type Aliases§

AuthUsing
Decides who may open the dashboard: Horizon::auth().
TagsUsing
Finds the tags of a job from its name and its data: Tags::for().