use tokio_postgres::error::SqlState;
use super::{ATTEMPTS, Connection, Pool, contended, failure};
use crate::conversation::{Error, Refused};
use tokio_postgres::Transaction;
pub(in crate::postgres) enum Failure {
Domain(Error),
Database(tokio_postgres::Error),
}
impl From<Error> for Failure {
fn from(error: Error) -> Self {
Self::Domain(error)
}
}
impl From<Refused> for Failure {
fn from(error: Refused) -> Self {
Self::Domain(error.into())
}
}
impl From<tokio_postgres::Error> for Failure {
fn from(error: tokio_postgres::Error) -> Self {
Self::Database(error)
}
}
impl Connection {
pub(super) async fn lock_conversation(
&mut self,
schema: &str,
id: &str,
) -> Result<Transaction<'_>, tokio_postgres::Error> {
let key = format!("{schema}:records:{id}");
let tx = self
.client
.build_transaction()
.isolation_level(tokio_postgres::IsolationLevel::ReadCommitted)
.start()
.await?;
tx.execute(super::super::sql!("changes/lock"), &[&key])
.await?;
Ok(tx)
}
}
impl Pool {
#[cfg(test)]
pub(in crate::postgres) fn set_test_repeatable_read(&self) -> std::io::Result<()> {
self.runtime.block_on(async {
for _ in 0..super::CONNECTIONS {
let mut held = self.checkout().await?;
held.as_mut().expect("checked out").client
.batch_execute("SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ")
.await.map_err(failure)?;
}
Ok(())
})
}
pub(in crate::postgres) fn record_mutation<T>(
&self,
id: &str,
apply: impl AsyncFn(&Transaction<'_>) -> Result<T, Failure>,
) -> Result<T, Error> {
self.runtime.block_on(async {
for attempt in 0..ATTEMPTS {
let mut held = self.checkout().await?;
let connection = held.as_mut().expect("checked out");
let tx = connection
.lock_conversation(&self.schema, id)
.await
.map_err(failure)?;
let error = match apply(&tx).await {
Ok(answer) => match tx.commit().await {
Ok(()) => return Ok(answer),
Err(error) => error,
},
Err(error) => {
tx.rollback().await.map_err(failure)?;
match error {
Failure::Domain(error) => return Err(error),
Failure::Database(error) => error,
}
}
};
let aborted =
contended(&error) || error.code() == Some(&SqlState::T_R_SERIALIZATION_FAILURE);
if !aborted || attempt + 1 == ATTEMPTS {
return Err(failure(error).into());
}
drop(held);
let jitter = uuid::Uuid::new_v4().as_u128() % (10_000 * (attempt as u128 + 1));
tokio::time::sleep(std::time::Duration::from_micros(jitter as u64)).await;
}
unreachable!("the last attempt always returns")
})
}
}