Skip to main content

Tx

Struct Tx 

Source
pub struct Tx<DB: QueueDatabase> { /* private fields */ }
Expand description

The delivery’s transaction, lent to the handler: it dereferences to the connection the transaction runs on, and goes back to the delivery when the handler ends.

A handler takes it as its first Ctx parameter, Ctx(mut tx): Ctx<keys::Tx<DB>>, on a registration mounted with transactional. It writes through &mut *tx, as through the connection of a sqlx transaction, and (&mut *tx).begin() nests a savepoint of its own. The delivery’s settlement ends the transaction: acknowledgement commits it, every other outcome rolls the handler’s writes back first. Dropping Tx gives the transaction back and ends nothing. A Tx dropped by a panic marks the handler’s writes for the rollback, so a delivery acknowledged after its handler panicked, as the skip panic policy does, commits none of them.

Tx is an owned value, so a handler may move it into a task of its own. The transaction must be back when the delivery settles: a settlement that finds it still lent fails with SqlxBrokerError::TransactionHeld, and the transaction rolls back when that Tx drops.

§Examples

use ruststream_sqlx::prelude::*;
use sqlx::{PgPool, Postgres};

#[derive(Inbox, sqlx::FromRow)]
#[inbox(table = "payment_jobs")]
pub struct PaymentJob {
    #[field(id)]
    id: i64,
    #[field(payload)]
    payload: Vec<u8>,
}

#[derive(serde::Deserialize)]
struct Payment {
    account: String,
    cents: i64,
}

#[subscriber(InboxQueue::<PaymentJob>::new("payments"))]
async fn post(payment: &Payment, Ctx(mut tx): Ctx<keys::Tx<Postgres>>) -> HandlerOutcome {
    let posted = sqlx::query("INSERT INTO ledger (account, cents) VALUES ($1, $2)")
        .bind(&payment.account)
        .bind(payment.cents)
        .execute(&mut *tx)
        .await;
    match posted {
        // The commit keeps the ledger row and finishes the job, together.
        Ok(_) => HandlerOutcome::ack(),
        // The retry discards the ledger row and returns the job to the queue.
        Err(error) => {
            tracing::warn!(%error, "the payment was not posted");
            HandlerOutcome::retry()
        }
    }
}

pub fn app(pool: PgPool) -> RustStream {
    RustStream::new(AppInfo::new("payments", "0.1.0")).with_broker(SqlxBroker::new(pool), |b| {
        b.include(post.transactional());
    })
}

Trait Implementations§

Source§

impl<DB: QueueDatabase> AsMut<<DB as Database>::Connection> for Tx<DB>

Source§

fn as_mut(&mut self) -> &mut DB::Connection

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl<DB: QueueDatabase> Debug for Tx<DB>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<DB: QueueDatabase> Deref for Tx<DB>

Source§

fn deref(&self) -> &DB::Connection

The connection inside the delivery’s transaction.

§Panics

Never: Tx holds the transaction until it drops.

Source§

type Target = <DB as Database>::Connection

The resulting type after dereferencing.
Source§

impl<DB: QueueDatabase> DerefMut for Tx<DB>

Source§

fn deref_mut(&mut self) -> &mut DB::Connection

The connection inside the delivery’s transaction, to run a statement on.

§Panics

Never: Tx holds the transaction until it drops.

Source§

impl<DB: QueueDatabase> Drop for Tx<DB>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl<DB> !RefUnwindSafe for Tx<DB>

§

impl<DB> !UnwindSafe for Tx<DB>

§

impl<DB> Freeze for Tx<DB>
where Option<Lent<DB>>: Freeze,

§

impl<DB> Send for Tx<DB>
where Option<Lent<DB>>: Send,

§

impl<DB> Sync for Tx<DB>
where Option<Lent<DB>>: Sync,

§

impl<DB> Unpin for Tx<DB>
where Option<Lent<DB>>: Unpin,

§

impl<DB> UnsafeUnpin for Tx<DB>
where Option<Lent<DB>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<R> CryptoRng for R
where R: TryCryptoRng<Error = !> + ?Sized,

Source§

impl<T> Formattable for T
where T: Deref, <T as Deref>::Target: Formattable,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Parsable for T
where T: Deref, <T as Deref>::Target: Parsable,

Source§

impl<T> PublishedThrough<DefaultSlot> for T

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<R> Rng for R
where R: TryRng<Error = !> + ?Sized,

Source§

fn next_u32(&mut self) -> u32

Return the next random u32.
Source§

fn next_u64(&mut self) -> u64

Return the next random u64.
Source§

fn fill_bytes(&mut self, dst: &mut [u8])

Fill dest with random data. Read more
Source§

impl<R> RngCore for R
where R: Rng,

Source§

impl<R> RngExt for R
where R: Rng + ?Sized,

Source§

fn random<T>(&mut self) -> T

Return a random value via the StandardUniform distribution. Read more
Source§

fn random_iter<T>(self) -> Iter<StandardUniform, Self, T> ⓘ

Return an iterator over random variates Read more
Source§

fn random_range<T, R>(&mut self, range: R) -> T
where T: SampleUniform, R: SampleRange<T>,

Generate a random value in the given range. Read more
Source§

fn random_bool(&mut self, p: f64) -> bool

Return a bool with a probability p of being true. Read more
Source§

fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool

Return a bool with a probability of numerator/denominator of being true. Read more
Source§

fn sample<T, D>(&mut self, distr: D) -> T
where D: Distribution<T>,

Sample a new value, using the given distribution. Read more
Source§

fn sample_iter<T, D>(self, distr: D) -> Iter<D, Self, T> ⓘ
where D: Distribution<T>, Self: Sized,

Create an iterator that generates values using the given distribution. Read more
Source§

fn fill<T>(&mut self, dest: &mut [T])
where T: Fill,

Fill any type implementing Fill with random data Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<R> TryCryptoRng for R
where R: DerefMut, <R as Deref>::Target: TryCryptoRng,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<R> TryRng for R
where R: DerefMut, <R as Deref>::Target: TryRng,

Source§

type Error = <<R as Deref>::Target as TryRng>::Error

The type returned in the event of a RNG error. Read more
Source§

fn try_next_u32(&mut self) -> Result<u32, <R as TryRng>::Error>

Return the next random u32.
Source§

fn try_next_u64(&mut self) -> Result<u64, <R as TryRng>::Error>

Return the next random u64.
Source§

fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), <R as TryRng>::Error>

Fill dst entirely with random data.
Source§

impl<R> TryRngCore for R
where R: TryRng,

Source§

type Error = <R as TryRng>::Error

👎Deprecated since 0.10.0:

use TryRng instead

Error type.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more