oxidecomputer / async-bb8-diesel

Safe asynchronous access to Diesel and the bb8 connection manager
MIT License
12 stars 8 forks source link

async-bb8-diesel

This crate provides an interface for asynchronously accessing a bb8 connection pool atop Diesel.

This is accomplished by implementing an async version of Diesel's "RunQueryDsl" trait, aptly named "AsyncRunQueryDsl", which operates on an async-compatible connection. When called from an async context, these operations transfer the query to a blocking tokio thread, where it may be executed.

NOTE: This crate pre-dated diesel-async. For new code, consider using that interface directly.

Pre-requisites

Comparisons with existing crates

This crate was heavily inspired by both tokio-diesel and bb8-diesel, but serves a slightly different purpose.

What do those crates do?

Both of those crates rely heavily on the tokio::block_in_place function to actually execute synchronous Diesel queries.

Their flow is effectively:

These crates have some advantages by taking this approach:

However, they also have some downsides:

This starvation results in some subtle inhibition of other futures, such as in the following example, where a timeout would be ignored if a long-running database operation was issued from the same task as a timeout.

tokio::select! {
  // Calls "tokio::block_in_place", doing a synchronous Diesel operation
  // on the calling thread...
  _ = perform_database_operation() => {},
  // ... meaning this asynchronous timeout cannot complete!
  _ = sleep_until(timeout) = {},
}

What does this crate do?

This crate attempts to avoid calls to block_in_place - which would block the calling thread - and prefers to use tokio::spawn_blocking function. This function moves the requested operation to an entirely distinct thread where blocking is acceptable, but does not prevent the current task from executing other asynchronous work.

This isn't entirely free - as this work now needs to be transferred to a new thread, it imposes a "Send + 'static" constraint on the queries which are constructed.

Which one is right for me?