Skip to main content

with_request_scope

Function with_request_scope 

Source
pub async fn with_request_scope<F, R>(
    pool: &PgPool,
    company: Uuid,
    f: F,
) -> Result<R, Error>
where F: Future<Output = R>,
Expand description

Run f with a request-dedicated connection whose app.company_id is set to company.

Acquires one connection from pool, sets the session variable on it, and binds it as the request connection for the duration of f. Every scoped execute helper called inside f — from the ORM or a hand-written service — runs on this connection, so the whole request shares one company scope set exactly once (no per-statement transaction, and ID-only lookups are fenced too). The variable is reset before the connection returns to the pool, so it can never ride into the next request.

Trade-off: this pins a pooled connection for the request’s lifetime (vs. connection-per-statement), so size the pool for peak concurrent requests. Prefer this at the HTTP composition root; leave non-request callers (jobs) on with_company_scope (per-statement scoping).