Skip to main content

gcloud_spanner/
client.rs

1use std::env::var;
2use std::fmt::Debug;
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6use std::time::Duration;
7
8use google_cloud_gax::conn::{ConnectionOptions, Environment};
9use google_cloud_gax::grpc::{Code, Status};
10use google_cloud_gax::retry::{invoke_fn, TryAs};
11use google_cloud_googleapis::spanner::v1::{commit_request, transaction_options, Mutation, TransactionOptions};
12use token_source::NoopTokenSourceProvider;
13
14use crate::apiv1::conn_pool::{ConnectionManager, SPANNER};
15use crate::metrics::{MetricsConfig, MetricsRecorder};
16use crate::retry::TransactionRetrySetting;
17use crate::session::{ManagedSession, SessionConfig, SessionError, SessionManager};
18use crate::statement::Statement;
19use crate::transaction::{CallOptions, QueryOptions};
20use crate::transaction_ro::{BatchReadOnlyTransaction, ReadOnlyTransaction};
21use crate::transaction_rw::{commit, CommitOptions, CommitResult, ReadWriteTransaction};
22use crate::value::TimestampBound;
23
24#[derive(Clone, Default)]
25pub struct PartitionedUpdateOption {
26    pub begin_options: CallOptions,
27    pub query_options: Option<QueryOptions>,
28    /// The transaction tag to use for partitioned update operations.
29    pub transaction_tag: Option<String>,
30}
31
32#[derive(Clone)]
33pub struct ReadOnlyTransactionOption {
34    pub timestamp_bound: TimestampBound,
35    pub call_options: CallOptions,
36}
37
38impl Default for ReadOnlyTransactionOption {
39    fn default() -> Self {
40        ReadOnlyTransactionOption {
41            timestamp_bound: TimestampBound::strong_read(),
42            call_options: CallOptions::default(),
43        }
44    }
45}
46
47#[derive(Clone, Default)]
48pub struct ReadWriteTransactionOption {
49    pub begin_options: CallOptions,
50    pub commit_options: CommitOptions,
51    /// The transaction tag to use for this read/write transaction.
52    pub transaction_tag: Option<String>,
53}
54
55#[derive(Clone, Debug)]
56pub struct ChannelConfig {
57    /// num_channels is the number of gRPC channels.
58    pub num_channels: usize,
59    pub connect_timeout: Duration,
60    pub timeout: Duration,
61    pub http2_keep_alive_interval: Option<Duration>,
62    pub keep_alive_timeout: Option<Duration>,
63    pub keep_alive_while_idle: Option<bool>,
64}
65
66impl Default for ChannelConfig {
67    fn default() -> Self {
68        ChannelConfig {
69            num_channels: 4,
70            connect_timeout: Duration::from_secs(30),
71            timeout: Duration::from_secs(30),
72            http2_keep_alive_interval: None,
73            keep_alive_timeout: None,
74            keep_alive_while_idle: None,
75        }
76    }
77}
78
79/// ClientConfig has configurations for the client.
80#[derive(Debug)]
81pub struct ClientConfig {
82    /// SessionPoolConfig is the configuration for session pool.
83    pub session_config: SessionConfig,
84    /// ChannelConfig is the configuration for gRPC connection.
85    pub channel_config: ChannelConfig,
86    /// Overriding service endpoint
87    pub endpoint: String,
88    /// Runtime project
89    pub environment: Environment,
90    /// DisableRouteToLeader specifies if all the requests of type read-write and PDML need to be routed to the leader region.
91    pub disable_route_to_leader: bool,
92    /// Metrics configuration for emitting OpenTelemetry signals.
93    pub metrics: MetricsConfig,
94}
95
96impl Default for ClientConfig {
97    fn default() -> Self {
98        let mut config = ClientConfig {
99            channel_config: Default::default(),
100            session_config: Default::default(),
101            endpoint: SPANNER.to_string(),
102            environment: match var("SPANNER_EMULATOR_HOST").ok() {
103                Some(v) => Environment::Emulator(v),
104                None => Environment::GoogleCloud(Box::new(NoopTokenSourceProvider {})),
105            },
106            disable_route_to_leader: false,
107            metrics: MetricsConfig::default(),
108        };
109        config.session_config.min_opened = config.channel_config.num_channels * 4;
110        config.session_config.max_opened = config.channel_config.num_channels * 100;
111        config
112    }
113}
114
115#[cfg(feature = "auth")]
116pub use google_cloud_auth;
117use google_cloud_googleapis::spanner::v1::transaction_options::IsolationLevel;
118
119#[cfg(feature = "auth")]
120impl ClientConfig {
121    pub async fn with_auth(mut self) -> Result<Self, google_cloud_auth::error::Error> {
122        if let Environment::GoogleCloud(_) = self.environment {
123            let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new(Self::auth_config()).await?;
124            self.environment = Environment::GoogleCloud(Box::new(ts))
125        }
126        Ok(self)
127    }
128
129    pub async fn with_credentials(
130        mut self,
131        credentials: google_cloud_auth::credentials::CredentialsFile,
132    ) -> Result<Self, google_cloud_auth::error::Error> {
133        if let Environment::GoogleCloud(_) = self.environment {
134            let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new_with_credentials(
135                Self::auth_config(),
136                Box::new(credentials),
137            )
138            .await?;
139            self.environment = Environment::GoogleCloud(Box::new(ts))
140        }
141        Ok(self)
142    }
143
144    fn auth_config() -> google_cloud_auth::project::Config<'static> {
145        google_cloud_auth::project::Config::default()
146            .with_audience(crate::apiv1::conn_pool::AUDIENCE)
147            .with_scopes(&crate::apiv1::conn_pool::SCOPES)
148    }
149}
150
151#[derive(thiserror::Error, Debug)]
152pub enum Error {
153    #[error(transparent)]
154    GRPC(#[from] Status),
155
156    #[error(transparent)]
157    InvalidSession(#[from] SessionError),
158
159    #[error(transparent)]
160    ParseError(#[from] crate::row::Error),
161
162    #[error(transparent)]
163    Connection(#[from] google_cloud_gax::conn::Error),
164
165    #[error("invalid config: {0}")]
166    InvalidConfig(String),
167}
168
169impl TryAs<Status> for Error {
170    fn try_as(&self) -> Option<&Status> {
171        match self {
172            Error::GRPC(e) => Some(e),
173            _ => None,
174        }
175    }
176}
177
178/// Compression used for Spanner gRPC requests and responses.
179#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
180#[non_exhaustive]
181pub enum Compression {
182    /// Sends uncompressed requests and does not request compressed responses.
183    #[default]
184    Identity,
185    /// Compresses requests and requests gzip-compressed responses.
186    Gzip,
187}
188
189/// Builds a Spanner client with optional transport settings.
190///
191/// Use [`Client::builder`] to create a builder. Additional settings can be added
192/// without changing [`ClientConfig`] or the existing [`Client::new`] constructor.
193#[derive(Debug)]
194#[must_use]
195pub struct ClientBuilder {
196    database: String,
197    config: ClientConfig,
198    compression: Compression,
199}
200
201impl ClientBuilder {
202    /// Replaces the client configuration. Defaults to [`ClientConfig::default`].
203    ///
204    /// Configure authentication on `config` before passing it to this method.
205    /// This does not change the builder's transport settings.
206    pub fn config(mut self, config: ClientConfig) -> Self {
207        self.config = config;
208        self
209    }
210
211    /// Selects request and response compression. Defaults to [`Compression::Identity`].
212    pub fn compression(mut self, compression: Compression) -> Self {
213        self.compression = compression;
214        self
215    }
216
217    /// Connects to Spanner and initializes the session pool.
218    pub async fn build(self) -> Result<Client, Error> {
219        let Self {
220            database,
221            config,
222            compression,
223        } = self;
224        if config.session_config.max_opened > config.channel_config.num_channels * 100 {
225            return Err(Error::InvalidConfig(format!(
226                "max session size is {} because max session size is 100 per gRPC connection",
227                config.channel_config.num_channels * 100
228            )));
229        }
230
231        let metrics = Arc::new(
232            MetricsRecorder::try_new(&database, &config.metrics).map_err(|e| Error::InvalidConfig(e.to_string()))?,
233        );
234
235        let pool_size = config.channel_config.num_channels;
236        let options = ConnectionOptions {
237            timeout: Some(config.channel_config.timeout),
238            connect_timeout: Some(config.channel_config.connect_timeout),
239            http2_keep_alive_interval: config.channel_config.http2_keep_alive_interval,
240            keep_alive_timeout: config.channel_config.keep_alive_timeout,
241            keep_alive_while_idle: config.channel_config.keep_alive_while_idle,
242        };
243        let conn_pool = ConnectionManager::new(pool_size, &config.environment, config.endpoint.as_str(), &options)
244            .await?
245            .with_gzip(match compression {
246                Compression::Identity => false,
247                Compression::Gzip => true,
248            });
249        let session_manager = SessionManager::new(
250            database,
251            conn_pool,
252            config.session_config,
253            config.disable_route_to_leader,
254            metrics.clone(),
255        )
256        .await?;
257
258        Ok(Client {
259            sessions: session_manager,
260            disable_route_to_leader: config.disable_route_to_leader,
261        })
262    }
263}
264
265/// Client is a client for reading and writing data to a Cloud Spanner database.
266/// A client is safe to use concurrently, except for its Close method.
267#[derive(Clone)]
268pub struct Client {
269    sessions: Arc<SessionManager>,
270    disable_route_to_leader: bool,
271}
272
273impl Client {
274    /// new creates a client to a database. A valid database name has
275    /// the form projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID.
276    pub async fn new(database: impl Into<String>, config: ClientConfig) -> Result<Self, Error> {
277        Self::builder(database).config(config).build().await
278    }
279
280    /// Creates a builder with default configuration and compression disabled.
281    /// A valid database name has the form
282    /// projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID.
283    pub fn builder(database: impl Into<String>) -> ClientBuilder {
284        ClientBuilder {
285            database: database.into(),
286            config: ClientConfig::default(),
287            compression: Compression::default(),
288        }
289    }
290
291    /// Close closes all the sessions gracefully.
292    /// This method can be called only once.
293    ///
294    /// Dropping the last `Client` clone instead also stops the background tasks,
295    /// but server-side sessions are left to expire (about one hour idle).
296    pub async fn close(self) {
297        self.sessions.close().await;
298    }
299
300    /// single provides a read-only snapshot transaction optimized for the case
301    /// where only a single read or query is needed.  This is more efficient than
302    /// using read_only_transaction for a single read or query.
303    /// ```
304    /// use google_cloud_spanner::key::Key;
305    /// use google_cloud_spanner::statement::ToKind;
306    /// use google_cloud_spanner::client::Client;
307    ///
308    /// #[tokio::main]
309    /// async fn run(client: Client) {
310    ///     let mut tx = client.single().await.unwrap();
311    ///     let iter1 = tx.read("Guild",&["GuildID", "OwnerUserID"], vec![
312    ///         Key::new(&"pk1"),
313    ///         Key::new(&"pk2")
314    ///     ]).await.unwrap();
315    /// }
316    /// ```
317    pub async fn single(&self) -> Result<ReadOnlyTransaction, Error> {
318        self.single_with_timestamp_bound(TimestampBound::strong_read()).await
319    }
320
321    /// single provides a read-only snapshot transaction optimized for the case
322    /// where only a single read or query is needed.  This is more efficient than
323    /// using read_only_transaction for a single read or query.
324    pub async fn single_with_timestamp_bound(&self, tb: TimestampBound) -> Result<ReadOnlyTransaction, Error> {
325        let session = self.get_session().await?;
326        let result = ReadOnlyTransaction::single(session, tb).await?;
327        Ok(result)
328    }
329
330    /// read_only_transaction returns a ReadOnlyTransaction that can be used for
331    /// multiple reads from the database.
332    ///
333    /// ```ignore
334    /// use google_cloud_spanner::client::{Client, Error};
335    /// use google_cloud_spanner::statement::Statement;
336    /// use google_cloud_spanner::key::Key;
337    ///
338    /// async fn run(client: Client) -> Result<(), Error>{
339    ///     let mut tx = client.read_only_transaction().await?;
340    ///
341    ///     let mut stmt = Statement::new("SELECT * , \
342    ///             ARRAY (SELECT AS STRUCT * FROM UserItem WHERE UserId = @Param1 ) AS UserItem, \
343    ///             ARRAY (SELECT AS STRUCT * FROM UserCharacter WHERE UserId = @Param1 ) AS UserCharacter  \
344    ///             FROM User \
345    ///             WHERE UserId = @Param1");
346    ///
347    ///     stmt.add_param("Param1", user_id);
348    ///     let mut reader = tx.query(stmt).await?;
349    ///     let mut data = vec![];
350    ///     while let Some(row) = reader.next().await? {
351    ///         let user_id= row.column_by_name::<String>("UserId")?;
352    ///         let user_items= row.column_by_name::<Vec<model::UserItem>>("UserItem")?;
353    ///         let user_characters = row.column_by_name::<Vec<model::UserCharacter>>("UserCharacter")?;
354    ///         data.push(user_id);
355    ///     }
356    ///
357    ///     let mut reader2 = tx.read("User", &["UserId"], vec![
358    ///         Key::new(&"user-1"),
359    ///         Key::new(&"user-2")
360    ///     ]).await?;
361    ///
362    ///     Ok(())
363    /// }
364    pub async fn read_only_transaction(&self) -> Result<ReadOnlyTransaction, Error> {
365        self.read_only_transaction_with_option(ReadOnlyTransactionOption::default())
366            .await
367    }
368
369    /// read_only_transaction returns a ReadOnlyTransaction that can be used for
370    /// multiple reads from the database.
371    pub async fn read_only_transaction_with_option(
372        &self,
373        options: ReadOnlyTransactionOption,
374    ) -> Result<ReadOnlyTransaction, Error> {
375        let session = self.get_session().await?;
376        let result = ReadOnlyTransaction::begin(session, options.timestamp_bound, options.call_options).await?;
377        Ok(result)
378    }
379
380    /// batch_read_only_transaction returns a BatchReadOnlyTransaction that can be used
381    /// for partitioned reads or queries from a snapshot of the database. This is
382    /// useful in batch processing pipelines where one wants to divide the work of
383    /// reading from the database across multiple machines.
384    pub async fn batch_read_only_transaction(&self) -> Result<BatchReadOnlyTransaction, Error> {
385        self.batch_read_only_transaction_with_option(ReadOnlyTransactionOption::default())
386            .await
387    }
388
389    /// batch_read_only_transaction returns a BatchReadOnlyTransaction that can be used
390    /// for partitioned reads or queries from a snapshot of the database. This is
391    /// useful in batch processing pipelines where one wants to divide the work of
392    /// reading from the database across multiple machines.
393    pub async fn batch_read_only_transaction_with_option(
394        &self,
395        options: ReadOnlyTransactionOption,
396    ) -> Result<BatchReadOnlyTransaction, Error> {
397        let session = self.get_session().await?;
398        let result = BatchReadOnlyTransaction::begin(session, options.timestamp_bound, options.call_options).await?;
399        Ok(result)
400    }
401
402    /// partitioned_update executes a DML statement in parallel across the database,
403    /// using separate, internal transactions that commit independently. The DML
404    /// statement must be fully partitionable: it must be expressible as the union
405    /// of many statements each of which accesses only a single row of the table. The
406    /// statement should also be idempotent, because it may be applied more than once.
407    ///
408    /// PartitionedUpdate returns an estimated count of the number of rows affected.
409    /// The actual number of affected rows may be greater than the estimate.
410    pub async fn partitioned_update(&self, stmt: Statement) -> Result<i64, Error> {
411        self.partitioned_update_with_option(stmt, PartitionedUpdateOption::default())
412            .await
413    }
414
415    /// partitioned_update executes a DML statement in parallel across the database,
416    /// using separate, internal transactions that commit independently. The DML
417    /// statement must be fully partitionable: it must be expressible as the union
418    /// of many statements each of which accesses only a single row of the table. The
419    /// statement should also be idempotent, because it may be applied more than once.
420    ///
421    /// PartitionedUpdate returns an estimated count of the number of rows affected.
422    /// The actual number of affected rows may be greater than the estimate.
423    pub async fn partitioned_update_with_option(
424        &self,
425        stmt: Statement,
426        options: PartitionedUpdateOption,
427    ) -> Result<i64, Error> {
428        let ro = TransactionRetrySetting::new(vec![Code::Aborted, Code::Internal]);
429        let session = Some(self.get_session().await?);
430
431        // reuse session
432        invoke_fn(
433            Some(ro),
434            |session| async {
435                let mut tx = match ReadWriteTransaction::begin_partitioned_dml(
436                    session.unwrap(),
437                    options.begin_options.clone(),
438                    options.transaction_tag.clone(),
439                    self.disable_route_to_leader,
440                )
441                .await
442                {
443                    Ok(tx) => tx,
444                    Err(e) => return Err((Error::GRPC(e.status), Some(e.session))),
445                };
446                tx.update_with_option(stmt.clone(), options.query_options.clone().unwrap_or_default())
447                    .await
448                    .map_err(|e| (Error::GRPC(e), tx.take_session()))
449            },
450            session,
451        )
452        .await
453    }
454
455    /// apply_at_least_once may attempt to apply mutations more than once; if
456    /// the mutations are not idempotent, this may lead to a failure being reported
457    /// when the mutation was applied more than once. For example, an insert may
458    /// fail with ALREADY_EXISTS even though the row did not exist before Apply was
459    /// called. For this reason, most users of the library will prefer not to use
460    /// this option.  However, apply_at_least_once requires only a single RPC, whereas
461    /// apply's default replay protection may require an additional RPC.  So this
462    /// method may be appropriate for latency sensitive and/or high throughput blind
463    /// writing.
464    pub async fn apply_at_least_once(&self, ms: Vec<Mutation>) -> Result<Option<CommitResult>, Error> {
465        self.apply_at_least_once_with_option(ms, CommitOptions::default()).await
466    }
467
468    /// apply_at_least_once may attempt to apply mutations more than once; if
469    /// the mutations are not idempotent, this may lead to a failure being reported
470    /// when the mutation was applied more than once. For example, an insert may
471    /// fail with ALREADY_EXISTS even though the row did not exist before Apply was
472    /// called. For this reason, most users of the library will prefer not to use
473    /// this option.  However, apply_at_least_once requires only a single RPC, whereas
474    /// apply's default replay protection may require an additional RPC.  So this
475    /// method may be appropriate for latency sensitive and/or high throughput blind
476    /// writing.
477    pub async fn apply_at_least_once_with_option(
478        &self,
479        ms: Vec<Mutation>,
480        options: CommitOptions,
481    ) -> Result<Option<CommitResult>, Error> {
482        let ro = TransactionRetrySetting::default();
483        let mut session = self.get_session().await?;
484
485        invoke_fn(
486            Some(ro),
487            |session| async {
488                let tx = commit_request::Transaction::SingleUseTransaction(TransactionOptions {
489                    exclude_txn_from_change_streams: false,
490                    mode: Some(transaction_options::Mode::ReadWrite(transaction_options::ReadWrite::default())),
491                    isolation_level: IsolationLevel::Unspecified as i32,
492                });
493                match commit(session, ms.clone(), tx, options.clone(), self.disable_route_to_leader).await {
494                    Ok(s) => Ok(Some(s.into())),
495                    Err(e) => Err((Error::GRPC(e), session)),
496                }
497            },
498            &mut session,
499        )
500        .await
501    }
502
503    /// Apply applies a list of mutations atomically to the database.
504    /// ```
505    /// use google_cloud_spanner::mutation::insert;
506    /// use google_cloud_spanner::mutation::delete;
507    /// use google_cloud_spanner::key::all_keys;
508    /// use google_cloud_spanner::statement::ToKind;
509    /// use google_cloud_spanner::client::{Client, Error};
510    /// use google_cloud_spanner::value::CommitTimestamp;
511    ///
512    /// async fn run(client: Client) -> Result<(), Error>{
513    ///     let m1 = delete("Guild", all_keys());
514    ///     let m2 = insert("Guild", &["GuildID", "OwnerUserID", "UpdatedAt"], &[&"1", &"2", &CommitTimestamp::new()]);
515    ///     let commit_timestamp = client.apply(vec![m1,m2]).await?;
516    ///     Ok(())
517    /// }
518    /// ```
519    pub async fn apply(&self, ms: Vec<Mutation>) -> Result<CommitResult, Error> {
520        self.apply_with_option(ms, ReadWriteTransactionOption::default()).await
521    }
522
523    /// Apply applies a list of mutations atomically to the database.
524    pub async fn apply_with_option(
525        &self,
526        ms: Vec<Mutation>,
527        options: ReadWriteTransactionOption,
528    ) -> Result<CommitResult, Error> {
529        let result: Result<(CommitResult, ()), Error> = self
530            .read_write_transaction_sync_with_option(
531                |tx| {
532                    tx.buffer_write(ms.to_vec());
533                    Ok(())
534                },
535                options,
536            )
537            .await;
538        Ok(result?.0)
539    }
540
541    /// ReadWriteTransaction executes a read-write transaction, with retries as
542    /// necessary.
543    ///
544    /// The function f will be called one or more times. It must not maintain
545    /// any state between calls.
546    ///
547    /// If the transaction cannot be committed or if f returns an ABORTED error,
548    /// ReadWriteTransaction will call f again. It will continue to call f until the
549    /// transaction can be committed or the Context times out or is cancelled.  If f
550    /// returns an error other than ABORTED, ReadWriteTransaction will abort the
551    /// transaction and return the error.
552    ///
553    /// To limit the number of retries, set a deadline on the Context rather than
554    /// using a fixed limit on the number of attempts. ReadWriteTransaction will
555    /// retry as needed until that deadline is met.
556    ///
557    /// See <https://godoc.org/cloud.google.com/go/spanner#ReadWriteTransaction> for
558    /// more details.
559    /// ```
560    /// use google_cloud_spanner::mutation::update;
561    /// use google_cloud_spanner::key::{Key, all_keys};
562    /// use google_cloud_spanner::value::Timestamp;
563    /// use google_cloud_spanner::client::Error;
564    /// use google_cloud_spanner::client::Client;
565    ///
566    /// #[tokio::main]
567    /// async fn run(client: Client) ->  Result<(Option<Timestamp>,()), Error>{
568    ///     client.read_write_transaction(|tx| {
569    ///         Box::pin(async move {
570    ///             // The transaction function will be called again if the error code
571    ///             // of this error is Aborted. The backend may automatically abort
572    ///             // any read/write transaction if it detects a deadlock or other problems.
573    ///             let key = all_keys();
574    ///             let mut reader = tx.read("UserItem", &["UserId", "ItemId", "Quantity"], key).await?;
575    ///             let mut ms = vec![];
576    ///             while let Some(row) = reader.next().await? {
577    ///                 let user_id = row.column_by_name::<String>("UserId")?;
578    ///                 let item_id = row.column_by_name::<i64>("ItemId")?;
579    ///                 let quantity = row.column_by_name::<i64>("Quantity")? + 1;
580    ///                 let m = update("UserItem", &["Quantity"], &[&user_id, &item_id, &quantity]);
581    ///                 ms.push(m);
582    ///             }
583    ///             // The buffered mutation will be committed.  If the commit
584    ///             // fails with an Aborted error, this function will be called again
585    ///             tx.buffer_write(ms);
586    ///             Ok(())
587    ///         })
588    ///     }).await
589    /// }
590    pub async fn read_write_transaction<'a, T, E, F>(&self, f: F) -> Result<(CommitResult, T), E>
591    where
592        E: TryAs<Status> + From<SessionError> + From<Status>,
593        F: for<'tx> Fn(&'tx mut ReadWriteTransaction) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'tx>>,
594    {
595        self.read_write_transaction_with_option(f, ReadWriteTransactionOption::default())
596            .await
597    }
598
599    /// ReadWriteTransaction executes a read-write transaction, with retries as
600    /// necessary.
601    ///
602    /// The function f will be called one or more times. It must not maintain
603    /// any state between calls.
604    ///
605    /// If the transaction cannot be committed or if f returns an ABORTED error,
606    /// ReadWriteTransaction will call f again. It will continue to call f until the
607    /// transaction can be committed or the Context times out or is cancelled.  If f
608    /// returns an error other than ABORTED, ReadWriteTransaction will abort the
609    /// transaction and return the error.
610    ///
611    /// To limit the number of retries, set a deadline on the Context rather than
612    /// using a fixed limit on the number of attempts. ReadWriteTransaction will
613    /// retry as needed until that deadline is met.
614    ///
615    /// See <https://godoc.org/cloud.google.com/go/spanner#ReadWriteTransaction> for
616    /// more details.
617    pub async fn read_write_transaction_with_option<'a, T, E, F>(
618        &'a self,
619        f: F,
620        options: ReadWriteTransactionOption,
621    ) -> Result<(CommitResult, T), E>
622    where
623        E: TryAs<Status> + From<SessionError> + From<Status>,
624        F: for<'tx> Fn(&'tx mut ReadWriteTransaction) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'tx>>,
625    {
626        let (bo, co, tag) = Client::split_read_write_transaction_option(options);
627
628        let ro = TransactionRetrySetting::default();
629        let session = Some(self.get_session().await?);
630        // must reuse session
631        invoke_fn(
632            Some(ro),
633            |session| async {
634                let mut tx = self
635                    .create_read_write_transaction::<E>(session, bo.clone(), tag.clone())
636                    .await?;
637                let result = f(&mut tx).await;
638                tx.finish(result, Some(co.clone())).await
639            },
640            session,
641        )
642        .await
643    }
644
645    /// begin_read_write_transaction creates new ReadWriteTransaction.
646    /// ```
647    /// use google_cloud_spanner::mutation::update;
648    /// use google_cloud_spanner::key::{Key, all_keys};
649    /// use google_cloud_spanner::value::Timestamp;
650    /// use google_cloud_spanner::client::Error;
651    /// use google_cloud_spanner::client::Client;
652    /// use google_cloud_spanner::transaction_rw::ReadWriteTransaction;
653    /// use google_cloud_googleapis::spanner::v1::execute_batch_dml_request::Statement;
654    /// use google_cloud_spanner::retry::TransactionRetry;
655    ///
656    /// async fn run(client: Client) -> Result<(), Error>{
657    ///     let retry = &mut TransactionRetry::new();
658    ///     loop {
659    ///         let tx = &mut client.begin_read_write_transaction().await?;
660    ///
661    ///         let result = run_in_transaction(tx).await;
662    ///
663    ///         // try to commit or rollback transaction.
664    ///         match tx.end(result, None).await {
665    ///             Ok((_commit_timestamp, success)) => return Ok(success),
666    ///             Err(err) => retry.next(err).await? // check retry
667    ///         }
668    ///     }
669    /// }
670    ///
671    /// async fn run_in_transaction(tx: &mut ReadWriteTransaction) -> Result<(), Error> {
672    ///     let key = all_keys();
673    ///     let mut reader = tx.read("UserItem", &["UserId", "ItemId", "Quantity"], key).await?;
674    ///     let mut ms = vec![];
675    ///     while let Some(row) = reader.next().await? {
676    ///         let user_id = row.column_by_name::<String>("UserId")?;
677    ///         let item_id = row.column_by_name::<i64>("ItemId")?;
678    ///         let quantity = row.column_by_name::<i64>("Quantity")? + 1;
679    ///         let m = update("UserItem", &["UserId", "ItemId", "Quantity"], &[&user_id, &item_id, &quantity]);
680    ///         ms.push(m);
681    ///     }
682    ///     tx.buffer_write(ms);
683    ///     Ok(())
684    /// }
685    /// ```
686    pub async fn begin_read_write_transaction(&self) -> Result<ReadWriteTransaction, Error> {
687        let session = self.get_session().await?;
688        ReadWriteTransaction::begin(
689            session,
690            ReadWriteTransactionOption::default().begin_options,
691            ReadWriteTransactionOption::default().transaction_tag,
692            self.disable_route_to_leader,
693        )
694        .await
695        .map_err(|e| e.status.into())
696    }
697
698    /// Get open session count.
699    pub fn session_count(&self) -> usize {
700        self.sessions.num_opened()
701    }
702
703    async fn read_write_transaction_sync_with_option<T, E>(
704        &self,
705        f: impl Fn(&mut ReadWriteTransaction) -> Result<T, E>,
706        options: ReadWriteTransactionOption,
707    ) -> Result<(CommitResult, T), E>
708    where
709        E: TryAs<Status> + From<SessionError> + From<Status>,
710    {
711        let (bo, co, tag) = Client::split_read_write_transaction_option(options);
712
713        let ro = TransactionRetrySetting::default();
714        let session = Some(self.get_session().await?);
715
716        // reuse session
717        invoke_fn(
718            Some(ro),
719            |session| async {
720                let mut tx = self
721                    .create_read_write_transaction::<E>(session, bo.clone(), tag.clone())
722                    .await?;
723                let result = f(&mut tx);
724                tx.finish(result, Some(co.clone())).await
725            },
726            session,
727        )
728        .await
729    }
730
731    async fn create_read_write_transaction<E>(
732        &self,
733        session: Option<ManagedSession>,
734        bo: CallOptions,
735        transaction_tag: Option<String>,
736    ) -> Result<ReadWriteTransaction, (E, Option<ManagedSession>)>
737    where
738        E: TryAs<Status> + From<SessionError> + From<Status>,
739    {
740        ReadWriteTransaction::begin(session.unwrap(), bo, transaction_tag, self.disable_route_to_leader)
741            .await
742            .map_err(|e| (E::from(e.status), Some(e.session)))
743    }
744
745    async fn get_session(&self) -> Result<ManagedSession, SessionError> {
746        self.sessions.get().await
747    }
748
749    fn split_read_write_transaction_option(
750        options: ReadWriteTransactionOption,
751    ) -> (CallOptions, CommitOptions, Option<String>) {
752        (options.begin_options, options.commit_options, options.transaction_tag)
753    }
754}