A job's models are read from the worker's default connection before anything can switch it

Aperta
#413 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
25/100
Tipo di issue
Funzionalità
Chiarezza
Da chiarire
Stato di attività
Attiva
Stack tecnologico
rust, sqlite
Ambito
backend, databases

Direzione di ricerca

Read crates/queue/src/queue/job.rs around lines 374–393 and the scoped default connections and models in jobs sections of the database and queues guides. The issue leaves the behavior open among several approaches, so first get a maintainer decision before implementing anything. The reported tests are in tests/queue_models.rs; done means the agreed behavior works for both cases in the reproduction and is documented.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

The problem

The worker restores a job from its payload, which reads its model fields from the database, and only then builds and runs the job's middleware (job.rs#L374-L393). Each run also starts in a fresh context, so a db::using_connection scope that was active at dispatch doesn't carry over. Nothing an application or package writes runs before the models are read, so they always come from the worker's default connection.

For an application that uses scoped default connections, for example one database per tenant, a job with a model field then does one of two things:

  • If the default connection has a row with the same key, the job runs with that row. Nothing reports it.
  • If it doesn't, the worker deletes the job with the MissingModels outcome before any middleware runs, or fails it for good with fail_when_missing_models.

The same applies to a queued listener whose event holds models (including Created<M> and Updated<M>), to the failed hook, which restores the job again outside its middleware, and to chain and batch callbacks, which have no middleware.

#226 listed the connection as its first open question ("A model without #[model(connection)] dispatched inside db::using_connection is restored from its default connection"). I couldn't find a later decision, so I'm asking here.

Reproduction

Two SQLite connections, primary (the default) and archive, each with a users table and a user under key 1 with a different name.

use laravel::container::Inject;
use laravel::db;
use laravel::queue::{IntoMiddleware, Next, Queueable, job, middleware};

#[middleware]
async fn on_archive(next: Next) -> laravel::Result<()> {
    db::using_connection("archive", next.run()).await
}

#[derive(Queueable)]
struct Greet {
    user: User,
}

#[job]
impl Greet {
    fn middleware(&self) -> impl IntoMiddleware {
        on_archive
    }

    async fn handle(self, records: Inject<Records>) {
        let connection = db::manager().default_connection_name();
        records.push(format!("greeted {} on {connection}", self.user.name));
    }
}

Dispatching Greet { user } with the archive user and running queue:work:

primary has a user with key 1 Expected Actual
Yes greeted Archived Taylor on archive greeted Taylor on archive
No greeted Archived Taylor on archive Job deleted, JobProcessed reports missing models

I have both cases as tests in tests/queue_models.rs, in the style of the existing ones, and can open a PR with them.

What works today

Carrying the key and reading the model in handle works, because handle runs inside the middleware:

#[derive(Queueable)]
struct Greet {
    user_id: i64,
}

The queues guide doesn't say this is needed. Models in jobs says the worker reloads the model "before handle runs", and Creating jobs says context values "such as the active tenant" reach the job, which reads as if a tenant-aware job with a model field would work.

Options I considered

  1. Document it. Say in the queues guide that models are read before middleware, from the worker's default connection, and that a job dispatched for another connection should carry keys. No code change. The wrong-row case stays silent for anyone who hasn't read it.
  2. Carry the scoped default connection in the payload, as #226 hinted, and apply it around the job's contexts on the worker. No new public API. It changes the rule that a new application scope doesn't inherit using_connection, and a connection added at runtime may not exist in the worker.
  3. A queue-wide hook that wraps each job's context, registered once like global HTTP middleware, which runs before the restore. It would also need to cover the failed hook and callbacks. One new registration method.
  4. Restore in two phases, so job middleware runs before models load. middleware(&self) takes the restored job, so this changes the signature of Job::middleware and QueuedListener::middleware. It still leaves the failed hook and callbacks.
  5. A field type that opts out of loading. This is what an i64 field already does.

Options 2 and 3 are the only ones that remove the silent case, and both are design decisions I don't think a contributor should make alone.

Question

Which direction would you prefer? I'm opening a docs-only PR for option 1 and will link it here. I'm happy to implement option 2 or 3 if you say which fits. If the answer is that models in jobs are meant for the default connection only, the docs change alone would settle it.

Lingua principale
Rust
Stelle
847
Fork
174
Merge medio
5h 40m
PR unite (30g)
167

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di laravel/rust-framework

Tutte le issue di laravel/rust-framework

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.