Skip to main content

gcloud_spanner/apiv1/
spanner_client.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use google_cloud_gax::conn::Channel;
5use google_cloud_gax::grpc::metadata::{KeyAndValueRef, MetadataMap};
6use google_cloud_gax::grpc::{Code, Response, Status, Streaming};
7use google_cloud_gax::retry::{invoke_fn, RetrySetting};
8use google_cloud_gax::{create_request, grpc};
9use google_cloud_googleapis::spanner::v1::spanner_client::SpannerClient;
10use google_cloud_googleapis::spanner::v1::{
11    BatchCreateSessionsRequest, BatchCreateSessionsResponse, BeginTransactionRequest, CommitRequest, CommitResponse,
12    CreateSessionRequest, DeleteSessionRequest, ExecuteBatchDmlRequest, ExecuteBatchDmlResponse, ExecuteSqlRequest,
13    GetSessionRequest, ListSessionsRequest, ListSessionsResponse, PartialResultSet, PartitionQueryRequest,
14    PartitionReadRequest, PartitionResponse, ReadRequest, ResultSet, RollbackRequest, Session, Transaction,
15};
16
17use crate::metrics::MetricsRecorder;
18
19const ROUTE_TO_LEADER_HEADER: &str = "x-goog-spanner-route-to-leader";
20
21pub(crate) fn ping_query_request(session_name: impl Into<String>) -> ExecuteSqlRequest {
22    ExecuteSqlRequest {
23        session: session_name.into(),
24        transaction: None,
25        sql: "SELECT 1".to_string(),
26        params: None,
27        param_types: Default::default(),
28        resume_token: vec![],
29        query_mode: 0,
30        partition_token: vec![],
31        seqno: 0,
32        query_options: None,
33        request_options: None,
34        directed_read_options: None,
35        data_boost_enabled: false,
36        last_statement: false,
37    }
38}
39
40fn default_setting() -> RetrySetting {
41    RetrySetting {
42        from_millis: 50,
43        max_delay: Some(Duration::from_secs(10)),
44        factor: 1u64,
45        take: 20,
46        codes: vec![Code::Unavailable, Code::Unknown],
47    }
48}
49
50#[derive(Clone)]
51pub struct Client {
52    inner: SpannerClient<Channel>,
53    enable_gzip: bool,
54    metadata: MetadataMap,
55    metrics: Arc<MetricsRecorder>,
56}
57
58impl Client {
59    /// create new spanner client
60    pub fn new(inner: SpannerClient<Channel>) -> Client {
61        // https://github.com/googleapis/google-cloud-go/blob/65a9ba55ed3777f520bd881d891e8917323549a5/spanner/apiv1/spanner_client.go#L73
62        Client {
63            inner: inner.max_decoding_message_size(i32::MAX as usize),
64            enable_gzip: false,
65            metadata: Default::default(),
66            metrics: Arc::new(MetricsRecorder::default()),
67        }
68    }
69
70    /// set metadata for spanner client
71    pub(crate) fn with_metadata(self, metadata: MetadataMap) -> Client {
72        Client {
73            inner: self.inner,
74            enable_gzip: self.enable_gzip,
75            metadata,
76            metrics: self.metrics,
77        }
78    }
79
80    pub(crate) fn with_gzip(mut self, enabled: bool) -> Self {
81        self.enable_gzip = enabled;
82        if enabled {
83            self.inner = self
84                .inner
85                .send_compressed(grpc::codec::CompressionEncoding::Gzip)
86                .accept_compressed(grpc::codec::CompressionEncoding::Gzip);
87        }
88        self
89    }
90
91    pub(crate) fn with_metrics(mut self, metrics: Arc<MetricsRecorder>) -> Client {
92        self.metrics = metrics;
93        self
94    }
95
96    /// create_session creates a new session. A session can be used to perform
97    /// transactions that read and/or modify data in a Cloud Spanner database.
98    /// Sessions are meant to be reused for many consecutive
99    /// transactions.
100    ///
101    /// Sessions can only execute one transaction at a time. To execute
102    /// multiple concurrent read-write/write-only transactions, create
103    /// multiple sessions. Note that standalone reads and queries use a
104    /// transaction internally, and count toward the one transaction
105    /// limit.
106    ///
107    /// Active sessions use additional server resources, so it is a good idea to
108    /// delete idle and unneeded sessions.
109    /// Aside from explicit deletes, Cloud Spanner may delete sessions for which no
110    /// operations are sent for more than an hour. If a session is deleted,
111    /// requests to it return NOT_FOUND.
112    ///
113    /// Idle sessions can be kept alive by sending a trivial SQL query
114    /// periodically, e.g., "SELECT 1".
115    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
116    pub async fn create_session(
117        &mut self,
118        req: CreateSessionRequest,
119        disable_route_to_leader: bool,
120        retry: Option<RetrySetting>,
121    ) -> Result<Response<Session>, Status> {
122        let setting = retry.unwrap_or_else(default_setting);
123        let database = &req.database;
124        let metrics = Arc::clone(&self.metrics);
125        invoke_fn(
126            Some(setting),
127            |this| async {
128                let request = this.create_request(disable_route_to_leader, format!("database={database}"), req.clone());
129                this.inner.create_session(request).await.map_err(|e| (e, this))
130            },
131            self,
132        )
133        .await
134        .inspect(move |response| {
135            Self::record_gfe(metrics.as_ref(), "createSession", response);
136        })
137    }
138
139    /// batch_create_sessions creates multiple new sessions.
140    ///
141    /// This API can be used to initialize a session cache on the clients.
142    /// See https:///goo.gl/TgSFN2 (at https:///goo.gl/TgSFN2) for best practices on session cache management.
143    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
144    pub async fn batch_create_sessions(
145        &mut self,
146        req: BatchCreateSessionsRequest,
147        disable_route_to_leader: bool,
148        retry: Option<RetrySetting>,
149    ) -> Result<Response<BatchCreateSessionsResponse>, Status> {
150        let setting = retry.unwrap_or_else(default_setting);
151        let database = &req.database;
152        let metrics = Arc::clone(&self.metrics);
153        invoke_fn(
154            Some(setting),
155            |this| async {
156                let request = this.create_request(disable_route_to_leader, format!("database={database}"), req.clone());
157                this.inner.batch_create_sessions(request).await.map_err(|e| (e, this))
158            },
159            self,
160        )
161        .await
162        .inspect(move |response| {
163            Self::record_gfe(metrics.as_ref(), "batchCreateSessions", response);
164        })
165    }
166
167    /// get_session gets a session. Returns NOT_FOUND if the session does not exist.
168    /// This is mainly useful for determining whether a session is still alive.
169    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
170    pub async fn get_session(
171        &mut self,
172        req: GetSessionRequest,
173        disable_route_to_leader: bool,
174        retry: Option<RetrySetting>,
175    ) -> Result<Response<Session>, Status> {
176        let setting = retry.unwrap_or_else(default_setting);
177        let name = &req.name;
178        let metrics = Arc::clone(&self.metrics);
179        invoke_fn(
180            Some(setting),
181            |this| async {
182                let request = this.create_request(disable_route_to_leader, format!("name={name}"), req.clone());
183                this.inner.get_session(request).await.map_err(|e| (e, this))
184            },
185            self,
186        )
187        .await
188        .inspect(move |response| {
189            Self::record_gfe(metrics.as_ref(), "getSession", response);
190        })
191    }
192
193    /// list_sessions lists all sessions in a given database.
194    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
195    pub async fn list_sessions(
196        &mut self,
197        req: ListSessionsRequest,
198        disable_route_to_leader: bool,
199        retry: Option<RetrySetting>,
200    ) -> Result<Response<ListSessionsResponse>, Status> {
201        let setting = retry.unwrap_or_else(default_setting);
202        let database = &req.database;
203        let metrics = Arc::clone(&self.metrics);
204        invoke_fn(
205            Some(setting),
206            |this| async {
207                let request = this.create_request(disable_route_to_leader, format!("database={database}"), req.clone());
208                this.inner.list_sessions(request).await.map_err(|e| (e, this))
209            },
210            self,
211        )
212        .await
213        .inspect(move |response| {
214            Self::record_gfe(metrics.as_ref(), "listSessions", response);
215        })
216    }
217
218    /// delete_session ends a session, releasing server resources associated with it. This will
219    /// asynchronously trigger cancellation of any operations that are running with
220    /// this session.
221    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
222    pub async fn delete_session(
223        &mut self,
224        req: DeleteSessionRequest,
225        disable_route_to_leader: bool,
226        retry: Option<RetrySetting>,
227    ) -> Result<Response<()>, Status> {
228        let setting = retry.unwrap_or_else(default_setting);
229        let name = &req.name;
230        let metrics = Arc::clone(&self.metrics);
231        invoke_fn(
232            Some(setting),
233            |this| async {
234                let request = this.create_request(disable_route_to_leader, format!("name={name}"), req.clone());
235                this.inner.delete_session(request).await.map_err(|e| (e, this))
236            },
237            self,
238        )
239        .await
240        .inspect(move |response| {
241            Self::record_gfe(metrics.as_ref(), "deleteSession", response);
242        })
243    }
244
245    /// execute_sql executes an SQL statement, returning all results in a single reply. This
246    /// method cannot be used to return a result set larger than 10 MiB;
247    /// if the query yields more data than that, the query fails with
248    /// a FAILED_PRECONDITION error.
249    ///
250    /// Operations inside read-write transactions might return ABORTED. If
251    /// this occurs, the application should restart the transaction from
252    /// the beginning. See Transaction for more details.
253    ///
254    /// Larger result sets can be fetched in streaming fashion by calling
255    /// ExecuteStreamingSql instead.
256    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
257    pub async fn execute_sql(
258        &mut self,
259        req: ExecuteSqlRequest,
260        disable_route_to_leader: bool,
261        retry: Option<RetrySetting>,
262    ) -> Result<Response<ResultSet>, Status> {
263        let setting = retry.unwrap_or_else(default_setting);
264        let session = &req.session;
265        let metrics = Arc::clone(&self.metrics);
266        invoke_fn(
267            Some(setting),
268            |this| async {
269                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
270                this.inner.execute_sql(request).await.map_err(|e| (e, this))
271            },
272            self,
273        )
274        .await
275        .inspect(move |response| {
276            Self::record_gfe(metrics.as_ref(), "executeSql", response);
277        })
278    }
279
280    /// execute_streaming_sql like ExecuteSql, except returns the result
281    /// set as a stream. Unlike ExecuteSql, there
282    /// is no limit on the size of the returned result set. However, no
283    /// individual row in the result set can exceed 100 MiB, and no
284    /// column value can exceed 10 MiB.
285    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
286    pub async fn execute_streaming_sql(
287        &mut self,
288        req: ExecuteSqlRequest,
289        disable_route_to_leader: bool,
290        retry: Option<RetrySetting>,
291    ) -> Result<Response<Streaming<PartialResultSet>>, Status> {
292        let setting = retry.unwrap_or_else(default_setting);
293        let session = &req.session;
294        let metrics = Arc::clone(&self.metrics);
295        invoke_fn(
296            Some(setting),
297            |this| async {
298                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
299                this.inner.execute_streaming_sql(request).await.map_err(|e| (e, this))
300            },
301            self,
302        )
303        .await
304        .inspect(move |response| {
305            Self::record_gfe(metrics.as_ref(), "executeStreamingSql", response);
306        })
307    }
308
309    /// execute_batch_dml executes a batch of SQL DML statements. This method allows many statements
310    /// to be run with lower latency than submitting them sequentially with
311    /// ExecuteSql.
312    ///
313    /// Statements are executed in sequential order. A request can succeed even if
314    /// a statement fails. The ExecuteBatchDmlResponse.status field in the
315    /// response provides information about the statement that failed. Clients must
316    /// inspect this field to determine whether an error occurred.
317    ///
318    /// Execution stops after the first failed statement; the remaining statements
319    /// are not executed.
320    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
321    pub async fn execute_batch_dml(
322        &mut self,
323        req: ExecuteBatchDmlRequest,
324        disable_route_to_leader: bool,
325        retry: Option<RetrySetting>,
326    ) -> Result<Response<ExecuteBatchDmlResponse>, Status> {
327        let setting = retry.unwrap_or_else(default_setting);
328        let session = &req.session;
329        let metrics = Arc::clone(&self.metrics);
330        invoke_fn(
331            Some(setting),
332            |this| async {
333                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
334                let result = this.inner.execute_batch_dml(request).await;
335                match result {
336                    Ok(response) => match response.get_ref().status.as_ref() {
337                        Some(s) => {
338                            let code = Code::from(s.code);
339                            if code == Code::Ok {
340                                Ok(response)
341                            } else {
342                                Err((Status::new(code, s.message.to_string()), this))
343                            }
344                        }
345                        None => Ok(response),
346                    },
347                    Err(err) => Err((err, this)),
348                }
349            },
350            self,
351        )
352        .await
353        .inspect(move |response| {
354            Self::record_gfe(metrics.as_ref(), "executeBatchDml", response);
355        })
356    }
357
358    /// read reads rows from the database using key lookups and scans, as a
359    /// simple key/value style alternative to
360    /// ExecuteSql.  This method cannot be used to
361    /// return a result set larger than 10 MiB; if the read matches more
362    /// data than that, the read fails with a FAILED_PRECONDITION
363    /// error.
364    ///
365    /// Reads inside read-write transactions might return ABORTED. If
366    /// this occurs, the application should restart the transaction from
367    /// the beginning. See Transaction for more details.
368    ///
369    /// Larger result sets can be yielded in streaming fashion by calling
370    /// StreamingRead instead.
371    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
372    pub async fn read(
373        &mut self,
374        req: ReadRequest,
375        disable_route_to_leader: bool,
376        retry: Option<RetrySetting>,
377    ) -> Result<Response<ResultSet>, Status> {
378        let setting = retry.unwrap_or_else(default_setting);
379        let session = &req.session;
380        let metrics = Arc::clone(&self.metrics);
381        invoke_fn(
382            Some(setting),
383            |this| async {
384                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
385                this.inner.read(request).await.map_err(|e| (e, this))
386            },
387            self,
388        )
389        .await
390        .inspect(move |response| {
391            Self::record_gfe(metrics.as_ref(), "read", response);
392        })
393    }
394
395    /// streaming_read like read, except returns the result set as a
396    /// stream. Unlike read, there is no limit on the
397    /// size of the returned result set. However, no individual row in
398    /// the result set can exceed 100 MiB, and no column value can exceed
399    /// 10 MiB.
400    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
401    pub async fn streaming_read(
402        &mut self,
403        req: ReadRequest,
404        disable_route_to_leader: bool,
405        retry: Option<RetrySetting>,
406    ) -> Result<Response<Streaming<PartialResultSet>>, Status> {
407        let setting = retry.unwrap_or_else(default_setting);
408        let session = &req.session;
409        let metrics = Arc::clone(&self.metrics);
410        invoke_fn(
411            Some(setting),
412            |this| async {
413                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
414                this.inner.streaming_read(request).await.map_err(|e| (e, this))
415            },
416            self,
417        )
418        .await
419        .inspect(move |response| {
420            Self::record_gfe(metrics.as_ref(), "streamingRead", response);
421        })
422    }
423
424    /// BeginTransaction begins a new transaction. This step can often be skipped:
425    /// Read, ExecuteSql and
426    /// Commit can begin a new transaction as a
427    /// side-effect.
428    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
429    pub async fn begin_transaction(
430        &mut self,
431        req: BeginTransactionRequest,
432        disable_route_to_leader: bool,
433        retry: Option<RetrySetting>,
434    ) -> Result<Response<Transaction>, Status> {
435        let setting = retry.unwrap_or_else(default_setting);
436        let session = &req.session;
437        let metrics = Arc::clone(&self.metrics);
438        invoke_fn(
439            Some(setting),
440            |this| async {
441                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
442                this.inner.begin_transaction(request).await.map_err(|e| (e, this))
443            },
444            self,
445        )
446        .await
447        .inspect(move |response| {
448            Self::record_gfe(metrics.as_ref(), "beginTransaction", response);
449        })
450    }
451
452    /// Commit commits a transaction. The request includes the mutations to be
453    /// applied to rows in the database.
454    ///
455    /// Commit might return an ABORTED error. This can occur at any time;
456    /// commonly, the cause is conflicts with concurrent
457    /// transactions. However, it can also happen for a variety of other
458    /// reasons. If Commit returns ABORTED, the caller should re-attempt
459    /// the transaction from the beginning, re-using the same session.
460    ///
461    /// On very rare occasions, Commit might return UNKNOWN. This can happen,
462    /// for example, if the client job experiences a 1+ hour networking failure.
463    /// At that point, Cloud Spanner has lost track of the transaction outcome and
464    /// we recommend that you perform another read from the database to see the
465    /// state of things as they are now.
466    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
467    pub async fn commit(
468        &mut self,
469        req: CommitRequest,
470        disable_route_to_leader: bool,
471        retry: Option<RetrySetting>,
472    ) -> Result<Response<CommitResponse>, Status> {
473        let setting = retry.unwrap_or_else(default_setting);
474        let session = &req.session;
475        let metrics = Arc::clone(&self.metrics);
476        invoke_fn(
477            Some(setting),
478            |this| async {
479                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
480                this.inner.commit(request).await.map_err(|e| (e, this))
481            },
482            self,
483        )
484        .await
485        .inspect(move |response| {
486            Self::record_gfe(metrics.as_ref(), "commit", response);
487        })
488    }
489
490    /// Rollback rolls back a transaction, releasing any locks it holds. It is a good
491    /// idea to call this for any transaction that includes one or more
492    /// Read or ExecuteSql requests and
493    /// ultimately decides not to commit.
494    ///
495    /// Rollback returns OK if it successfully aborts the transaction, the
496    /// transaction was already aborted, or the transaction is not
497    /// found. Rollback never returns ABORTED.
498    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
499    pub async fn rollback(
500        &mut self,
501        req: RollbackRequest,
502        disable_route_to_leader: bool,
503        retry: Option<RetrySetting>,
504    ) -> Result<Response<()>, Status> {
505        let setting = retry.unwrap_or_else(default_setting);
506        let session = &req.session;
507        let metrics = Arc::clone(&self.metrics);
508        invoke_fn(
509            Some(setting),
510            |this| async {
511                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
512                this.inner.rollback(request).await.map_err(|e| (e, this))
513            },
514            self,
515        )
516        .await
517        .inspect(move |response| {
518            Self::record_gfe(metrics.as_ref(), "rollback", response);
519        })
520    }
521
522    /// PartitionQuery creates a set of partition tokens that can be used to execute a query
523    /// operation in parallel.  Each of the returned partition tokens can be used
524    /// by ExecuteStreamingSql to specify a subset
525    /// of the query result to read.  The same session and read-only transaction
526    /// must be used by the PartitionQueryRequest used to create the
527    /// partition tokens and the ExecuteSqlRequests that use the partition tokens.
528    ///
529    /// Partition tokens become invalid when the session used to create them
530    /// is deleted, is idle for too long, begins a new transaction, or becomes too
531    /// old.  When any of these happen, it is not possible to resume the query, and
532    /// the whole operation must be restarted from the beginning.
533    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
534    pub async fn partition_query(
535        &mut self,
536        req: PartitionQueryRequest,
537        disable_route_to_leader: bool,
538        retry: Option<RetrySetting>,
539    ) -> Result<Response<PartitionResponse>, Status> {
540        let setting = retry.unwrap_or_else(default_setting);
541        let session = &req.session;
542        let metrics = Arc::clone(&self.metrics);
543        invoke_fn(
544            Some(setting),
545            |this| async {
546                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
547                this.inner.partition_query(request).await.map_err(|e| (e, this))
548            },
549            self,
550        )
551        .await
552        .inspect(move |response| {
553            Self::record_gfe(metrics.as_ref(), "partitionQuery", response);
554        })
555    }
556
557    /// PartitionRead creates a set of partition tokens that can be used to execute a read
558    /// operation in parallel.  Each of the returned partition tokens can be used
559    /// by StreamingRead to specify a subset of the read
560    /// result to read.  The same session and read-only transaction must be used by
561    /// the PartitionReadRequest used to create the partition tokens and the
562    /// ReadRequests that use the partition tokens.  There are no ordering
563    /// guarantees on rows returned among the returned partition tokens, or even
564    /// within each individual StreamingRead call issued with a partition_token.
565    ///
566    /// Partition tokens become invalid when the session used to create them
567    /// is deleted, is idle for too long, begins a new transaction, or becomes too
568    /// old.  When any of these happen, it is not possible to resume the read, and
569    /// the whole operation must be restarted from the beginning.
570    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
571    pub async fn partition_read(
572        &mut self,
573        req: PartitionReadRequest,
574        disable_route_to_leader: bool,
575        retry: Option<RetrySetting>,
576    ) -> Result<Response<PartitionResponse>, Status> {
577        let setting = retry.unwrap_or_else(default_setting);
578        let session = &req.session;
579        let metrics = Arc::clone(&self.metrics);
580        invoke_fn(
581            Some(setting),
582            |this| async {
583                let request = this.create_request(disable_route_to_leader, format!("session={session}"), req.clone());
584                this.inner.partition_read(request).await.map_err(|e| (e, this))
585            },
586            self,
587        )
588        .await
589        .inspect(move |response| {
590            Self::record_gfe(metrics.as_ref(), "partitionRead", response);
591        })
592    }
593
594    fn create_request<T>(
595        &self,
596        disable_route_to_leader: bool,
597        param_string: String,
598        into_request: impl grpc::IntoRequest<T>,
599    ) -> grpc::Request<T> {
600        let mut req = create_request(param_string, into_request);
601        let target = req.metadata_mut();
602        if self.enable_gzip {
603            // Spanner requires this header to request compressed responses.
604            target.insert("x-response-encoding", "gzip".parse().unwrap());
605        }
606        if !disable_route_to_leader {
607            target.append(ROUTE_TO_LEADER_HEADER, "true".parse().unwrap());
608        }
609        for entry in self.metadata.iter() {
610            match entry {
611                KeyAndValueRef::Ascii(k, v) => {
612                    target.append(k, v.clone());
613                }
614                KeyAndValueRef::Binary(k, v) => {
615                    target.append_bin(k, v.clone());
616                }
617            }
618        }
619        req
620    }
621
622    fn record_gfe<T>(metrics: &MetricsRecorder, method: &'static str, response: &Response<T>) {
623        metrics.record_server_timing(method, response.metadata());
624    }
625}
626
627#[cfg(test)]
628mod compression_tests {
629    use std::convert::Infallible;
630    use std::future::Future;
631    use std::io::{Read, Write};
632    use std::pin::Pin;
633    use std::task::{Context, Poll};
634
635    use bytes::Bytes;
636    use flate2::{read::GzDecoder, write::GzEncoder, Compression};
637    use http_body_util::BodyExt;
638    use prost::Message;
639    use tokio_stream::wrappers::TcpListenerStream;
640    use tonic::body::Body;
641    use tonic::server::NamedService;
642    use tower::Service;
643
644    use super::*;
645
646    #[derive(Clone)]
647    struct CompressionServer {
648        gzip: bool,
649    }
650
651    impl NamedService for CompressionServer {
652        const NAME: &'static str = "google.spanner.v1.Spanner";
653    }
654
655    impl Service<http::Request<Body>> for CompressionServer {
656        type Response = http::Response<Body>;
657        type Error = Infallible;
658        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
659
660        fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
661            Poll::Ready(Ok(()))
662        }
663
664        fn call(&mut self, req: http::Request<Body>) -> Self::Future {
665            let gzip = self.gzip;
666            Box::pin(async move {
667                let path = req.uri().path().to_string();
668                assert_eq!(
669                    req.headers().get("x-response-encoding").map(|v| v.to_str().unwrap()),
670                    gzip.then_some("gzip")
671                );
672                assert_eq!(
673                    req.headers().get("grpc-encoding").map(|v| v.to_str().unwrap()),
674                    gzip.then_some("gzip")
675                );
676                assert_eq!(
677                    req.headers()["google-cloud-resource-prefix"],
678                    "projects/test/instances/test/databases/test"
679                );
680                if gzip {
681                    assert!(req.headers()["grpc-accept-encoding"].to_str().unwrap().contains("gzip"));
682                }
683                let frame = req.into_body().collect().await.unwrap().to_bytes();
684                assert_eq!(frame[0], u8::from(gzip));
685                assert_eq!(u32::from_be_bytes(frame[1..5].try_into().unwrap()) as usize, frame.len() - 5);
686                let payload = if gzip {
687                    let mut decoded = Vec::new();
688                    GzDecoder::new(&frame[5..]).read_to_end(&mut decoded).unwrap();
689                    decoded
690                } else {
691                    frame[5..].to_vec()
692                };
693                let mut payload = match path.as_str() {
694                    "/google.spanner.v1.Spanner/GetSession" => {
695                        let request = GetSessionRequest::decode(payload.as_slice()).unwrap();
696                        Session {
697                            name: request.name,
698                            ..Default::default()
699                        }
700                        .encode_to_vec()
701                    }
702                    "/google.spanner.v1.Spanner/BatchCreateSessions" => {
703                        let request = BatchCreateSessionsRequest::decode(payload.as_slice()).unwrap();
704                        assert_eq!(request.database, "projects/test/instances/test/databases/test");
705                        assert_eq!(request.session_count, 1);
706                        BatchCreateSessionsResponse {
707                            session: vec![Session {
708                                name: format!("{}/sessions/test", request.database),
709                                ..Default::default()
710                            }],
711                        }
712                        .encode_to_vec()
713                    }
714                    "/google.spanner.v1.Spanner/DeleteSession" => {
715                        let request = DeleteSessionRequest::decode(payload.as_slice()).unwrap();
716                        assert_eq!(request.name, "projects/test/instances/test/databases/test/sessions/test");
717                        Vec::new()
718                    }
719                    _ => panic!("Unexpected RPC: {path}"),
720                };
721                if gzip {
722                    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
723                    encoder.write_all(&payload).unwrap();
724                    payload = encoder.finish().unwrap();
725                }
726                let mut frame = vec![u8::from(gzip)];
727                frame.extend_from_slice(&(payload.len() as u32).to_be_bytes());
728                frame.extend_from_slice(&payload);
729                let mut response = http::Response::builder().header("content-type", "application/grpc");
730                if gzip {
731                    response = response.header("grpc-encoding", "gzip");
732                }
733                let body = http_body_util::Full::new(Bytes::from(frame)).with_trailers(async {
734                    let mut trailers = http::HeaderMap::new();
735                    trailers.insert("grpc-status", "0".parse().unwrap());
736                    Some(Ok::<_, Infallible>(trailers))
737                });
738                Ok(response.body(Body::new(body)).unwrap())
739            })
740        }
741    }
742
743    #[tokio::test]
744    async fn gzip_round_trip_and_uncompressed_default() {
745        for gzip in [false, true] {
746            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
747            let addr = listener.local_addr().unwrap();
748            let server = tokio::spawn(
749                tonic::transport::Server::builder()
750                    .add_service(CompressionServer { gzip })
751                    .serve_with_incoming(TcpListenerStream::new(listener)),
752            );
753            let pool = crate::apiv1::conn_pool::ConnectionManager::new(
754                1,
755                &google_cloud_gax::conn::Environment::Emulator(addr.to_string()),
756                "",
757                &google_cloud_gax::conn::ConnectionOptions::default(),
758            )
759            .await
760            .unwrap()
761            .with_gzip(gzip);
762            let mut client = pool
763                .conn()
764                .with_metadata(crate::session::client_metadata("projects/test/instances/test/databases/test"));
765            let name = "projects/test/instances/test/databases/test/sessions/test";
766            let response = tokio::time::timeout(
767                Duration::from_secs(5),
768                client.get_session(GetSessionRequest { name: name.into() }, false, None),
769            )
770            .await
771            .unwrap()
772            .unwrap();
773            assert_eq!(response.into_inner().name, name);
774            server.abort();
775        }
776    }
777
778    #[tokio::test]
779    async fn public_builder_compression_and_legacy_constructor() {
780        use crate::client::{Client as SpannerClient, ClientConfig, Compression};
781
782        for mode in ["legacy", "default", "gzip", "identity"] {
783            let gzip = mode == "gzip";
784            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
785            let addr = listener.local_addr().unwrap();
786            let server = tokio::spawn(
787                tonic::transport::Server::builder()
788                    .add_service(CompressionServer { gzip })
789                    .serve_with_incoming(TcpListenerStream::new(listener)),
790            );
791            let mut config = ClientConfig {
792                environment: google_cloud_gax::conn::Environment::Emulator(addr.to_string()),
793                ..Default::default()
794            };
795            config.channel_config.num_channels = 1;
796            config.session_config.min_opened = 1;
797            config.session_config.max_opened = 1;
798            config.session_config.max_idle = 1;
799            let database = "projects/test/instances/test/databases/test";
800            tokio::time::timeout(Duration::from_secs(5), async {
801                let client = match mode {
802                    "legacy" => SpannerClient::new(database, config).await,
803                    "default" => SpannerClient::builder(database).config(config).build().await,
804                    "gzip" => {
805                        SpannerClient::builder(database)
806                            .compression(Compression::Gzip)
807                            .config(config)
808                            .build()
809                            .await
810                    }
811                    "identity" => {
812                        SpannerClient::builder(database)
813                            .config(config)
814                            .compression(Compression::Gzip)
815                            .compression(Compression::Identity)
816                            .build()
817                            .await
818                    }
819                    _ => unreachable!(),
820                }
821                .unwrap();
822                assert_eq!(client.session_count(), 1);
823                client.close().await;
824            })
825            .await
826            .unwrap();
827            server.abort();
828        }
829    }
830}