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/// Client is a client for reading and writing data to a Cloud Spanner database.
179/// A client is safe to use concurrently, except for its Close method.
180#[derive(Clone)]
181pub struct Client {
182    sessions: Arc<SessionManager>,
183    disable_route_to_leader: bool,
184}
185
186impl Client {
187    /// new creates a client to a database. A valid database name has
188    /// the form projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID.
189    pub async fn new(database: impl Into<String>, config: ClientConfig) -> Result<Self, Error> {
190        if config.session_config.max_opened > config.channel_config.num_channels * 100 {
191            return Err(Error::InvalidConfig(format!(
192                "max session size is {} because max session size is 100 per gRPC connection",
193                config.channel_config.num_channels * 100
194            )));
195        }
196
197        let database: String = database.into();
198        let metrics = Arc::new(
199            MetricsRecorder::try_new(&database, &config.metrics).map_err(|e| Error::InvalidConfig(e.to_string()))?,
200        );
201
202        let pool_size = config.channel_config.num_channels;
203        let options = ConnectionOptions {
204            timeout: Some(config.channel_config.timeout),
205            connect_timeout: Some(config.channel_config.connect_timeout),
206            http2_keep_alive_interval: config.channel_config.http2_keep_alive_interval,
207            keep_alive_timeout: config.channel_config.keep_alive_timeout,
208            keep_alive_while_idle: config.channel_config.keep_alive_while_idle,
209        };
210        let conn_pool =
211            ConnectionManager::new(pool_size, &config.environment, config.endpoint.as_str(), &options).await?;
212        let session_manager = SessionManager::new(
213            database,
214            conn_pool,
215            config.session_config,
216            config.disable_route_to_leader,
217            metrics.clone(),
218        )
219        .await?;
220
221        Ok(Client {
222            sessions: session_manager,
223            disable_route_to_leader: config.disable_route_to_leader,
224        })
225    }
226
227    /// Close closes all the sessions gracefully.
228    /// This method can be called only once.
229    ///
230    /// Dropping the last `Client` clone instead also stops the background tasks,
231    /// but server-side sessions are left to expire (about one hour idle).
232    pub async fn close(self) {
233        self.sessions.close().await;
234    }
235
236    /// single provides a read-only snapshot transaction optimized for the case
237    /// where only a single read or query is needed.  This is more efficient than
238    /// using read_only_transaction for a single read or query.
239    /// ```
240    /// use google_cloud_spanner::key::Key;
241    /// use google_cloud_spanner::statement::ToKind;
242    /// use google_cloud_spanner::client::Client;
243    ///
244    /// #[tokio::main]
245    /// async fn run(client: Client) {
246    ///     let mut tx = client.single().await.unwrap();
247    ///     let iter1 = tx.read("Guild",&["GuildID", "OwnerUserID"], vec![
248    ///         Key::new(&"pk1"),
249    ///         Key::new(&"pk2")
250    ///     ]).await.unwrap();
251    /// }
252    /// ```
253    pub async fn single(&self) -> Result<ReadOnlyTransaction, Error> {
254        self.single_with_timestamp_bound(TimestampBound::strong_read()).await
255    }
256
257    /// single provides a read-only snapshot transaction optimized for the case
258    /// where only a single read or query is needed.  This is more efficient than
259    /// using read_only_transaction for a single read or query.
260    pub async fn single_with_timestamp_bound(&self, tb: TimestampBound) -> Result<ReadOnlyTransaction, Error> {
261        let session = self.get_session().await?;
262        let result = ReadOnlyTransaction::single(session, tb).await?;
263        Ok(result)
264    }
265
266    /// read_only_transaction returns a ReadOnlyTransaction that can be used for
267    /// multiple reads from the database.
268    ///
269    /// ```ignore
270    /// use google_cloud_spanner::client::{Client, Error};
271    /// use google_cloud_spanner::statement::Statement;
272    /// use google_cloud_spanner::key::Key;
273    ///
274    /// async fn run(client: Client) -> Result<(), Error>{
275    ///     let mut tx = client.read_only_transaction().await?;
276    ///
277    ///     let mut stmt = Statement::new("SELECT * , \
278    ///             ARRAY (SELECT AS STRUCT * FROM UserItem WHERE UserId = @Param1 ) AS UserItem, \
279    ///             ARRAY (SELECT AS STRUCT * FROM UserCharacter WHERE UserId = @Param1 ) AS UserCharacter  \
280    ///             FROM User \
281    ///             WHERE UserId = @Param1");
282    ///
283    ///     stmt.add_param("Param1", user_id);
284    ///     let mut reader = tx.query(stmt).await?;
285    ///     let mut data = vec![];
286    ///     while let Some(row) = reader.next().await? {
287    ///         let user_id= row.column_by_name::<String>("UserId")?;
288    ///         let user_items= row.column_by_name::<Vec<model::UserItem>>("UserItem")?;
289    ///         let user_characters = row.column_by_name::<Vec<model::UserCharacter>>("UserCharacter")?;
290    ///         data.push(user_id);
291    ///     }
292    ///
293    ///     let mut reader2 = tx.read("User", &["UserId"], vec![
294    ///         Key::new(&"user-1"),
295    ///         Key::new(&"user-2")
296    ///     ]).await?;
297    ///
298    ///     Ok(())
299    /// }
300    pub async fn read_only_transaction(&self) -> Result<ReadOnlyTransaction, Error> {
301        self.read_only_transaction_with_option(ReadOnlyTransactionOption::default())
302            .await
303    }
304
305    /// read_only_transaction returns a ReadOnlyTransaction that can be used for
306    /// multiple reads from the database.
307    pub async fn read_only_transaction_with_option(
308        &self,
309        options: ReadOnlyTransactionOption,
310    ) -> Result<ReadOnlyTransaction, Error> {
311        let session = self.get_session().await?;
312        let result = ReadOnlyTransaction::begin(session, options.timestamp_bound, options.call_options).await?;
313        Ok(result)
314    }
315
316    /// batch_read_only_transaction returns a BatchReadOnlyTransaction that can be used
317    /// for partitioned reads or queries from a snapshot of the database. This is
318    /// useful in batch processing pipelines where one wants to divide the work of
319    /// reading from the database across multiple machines.
320    pub async fn batch_read_only_transaction(&self) -> Result<BatchReadOnlyTransaction, Error> {
321        self.batch_read_only_transaction_with_option(ReadOnlyTransactionOption::default())
322            .await
323    }
324
325    /// batch_read_only_transaction returns a BatchReadOnlyTransaction that can be used
326    /// for partitioned reads or queries from a snapshot of the database. This is
327    /// useful in batch processing pipelines where one wants to divide the work of
328    /// reading from the database across multiple machines.
329    pub async fn batch_read_only_transaction_with_option(
330        &self,
331        options: ReadOnlyTransactionOption,
332    ) -> Result<BatchReadOnlyTransaction, Error> {
333        let session = self.get_session().await?;
334        let result = BatchReadOnlyTransaction::begin(session, options.timestamp_bound, options.call_options).await?;
335        Ok(result)
336    }
337
338    /// partitioned_update executes a DML statement in parallel across the database,
339    /// using separate, internal transactions that commit independently. The DML
340    /// statement must be fully partitionable: it must be expressible as the union
341    /// of many statements each of which accesses only a single row of the table. The
342    /// statement should also be idempotent, because it may be applied more than once.
343    ///
344    /// PartitionedUpdate returns an estimated count of the number of rows affected.
345    /// The actual number of affected rows may be greater than the estimate.
346    pub async fn partitioned_update(&self, stmt: Statement) -> Result<i64, Error> {
347        self.partitioned_update_with_option(stmt, PartitionedUpdateOption::default())
348            .await
349    }
350
351    /// partitioned_update executes a DML statement in parallel across the database,
352    /// using separate, internal transactions that commit independently. The DML
353    /// statement must be fully partitionable: it must be expressible as the union
354    /// of many statements each of which accesses only a single row of the table. The
355    /// statement should also be idempotent, because it may be applied more than once.
356    ///
357    /// PartitionedUpdate returns an estimated count of the number of rows affected.
358    /// The actual number of affected rows may be greater than the estimate.
359    pub async fn partitioned_update_with_option(
360        &self,
361        stmt: Statement,
362        options: PartitionedUpdateOption,
363    ) -> Result<i64, Error> {
364        let ro = TransactionRetrySetting::new(vec![Code::Aborted, Code::Internal]);
365        let session = Some(self.get_session().await?);
366
367        // reuse session
368        invoke_fn(
369            Some(ro),
370            |session| async {
371                let mut tx = match ReadWriteTransaction::begin_partitioned_dml(
372                    session.unwrap(),
373                    options.begin_options.clone(),
374                    options.transaction_tag.clone(),
375                    self.disable_route_to_leader,
376                )
377                .await
378                {
379                    Ok(tx) => tx,
380                    Err(e) => return Err((Error::GRPC(e.status), Some(e.session))),
381                };
382                tx.update_with_option(stmt.clone(), options.query_options.clone().unwrap_or_default())
383                    .await
384                    .map_err(|e| (Error::GRPC(e), tx.take_session()))
385            },
386            session,
387        )
388        .await
389    }
390
391    /// apply_at_least_once may attempt to apply mutations more than once; if
392    /// the mutations are not idempotent, this may lead to a failure being reported
393    /// when the mutation was applied more than once. For example, an insert may
394    /// fail with ALREADY_EXISTS even though the row did not exist before Apply was
395    /// called. For this reason, most users of the library will prefer not to use
396    /// this option.  However, apply_at_least_once requires only a single RPC, whereas
397    /// apply's default replay protection may require an additional RPC.  So this
398    /// method may be appropriate for latency sensitive and/or high throughput blind
399    /// writing.
400    pub async fn apply_at_least_once(&self, ms: Vec<Mutation>) -> Result<Option<CommitResult>, Error> {
401        self.apply_at_least_once_with_option(ms, CommitOptions::default()).await
402    }
403
404    /// apply_at_least_once may attempt to apply mutations more than once; if
405    /// the mutations are not idempotent, this may lead to a failure being reported
406    /// when the mutation was applied more than once. For example, an insert may
407    /// fail with ALREADY_EXISTS even though the row did not exist before Apply was
408    /// called. For this reason, most users of the library will prefer not to use
409    /// this option.  However, apply_at_least_once requires only a single RPC, whereas
410    /// apply's default replay protection may require an additional RPC.  So this
411    /// method may be appropriate for latency sensitive and/or high throughput blind
412    /// writing.
413    pub async fn apply_at_least_once_with_option(
414        &self,
415        ms: Vec<Mutation>,
416        options: CommitOptions,
417    ) -> Result<Option<CommitResult>, Error> {
418        let ro = TransactionRetrySetting::default();
419        let mut session = self.get_session().await?;
420
421        invoke_fn(
422            Some(ro),
423            |session| async {
424                let tx = commit_request::Transaction::SingleUseTransaction(TransactionOptions {
425                    exclude_txn_from_change_streams: false,
426                    mode: Some(transaction_options::Mode::ReadWrite(transaction_options::ReadWrite::default())),
427                    isolation_level: IsolationLevel::Unspecified as i32,
428                });
429                match commit(session, ms.clone(), tx, options.clone(), self.disable_route_to_leader).await {
430                    Ok(s) => Ok(Some(s.into())),
431                    Err(e) => Err((Error::GRPC(e), session)),
432                }
433            },
434            &mut session,
435        )
436        .await
437    }
438
439    /// Apply applies a list of mutations atomically to the database.
440    /// ```
441    /// use google_cloud_spanner::mutation::insert;
442    /// use google_cloud_spanner::mutation::delete;
443    /// use google_cloud_spanner::key::all_keys;
444    /// use google_cloud_spanner::statement::ToKind;
445    /// use google_cloud_spanner::client::{Client, Error};
446    /// use google_cloud_spanner::value::CommitTimestamp;
447    ///
448    /// async fn run(client: Client) -> Result<(), Error>{
449    ///     let m1 = delete("Guild", all_keys());
450    ///     let m2 = insert("Guild", &["GuildID", "OwnerUserID", "UpdatedAt"], &[&"1", &"2", &CommitTimestamp::new()]);
451    ///     let commit_timestamp = client.apply(vec![m1,m2]).await?;
452    ///     Ok(())
453    /// }
454    /// ```
455    pub async fn apply(&self, ms: Vec<Mutation>) -> Result<CommitResult, Error> {
456        self.apply_with_option(ms, ReadWriteTransactionOption::default()).await
457    }
458
459    /// Apply applies a list of mutations atomically to the database.
460    pub async fn apply_with_option(
461        &self,
462        ms: Vec<Mutation>,
463        options: ReadWriteTransactionOption,
464    ) -> Result<CommitResult, Error> {
465        let result: Result<(CommitResult, ()), Error> = self
466            .read_write_transaction_sync_with_option(
467                |tx| {
468                    tx.buffer_write(ms.to_vec());
469                    Ok(())
470                },
471                options,
472            )
473            .await;
474        Ok(result?.0)
475    }
476
477    /// ReadWriteTransaction executes a read-write transaction, with retries as
478    /// necessary.
479    ///
480    /// The function f will be called one or more times. It must not maintain
481    /// any state between calls.
482    ///
483    /// If the transaction cannot be committed or if f returns an ABORTED error,
484    /// ReadWriteTransaction will call f again. It will continue to call f until the
485    /// transaction can be committed or the Context times out or is cancelled.  If f
486    /// returns an error other than ABORTED, ReadWriteTransaction will abort the
487    /// transaction and return the error.
488    ///
489    /// To limit the number of retries, set a deadline on the Context rather than
490    /// using a fixed limit on the number of attempts. ReadWriteTransaction will
491    /// retry as needed until that deadline is met.
492    ///
493    /// See <https://godoc.org/cloud.google.com/go/spanner#ReadWriteTransaction> for
494    /// more details.
495    /// ```
496    /// use google_cloud_spanner::mutation::update;
497    /// use google_cloud_spanner::key::{Key, all_keys};
498    /// use google_cloud_spanner::value::Timestamp;
499    /// use google_cloud_spanner::client::Error;
500    /// use google_cloud_spanner::client::Client;
501    ///
502    /// #[tokio::main]
503    /// async fn run(client: Client) ->  Result<(Option<Timestamp>,()), Error>{
504    ///     client.read_write_transaction(|tx| {
505    ///         Box::pin(async move {
506    ///             // The transaction function will be called again if the error code
507    ///             // of this error is Aborted. The backend may automatically abort
508    ///             // any read/write transaction if it detects a deadlock or other problems.
509    ///             let key = all_keys();
510    ///             let mut reader = tx.read("UserItem", &["UserId", "ItemId", "Quantity"], key).await?;
511    ///             let mut ms = vec![];
512    ///             while let Some(row) = reader.next().await? {
513    ///                 let user_id = row.column_by_name::<String>("UserId")?;
514    ///                 let item_id = row.column_by_name::<i64>("ItemId")?;
515    ///                 let quantity = row.column_by_name::<i64>("Quantity")? + 1;
516    ///                 let m = update("UserItem", &["Quantity"], &[&user_id, &item_id, &quantity]);
517    ///                 ms.push(m);
518    ///             }
519    ///             // The buffered mutation will be committed.  If the commit
520    ///             // fails with an Aborted error, this function will be called again
521    ///             tx.buffer_write(ms);
522    ///             Ok(())
523    ///         })
524    ///     }).await
525    /// }
526    pub async fn read_write_transaction<'a, T, E, F>(&self, f: F) -> Result<(CommitResult, T), E>
527    where
528        E: TryAs<Status> + From<SessionError> + From<Status>,
529        F: for<'tx> Fn(&'tx mut ReadWriteTransaction) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'tx>>,
530    {
531        self.read_write_transaction_with_option(f, ReadWriteTransactionOption::default())
532            .await
533    }
534
535    /// ReadWriteTransaction executes a read-write transaction, with retries as
536    /// necessary.
537    ///
538    /// The function f will be called one or more times. It must not maintain
539    /// any state between calls.
540    ///
541    /// If the transaction cannot be committed or if f returns an ABORTED error,
542    /// ReadWriteTransaction will call f again. It will continue to call f until the
543    /// transaction can be committed or the Context times out or is cancelled.  If f
544    /// returns an error other than ABORTED, ReadWriteTransaction will abort the
545    /// transaction and return the error.
546    ///
547    /// To limit the number of retries, set a deadline on the Context rather than
548    /// using a fixed limit on the number of attempts. ReadWriteTransaction will
549    /// retry as needed until that deadline is met.
550    ///
551    /// See <https://godoc.org/cloud.google.com/go/spanner#ReadWriteTransaction> for
552    /// more details.
553    pub async fn read_write_transaction_with_option<'a, T, E, F>(
554        &'a self,
555        f: F,
556        options: ReadWriteTransactionOption,
557    ) -> Result<(CommitResult, T), E>
558    where
559        E: TryAs<Status> + From<SessionError> + From<Status>,
560        F: for<'tx> Fn(&'tx mut ReadWriteTransaction) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'tx>>,
561    {
562        let (bo, co, tag) = Client::split_read_write_transaction_option(options);
563
564        let ro = TransactionRetrySetting::default();
565        let session = Some(self.get_session().await?);
566        // must reuse session
567        invoke_fn(
568            Some(ro),
569            |session| async {
570                let mut tx = self
571                    .create_read_write_transaction::<E>(session, bo.clone(), tag.clone())
572                    .await?;
573                let result = f(&mut tx).await;
574                tx.finish(result, Some(co.clone())).await
575            },
576            session,
577        )
578        .await
579    }
580
581    /// begin_read_write_transaction creates new ReadWriteTransaction.
582    /// ```
583    /// use google_cloud_spanner::mutation::update;
584    /// use google_cloud_spanner::key::{Key, all_keys};
585    /// use google_cloud_spanner::value::Timestamp;
586    /// use google_cloud_spanner::client::Error;
587    /// use google_cloud_spanner::client::Client;
588    /// use google_cloud_spanner::transaction_rw::ReadWriteTransaction;
589    /// use google_cloud_googleapis::spanner::v1::execute_batch_dml_request::Statement;
590    /// use google_cloud_spanner::retry::TransactionRetry;
591    ///
592    /// async fn run(client: Client) -> Result<(), Error>{
593    ///     let retry = &mut TransactionRetry::new();
594    ///     loop {
595    ///         let tx = &mut client.begin_read_write_transaction().await?;
596    ///
597    ///         let result = run_in_transaction(tx).await;
598    ///
599    ///         // try to commit or rollback transaction.
600    ///         match tx.end(result, None).await {
601    ///             Ok((_commit_timestamp, success)) => return Ok(success),
602    ///             Err(err) => retry.next(err).await? // check retry
603    ///         }
604    ///     }
605    /// }
606    ///
607    /// async fn run_in_transaction(tx: &mut ReadWriteTransaction) -> Result<(), Error> {
608    ///     let key = all_keys();
609    ///     let mut reader = tx.read("UserItem", &["UserId", "ItemId", "Quantity"], key).await?;
610    ///     let mut ms = vec![];
611    ///     while let Some(row) = reader.next().await? {
612    ///         let user_id = row.column_by_name::<String>("UserId")?;
613    ///         let item_id = row.column_by_name::<i64>("ItemId")?;
614    ///         let quantity = row.column_by_name::<i64>("Quantity")? + 1;
615    ///         let m = update("UserItem", &["UserId", "ItemId", "Quantity"], &[&user_id, &item_id, &quantity]);
616    ///         ms.push(m);
617    ///     }
618    ///     tx.buffer_write(ms);
619    ///     Ok(())
620    /// }
621    /// ```
622    pub async fn begin_read_write_transaction(&self) -> Result<ReadWriteTransaction, Error> {
623        let session = self.get_session().await?;
624        ReadWriteTransaction::begin(
625            session,
626            ReadWriteTransactionOption::default().begin_options,
627            ReadWriteTransactionOption::default().transaction_tag,
628            self.disable_route_to_leader,
629        )
630        .await
631        .map_err(|e| e.status.into())
632    }
633
634    /// Get open session count.
635    pub fn session_count(&self) -> usize {
636        self.sessions.num_opened()
637    }
638
639    async fn read_write_transaction_sync_with_option<T, E>(
640        &self,
641        f: impl Fn(&mut ReadWriteTransaction) -> Result<T, E>,
642        options: ReadWriteTransactionOption,
643    ) -> Result<(CommitResult, T), E>
644    where
645        E: TryAs<Status> + From<SessionError> + From<Status>,
646    {
647        let (bo, co, tag) = Client::split_read_write_transaction_option(options);
648
649        let ro = TransactionRetrySetting::default();
650        let session = Some(self.get_session().await?);
651
652        // reuse session
653        invoke_fn(
654            Some(ro),
655            |session| async {
656                let mut tx = self
657                    .create_read_write_transaction::<E>(session, bo.clone(), tag.clone())
658                    .await?;
659                let result = f(&mut tx);
660                tx.finish(result, Some(co.clone())).await
661            },
662            session,
663        )
664        .await
665    }
666
667    async fn create_read_write_transaction<E>(
668        &self,
669        session: Option<ManagedSession>,
670        bo: CallOptions,
671        transaction_tag: Option<String>,
672    ) -> Result<ReadWriteTransaction, (E, Option<ManagedSession>)>
673    where
674        E: TryAs<Status> + From<SessionError> + From<Status>,
675    {
676        ReadWriteTransaction::begin(session.unwrap(), bo, transaction_tag, self.disable_route_to_leader)
677            .await
678            .map_err(|e| (E::from(e.status), Some(e.session)))
679    }
680
681    async fn get_session(&self) -> Result<ManagedSession, SessionError> {
682        self.sessions.get().await
683    }
684
685    fn split_read_write_transaction_option(
686        options: ReadWriteTransactionOption,
687    ) -> (CallOptions, CommitOptions, Option<String>) {
688        (options.begin_options, options.commit_options, options.transaction_tag)
689    }
690}