google-cloud-rust icon indicating copy to clipboard operation
google-cloud-rust copied to clipboard

spanner: allow reusing sessions with begin_read_write_transaction

Open danielnorberg opened this issue 6 months ago • 2 comments

When using begin_read_write_transaction to manually handle the transaction lifecycle it would be useful to be able to reuse the session when retrying transactions that fail with an ABORTED error to retain lock priority and increase the likelihood that the retried transaction can commit.

Does it sound reasonable to expose the session in the client and transaction api in this manner?

I see that the transaction finish method returns the Option<ManagedSession> as part of the error. Maybe client get_session method could be made public and there could be variants of begin_read_write_transaction and end that take & return the session? Then the user would be partly responsible for the session lifecycle as well.

danielnorberg avatar May 15 '25 06:05 danielnorberg

Hi @danielnorberg

The session management is complex and we don't want to expose client.get_session(). If the purpose is to reuse sessions when using begin_read_write_transaction, how about creating TransactionManager that holds session.

async fn run(client: Client) -> Result<(), Error>{
    let retry = &mut TransactionRetry::new();
    // TransactionManager holds session 
    let tm: TransactionManager = client.new_transaction_manager().await?;
    loop {
          // Reuse session with begin_read_write_transaction
          let tx = &mut tm.begin_read_write_transaction().await?;
          let result = run_in_transaction(tx).await;
    
          // try to commit or rollback transaction.
          match tx.end(result, None).await {
              Ok((_commit_timestamp, success)) => return Ok(success),
              Err(err) => retry.next(err).await? // check retry
          }
     }
}

yoshidan avatar May 28 '25 01:05 yoshidan

That sounds good to me. I'll try to put together a PR to implement a TransactionManager.

danielnorberg avatar Jun 02 '25 06:06 danielnorberg