Skip to main content

gcloud_spanner/
session.rs

1use std::collections::VecDeque;
2use std::mem;
3use std::ops::{Deref, DerefMut};
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use parking_lot::{Mutex, RwLock};
8use thiserror;
9use tokio::select;
10use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
11use tokio::sync::{mpsc, oneshot};
12use tokio::task::{JoinHandle, JoinSet};
13use tokio::time::{sleep, timeout};
14use tokio_util::sync::CancellationToken;
15
16use tracing::{Instrument, Span};
17
18use google_cloud_gax::grpc::metadata::MetadataMap;
19use google_cloud_gax::grpc::{Code, Status};
20use google_cloud_gax::retry::TryAs;
21use google_cloud_googleapis::spanner::v1::{BatchCreateSessionsRequest, DeleteSessionRequest, Session};
22
23use crate::apiv1::conn_pool::ConnectionManager;
24use crate::apiv1::spanner_client::{ping_query_request, Client};
25use crate::metrics::{MetricsRecorder, SessionPoolSnapshot, SessionPoolStatsFn};
26
27const MAX_IN_USE_WINDOW: Duration = Duration::from_secs(600);
28
29/// Session
30pub struct SessionHandle {
31    pub session: Session,
32    pub spanner_client: Client,
33    valid: bool,
34    deleted: bool,
35    last_used_at: Instant,
36    last_checked_at: Instant,
37    last_pong_at: Instant,
38    created_at: Instant,
39}
40
41impl SessionHandle {
42    pub(crate) fn new(session: Session, spanner_client: Client, now: Instant) -> SessionHandle {
43        SessionHandle {
44            session,
45            spanner_client,
46            valid: true,
47            deleted: false,
48            last_used_at: now,
49            last_checked_at: now,
50            last_pong_at: now,
51            created_at: now,
52        }
53    }
54
55    pub async fn invalidate_if_needed<T>(&mut self, arg: Result<T, Status>) -> Result<T, Status> {
56        match arg {
57            Ok(s) => Ok(s),
58            Err(e) => {
59                if e.code() == Code::NotFound && e.message().contains("Session not found:") {
60                    tracing::debug!("session invalidate {}", self.session.name);
61                    self.delete().await;
62                }
63                Err(e)
64            }
65        }
66    }
67
68    async fn delete(&mut self) {
69        self.valid = false;
70        let session_name = &self.session.name;
71        let request = DeleteSessionRequest {
72            name: session_name.to_string(),
73        };
74        match self.spanner_client.delete_session(request, true, None).await {
75            Ok(_) => self.deleted = true,
76            Err(e) => tracing::warn!("failed to delete session {}, {:?}", session_name, e),
77        };
78    }
79}
80
81/// ManagedSession
82pub struct ManagedSession {
83    session_pool: SessionPool,
84    session: Option<SessionHandle>,
85}
86
87impl ManagedSession {
88    fn new(session_pool: SessionPool, session: SessionHandle) -> Self {
89        ManagedSession {
90            session_pool,
91            session: Some(session),
92        }
93    }
94}
95
96impl Drop for ManagedSession {
97    fn drop(&mut self) {
98        let session = self.session.take().unwrap();
99        self.session_pool.recycle(session);
100    }
101}
102
103impl Deref for ManagedSession {
104    type Target = SessionHandle;
105
106    fn deref(&self) -> &Self::Target {
107        self.session.as_ref().unwrap()
108    }
109}
110
111impl DerefMut for ManagedSession {
112    fn deref_mut(&mut self) -> &mut Self::Target {
113        self.session.as_mut().unwrap()
114    }
115}
116
117/// Sessions have all sessions and waiters.
118/// This is for atomically locking the waiting list and free sessions.
119struct Sessions {
120    available_sessions: VecDeque<SessionHandle>,
121
122    waiters: VecDeque<oneshot::Sender<()>>,
123
124    /// Invalid sessions living in the server.
125    orphans: Vec<SessionHandle>,
126
127    /// number of sessions user uses.
128    num_inuse: usize,
129
130    /// number of sessions scheduled to be replenished.
131    num_creating: usize,
132
133    /// Maximum observed number of sessions in use during the current window.
134    max_inuse_window: usize,
135    /// Start of the rolling window used for `max_inuse_window`.
136    window_started_at: Instant,
137}
138
139impl Sessions {
140    fn num_opened(&self) -> usize {
141        self.num_inuse + self.available_sessions.len()
142    }
143
144    fn take_waiter(&mut self) -> Option<oneshot::Sender<()>> {
145        while let Some(waiter) = self.waiters.pop_front() {
146            // Waiter can be closed when session acquisition times out.
147            if !waiter.is_closed() {
148                return Some(waiter);
149            }
150        }
151        None
152    }
153
154    fn take(&mut self) -> Option<SessionHandle> {
155        match self.available_sessions.pop_front() {
156            None => None,
157            Some(s) => {
158                self.num_inuse += 1;
159                self.update_max_in_use();
160                Some(s)
161            }
162        }
163    }
164
165    fn release(&mut self, session: SessionHandle) {
166        if self.num_inuse > 0 {
167            self.num_inuse -= 1;
168        }
169        if session.valid {
170            self.available_sessions.push_back(session);
171        } else if !session.deleted {
172            tracing::trace!("save as orphan name={}", session.session.name);
173            self.orphans.push(session);
174        }
175    }
176
177    /// reserve calculates next session count to create.
178    /// Must call replenish after calling this method.
179    fn reserve(&mut self, max_opened: usize, inc_step: usize) -> usize {
180        let num_opened = self.num_opened();
181        let num_creating = self.num_creating;
182        if max_opened < num_creating + num_opened {
183            tracing::trace!(
184                "No available connections max={}, num_creating={}, current={}",
185                max_opened,
186                num_creating,
187                num_opened
188            );
189            return 0;
190        }
191        let mut increasing = max_opened - (num_creating + num_opened);
192        if increasing > inc_step {
193            increasing = inc_step
194        }
195        self.num_creating += increasing;
196        increasing
197    }
198
199    fn replenish(&mut self, session_count: usize, result: Result<Vec<SessionHandle>, Status>) {
200        self.num_creating -= session_count;
201        match result {
202            Ok(mut new_sessions) => {
203                while let Some(session) = new_sessions.pop() {
204                    self.available_sessions.push_back(session);
205                    if let Some(waiter) = self.take_waiter() {
206                        let _ = waiter.send(());
207                    }
208                }
209            }
210            Err(e) => tracing::error!("failed to create new sessions {:?}", e),
211        }
212    }
213
214    fn update_max_in_use(&mut self) {
215        let now = Instant::now();
216        if now.duration_since(self.window_started_at) >= MAX_IN_USE_WINDOW {
217            self.window_started_at = now;
218            self.max_inuse_window = self.num_inuse;
219        } else if self.num_inuse > self.max_inuse_window {
220            self.max_inuse_window = self.num_inuse;
221        }
222    }
223}
224
225/// Keeps an idle session from being stranded when an acquisition is cancelled.
226struct SessionWaiter<'a> {
227    sessions: &'a RwLock<Sessions>,
228    receiver: oneshot::Receiver<()>,
229}
230
231impl Drop for SessionWaiter<'_> {
232    fn drop(&mut self) {
233        let mut sessions = self.sessions.write();
234        // Serialize closing the receiver with selecting and notifying waiters.
235        // The timeout must borrow the receiver so it cannot close it outside this lock.
236        self.receiver.close();
237        if !sessions.available_sessions.is_empty() {
238            if let Some(waiter) = sessions.take_waiter() {
239                let _ = waiter.send(());
240            }
241        }
242    }
243}
244
245#[derive(Clone)]
246struct SessionPool {
247    inner: Arc<RwLock<Sessions>>,
248    session_creation_sender: UnboundedSender<usize>,
249    config: Arc<SessionConfig>,
250    metrics: Arc<MetricsRecorder>,
251}
252
253impl SessionPool {
254    async fn new(
255        database: String,
256        conn_pool: &ConnectionManager,
257        session_creation_sender: UnboundedSender<usize>,
258        config: Arc<SessionConfig>,
259        disable_route_to_leader: bool,
260        metrics: Arc<MetricsRecorder>,
261    ) -> Result<Self, Status> {
262        let available_sessions =
263            Self::init_pool(database, conn_pool, config.min_opened, disable_route_to_leader, metrics.clone()).await?;
264        let pool = SessionPool {
265            inner: Arc::new(RwLock::new(Sessions {
266                available_sessions,
267                waiters: VecDeque::new(),
268                orphans: Vec::new(),
269                num_inuse: 0,
270                num_creating: 0,
271                max_inuse_window: 0,
272                window_started_at: Instant::now(),
273            })),
274            session_creation_sender,
275            config,
276            metrics,
277        };
278        pool.metrics.register_session_pool(pool.snapshot_fn());
279        Ok(pool)
280    }
281
282    async fn init_pool(
283        database: String,
284        conn_pool: &ConnectionManager,
285        min_opened: usize,
286        disable_route_to_leader: bool,
287        metrics: Arc<MetricsRecorder>,
288    ) -> Result<VecDeque<SessionHandle>, Status> {
289        let channel_num = conn_pool.num();
290        let creation_count_per_channel = min_opened / channel_num;
291        let remainder = min_opened % channel_num;
292
293        let mut sessions = Vec::<SessionHandle>::new();
294        let mut tasks = JoinSet::new();
295        for i in 0..channel_num {
296            // Ensure that we create the exact number of requested sessions by adding the remainder to the first channel.
297            let creation_count = if i == 0 {
298                creation_count_per_channel + remainder
299            } else {
300                creation_count_per_channel
301            };
302            let next_client = conn_pool
303                .conn()
304                .with_metrics(metrics.clone())
305                .with_metadata(client_metadata(&database));
306            let database = database.clone();
307            tasks.spawn(async move {
308                batch_create_sessions(next_client, &database, creation_count, disable_route_to_leader).await
309            }.instrument(Span::current()));
310        }
311        while let Some(r) = tasks.join_next().await {
312            let new_sessions = r.map_err(|e| Status::from_error(e.into()))??;
313            sessions.extend(new_sessions);
314        }
315        tracing::debug!("initial session created count = {}", sessions.len());
316        Ok(sessions.into())
317    }
318
319    fn num_opened(&self) -> usize {
320        self.inner.read().num_opened()
321    }
322
323    /// The client first checks the waiting list.
324    /// If the waiting list is empty, it retrieves the first available session.
325    /// If there are no available sessions, it enters the waiting list.
326    /// If the waiting list is not empty, the client enters the waiting list.
327    /// The client on the waiting list will be notified when another client's session has finished and
328    /// when the process of replenishing the available sessions is complete.
329    async fn acquire(&self) -> Result<ManagedSession, SessionError> {
330        let request_started_at = Instant::now();
331        loop {
332            let (mut waiter, session_count) = {
333                let mut sessions = self.inner.write();
334
335                // Prioritize waiters over new acquirers.
336                if sessions.waiters.is_empty() {
337                    if let Some(mut s) = sessions.take() {
338                        s.last_used_at = Instant::now();
339                        self.metrics.record_session_acquired();
340                        self.metrics
341                            .record_session_acquire_latency(request_started_at.elapsed());
342                        return Ok(ManagedSession::new(self.clone(), s));
343                    }
344                }
345                // Add the participant to the waiting list.
346                let (sender, receiver) = oneshot::channel();
347                sessions.waiters.push_back(sender);
348                let session_count = sessions.reserve(self.config.max_opened, self.config.inc_step);
349                (
350                    SessionWaiter {
351                        sessions: &self.inner,
352                        receiver,
353                    },
354                    session_count,
355                )
356            };
357
358            if session_count > 0 {
359                let _ = self.session_creation_sender.send(session_count);
360            }
361
362            // Wait for the session available notification.
363            match timeout(self.config.session_get_timeout, &mut waiter.receiver).await {
364                Ok(Ok(())) => {
365                    let mut sessions = self.inner.write();
366                    if let Some(mut s) = sessions.take() {
367                        s.last_used_at = Instant::now();
368                        self.metrics.record_session_acquired();
369                        self.metrics
370                            .record_session_acquire_latency(request_started_at.elapsed());
371                        return Ok(ManagedSession::new(self.clone(), s));
372                    } else {
373                        continue; // another waiter raced for session
374                    }
375                }
376                _ => {
377                    {
378                        let sessions = self.inner.write();
379                        tracing::info!(
380                            available = sessions.available_sessions.len(),
381                            waiters = sessions.waiters.len(),
382                            orphans = sessions.orphans.len(),
383                            num_inuse = sessions.num_inuse,
384                            num_creating = sessions.num_creating,
385                            max_opened = self.config.max_opened,
386                            "Timeout acquiring session"
387                        );
388                    }
389                    self.metrics.record_session_timeout();
390                    return Err(SessionError::SessionGetTimeout);
391                }
392            }
393        }
394    }
395
396    /// If the session is valid
397    ///  - Pass the session to the first user on the waiting list.
398    ///  - If there is no waiting list, the session is returned to the list of available sessions.
399    ///    If the session is invalid
400    ///  - Discard the session. If the number of sessions falls below the threshold as a result of discarding, the session replenishment process is called.
401    fn recycle(&self, mut session: SessionHandle) {
402        self.metrics.record_session_released();
403        if session.valid {
404            let mut sessions = self.inner.write();
405            let waiter = sessions.take_waiter();
406            if sessions.num_opened() > self.config.max_idle
407                && session.created_at + self.config.idle_timeout < Instant::now()
408                && waiter.is_none()
409            {
410                // Not reuse expired idle session
411                session.valid = false
412            }
413            sessions.release(session);
414            if let Some(waiter) = waiter {
415                let _ = waiter.send(());
416            }
417        } else {
418            let session_count = {
419                let mut sessions = self.inner.write();
420                sessions.release(session);
421                if sessions.num_opened() < self.config.min_opened && !sessions.waiters.is_empty() {
422                    sessions.reserve(self.config.max_opened, self.config.inc_step)
423                } else {
424                    0
425                }
426            };
427            if session_count > 0 {
428                let _ = self.session_creation_sender.send(session_count);
429            }
430        }
431    }
432
433    async fn close(&self) {
434        let empty = VecDeque::new();
435        let deleting_sessions = { mem::replace(&mut self.inner.write().available_sessions, empty) };
436        for mut session in deleting_sessions {
437            session.delete().await;
438        }
439
440        self.remove_orphans().await;
441    }
442
443    fn snapshot_fn(&self) -> SessionPoolStatsFn {
444        // Weak ref to break the cycle: Sessions -> SessionHandle -> client -> MetricsRecorder -> gauge callback -> Sessions.
445        let inner = Arc::downgrade(&self.inner);
446        let max_allowed = self.config.max_opened;
447        Arc::new(move || {
448            let Some(inner) = inner.upgrade() else {
449                return SessionPoolSnapshot {
450                    open_sessions: 0,
451                    sessions_in_use: 0,
452                    idle_sessions: 0,
453                    max_allowed_sessions: max_allowed,
454                    max_in_use_last_window: 0,
455                    has_multiplexed_session: false,
456                };
457            };
458            let sessions = inner.read();
459            SessionPoolSnapshot {
460                open_sessions: sessions.num_opened(),
461                sessions_in_use: sessions.num_inuse,
462                idle_sessions: sessions.available_sessions.len(),
463                max_allowed_sessions: max_allowed,
464                max_in_use_last_window: sessions.max_inuse_window,
465                has_multiplexed_session: false,
466            }
467        })
468    }
469
470    async fn remove_orphans(&self) {
471        let empty = vec![];
472        let deleting_sessions = { mem::replace(&mut self.inner.write().orphans, empty) };
473        tracing::trace!("remove {} orphan sessions", deleting_sessions.len());
474        for mut session in deleting_sessions {
475            session.delete().await;
476        }
477    }
478}
479
480#[derive(Clone, Debug)]
481pub struct SessionConfig {
482    /// max_opened is the maximum number of opened sessions allowed by the session
483    /// pool. If the client tries to open a session and there are already
484    /// max_opened sessions, it will block until one becomes available or the
485    /// context passed to the client method is canceled or times out.
486    pub max_opened: usize,
487
488    /// min_opened is the minimum number of opened sessions that the session pool
489    /// tries to maintain. Session pool won't continue to expire sessions if
490    /// number of opened connections drops below min_opened. However, if a session
491    /// is found to be broken, it will still be evicted from the session pool,
492    /// therefore it is posssible that the number of opened sessions drops below
493    /// min_opened.
494    pub min_opened: usize,
495
496    /// max_idle is the maximum number of idle sessions, pool is allowed to keep.
497    pub max_idle: usize,
498
499    /// idle_timeout is the wait time before discarding an idle session.
500    /// Sessions older than this value since they were last used will be discarded.
501    /// However, if the number of sessions is less than or equal to min_opened, it will not be discarded.
502    pub idle_timeout: Duration,
503
504    pub session_alive_trust_duration: Duration,
505
506    /// session_get_timeout is the maximum value of the waiting time that occurs when retrieving from the connection pool when there is no idle session.
507    pub session_get_timeout: Duration,
508
509    /// refresh_interval is the interval of cleanup and health check functions.
510    pub refresh_interval: Duration,
511
512    /// incStep is the number of sessions to create in one batch when at least
513    /// one more session is needed.
514    inc_step: usize,
515}
516
517impl Default for SessionConfig {
518    fn default() -> Self {
519        SessionConfig {
520            max_opened: 400,
521            min_opened: 10,
522            max_idle: 300,
523            inc_step: 25,
524            idle_timeout: Duration::from_secs(30 * 60),
525            session_alive_trust_duration: Duration::from_secs(55 * 60),
526            session_get_timeout: Duration::from_secs(1),
527            refresh_interval: Duration::from_secs(5 * 60),
528        }
529    }
530}
531
532#[derive(thiserror::Error, Debug)]
533pub enum SessionError {
534    #[error("session get time out")]
535    SessionGetTimeout,
536    #[error("failed to create session")]
537    FailedToCreateSession,
538    #[error(transparent)]
539    GRPC(#[from] Status),
540}
541
542impl TryAs<Status> for SessionError {
543    fn try_as(&self) -> Option<&Status> {
544        match self {
545            SessionError::GRPC(e) => Some(e),
546            _ => None,
547        }
548    }
549}
550
551pub(crate) struct SessionManager {
552    session_pool: SessionPool,
553    cancel: CancellationToken,
554    tasks: Mutex<Vec<JoinHandle<()>>>,
555}
556
557impl Drop for SessionManager {
558    /// Stops the background tasks when the last `Client` clone is dropped without
559    /// `close().await`. Aborting also covers tasks blocked mid-RPC.
560    fn drop(&mut self) {
561        self.cancel.cancel();
562        for task in self.tasks.lock().drain(..) {
563            task.abort();
564        }
565    }
566}
567
568impl SessionManager {
569    pub async fn new(
570        database: impl Into<String>,
571        conn_pool: ConnectionManager,
572        config: SessionConfig,
573        disable_route_to_leader: bool,
574        metrics: Arc<MetricsRecorder>,
575    ) -> Result<Arc<SessionManager>, Status> {
576        let database = database.into();
577        let (sender, receiver) = mpsc::unbounded_channel();
578        let session_pool = SessionPool::new(
579            database.clone(),
580            &conn_pool,
581            sender,
582            Arc::new(config.clone()),
583            disable_route_to_leader,
584            metrics.clone(),
585        )
586        .await?;
587
588        let cancel = CancellationToken::new();
589        let task_session_cleaner = Self::spawn_health_check_task(config, session_pool.clone(), cancel.clone());
590        let task_session_creator = Self::spawn_session_creation_task(
591            session_pool.clone(),
592            database,
593            conn_pool,
594            receiver,
595            cancel.clone(),
596            disable_route_to_leader,
597        );
598
599        let sm = SessionManager {
600            session_pool,
601            cancel,
602            tasks: Mutex::new(vec![task_session_cleaner, task_session_creator]),
603        };
604        Ok(Arc::new(sm))
605    }
606
607    pub fn num_opened(&self) -> usize {
608        self.session_pool.num_opened()
609    }
610
611    pub async fn get(&self) -> Result<ManagedSession, SessionError> {
612        self.session_pool.acquire().await
613    }
614
615    pub async fn close(&self) {
616        if self.cancel.is_cancelled() {
617            return;
618        }
619        self.cancel.cancel();
620        let tasks = { mem::take(&mut *self.tasks.lock()) };
621        for task in tasks {
622            let _ = task.await;
623        }
624        self.session_pool.close().await;
625    }
626
627    fn spawn_session_creation_task(
628        session_pool: SessionPool,
629        database: String,
630        conn_pool: ConnectionManager,
631        mut rx: UnboundedReceiver<usize>,
632        cancel: CancellationToken,
633        disable_route_to_leader: bool,
634    ) -> JoinHandle<()> {
635        tokio::spawn(async move {
636            let mut tasks = JoinSet::default();
637            loop {
638                select! {
639                    biased;
640                    _ = cancel.cancelled() => break,
641                    Some(Ok((session_count, result))) = tasks.join_next(), if !tasks.is_empty() => {
642                        session_pool.inner.write().replenish(session_count, result);
643                    }
644                    session_count = rx.recv() => match session_count {
645                        Some(session_count) => {
646                            let client = conn_pool
647                                .conn()
648                                .with_metrics(session_pool.metrics.clone())
649                                .with_metadata(client_metadata(&database));
650                            let database = database.clone();
651                            tasks.spawn(async move { (session_count, batch_create_sessions(client, &database, session_count, disable_route_to_leader).await) });
652                        },
653                        // channel closed
654                        None => break
655                    },
656                }
657            }
658            tracing::trace!("shutdown session creation task.");
659        })
660    }
661
662    fn spawn_health_check_task(
663        config: SessionConfig,
664        session_pool: SessionPool,
665        cancel: CancellationToken,
666    ) -> JoinHandle<()> {
667        let start = Instant::now() + config.refresh_interval;
668        let mut interval = tokio::time::interval_at(start.into(), config.refresh_interval);
669
670        tokio::spawn(async move {
671            loop {
672                select! {
673                    _ = interval.tick() => {},
674                    _ = cancel.cancelled() => break
675                }
676                let now = Instant::now();
677
678                // remove orphans first
679                session_pool.remove_orphans().await;
680
681                // start health check
682                health_check(
683                    now + Duration::from_nanos(1),
684                    config.session_alive_trust_duration,
685                    &session_pool,
686                    cancel.clone(),
687                )
688                .await;
689            }
690            tracing::trace!("shutdown health check task.")
691        })
692    }
693}
694
695async fn health_check(
696    now: Instant,
697    session_alive_trust_duration: Duration,
698    sessions: &SessionPool,
699    cancel: CancellationToken,
700) {
701    tracing::trace!("start health check");
702    let start = Instant::now();
703    let sleep_duration = Duration::from_millis(10);
704    loop {
705        select! {
706            _ = sleep(sleep_duration) => {},
707            _ = cancel.cancelled() => break
708        }
709        let mut s = {
710            // temporary take
711            let mut locked = sessions.inner.write();
712            match locked.take() {
713                Some(mut s) => {
714                    // all the session check complete.
715                    if s.last_checked_at == now {
716                        locked.release(s);
717                        break;
718                    }
719                    if std::cmp::max(s.last_used_at, s.last_pong_at) + session_alive_trust_duration >= now {
720                        s.last_checked_at = now;
721                        locked.release(s);
722                        continue;
723                    }
724                    s
725                }
726                None => break,
727            }
728        };
729
730        let request = ping_query_request(s.session.name.clone());
731        match s.spanner_client.execute_sql(request, true, None).await {
732            Ok(_) => {
733                s.last_checked_at = now;
734                s.last_pong_at = now;
735                sessions.recycle(s);
736            }
737            Err(_) => {
738                s.delete().await;
739                sessions.recycle(s);
740            }
741        }
742    }
743    tracing::trace!("end health check elapsed={}msec", start.elapsed().as_millis());
744}
745
746async fn batch_create_sessions(
747    spanner_client: Client,
748    database: &str,
749    mut remaining_create_count: usize,
750    disable_route_to_leader: bool,
751) -> Result<Vec<SessionHandle>, Status> {
752    let mut created = Vec::with_capacity(remaining_create_count);
753    while remaining_create_count > 0 {
754        let sessions = batch_create_session(
755            spanner_client.clone(),
756            database,
757            remaining_create_count,
758            disable_route_to_leader,
759        )
760        .await?;
761        // Spanner could return less sessions than requested.
762        // In that case, we should do another call using the same gRPC channel.
763        let actually_created = sessions.len();
764        remaining_create_count -= actually_created;
765        created.extend(sessions);
766    }
767    Ok(created)
768}
769
770async fn batch_create_session(
771    mut spanner_client: Client,
772    database: &str,
773    session_count: usize,
774    disable_route_to_leader: bool,
775) -> Result<Vec<SessionHandle>, Status> {
776    let request = BatchCreateSessionsRequest {
777        database: database.to_string(),
778        session_template: None,
779        session_count: session_count as i32,
780    };
781
782    tracing::debug!("spawn session creation request : session_count = {}", session_count);
783    let response = spanner_client
784        .batch_create_sessions(request, disable_route_to_leader, None)
785        .await?
786        .into_inner();
787
788    let now = Instant::now();
789    Ok(response
790        .session
791        .into_iter()
792        .map(|s| SessionHandle::new(s, spanner_client.clone(), now))
793        .collect::<Vec<SessionHandle>>())
794}
795
796pub(crate) fn client_metadata(database: &str) -> MetadataMap {
797    let mut metadata = MetadataMap::new();
798    metadata.insert("google-cloud-resource-prefix", database.parse().unwrap());
799    metadata
800}
801
802#[cfg(test)]
803mod tests {
804    use std::collections::VecDeque;
805    use std::future::{poll_fn, Future};
806    use std::sync::atomic::{AtomicI64, Ordering};
807    use std::sync::Arc;
808    use std::task::Poll;
809    use std::time::{Duration, Instant};
810
811    use parking_lot::RwLock;
812    use serial_test::serial;
813    use tokio::sync::mpsc;
814    use tokio::time::sleep;
815    use tokio_util::sync::CancellationToken;
816
817    use google_cloud_gax::conn::{ConnectionOptions, Environment};
818    use google_cloud_googleapis::spanner::v1::{ExecuteSqlRequest, Session};
819
820    use crate::apiv1::conn_pool::ConnectionManager;
821    use crate::metrics::MetricsRecorder;
822    use crate::session::{
823        batch_create_sessions, client_metadata, health_check, SessionConfig, SessionError, SessionHandle,
824        SessionManager, SessionPool, Sessions,
825    };
826
827    pub const DATABASE: &str = "projects/local-project/instances/test-instance/databases/local-database";
828
829    #[ctor::ctor]
830    fn init() {
831        let filter = tracing_subscriber::filter::EnvFilter::from_default_env()
832            .add_directive("google_cloud_spanner=trace".parse().unwrap());
833        let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init();
834    }
835
836    async fn single_session_pool() -> (SessionPool, tokio::net::TcpStream) {
837        // These tests never issue an RPC, so the transport only needs a TCP peer.
838        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
839        let environment = Environment::Emulator(listener.local_addr().unwrap().to_string());
840        let options = ConnectionOptions::default();
841        let (connection, peer) =
842            tokio::join!(ConnectionManager::new(1, &environment, "", &options), listener.accept(),);
843        let client = connection.unwrap().conn();
844        let (peer, _) = peer.unwrap();
845        let now = Instant::now();
846        let handle = SessionHandle::new(Session::default(), client, now);
847        let (session_creation_sender, _) = mpsc::unbounded_channel();
848        let pool = SessionPool {
849            inner: Arc::new(RwLock::new(Sessions {
850                available_sessions: VecDeque::from([handle]),
851                waiters: VecDeque::new(),
852                orphans: Vec::new(),
853                num_inuse: 0,
854                num_creating: 0,
855                max_inuse_window: 0,
856                window_started_at: now,
857            })),
858            session_creation_sender,
859            config: Arc::new(SessionConfig {
860                max_opened: 1,
861                min_opened: 1,
862                max_idle: 1,
863                session_get_timeout: Duration::from_secs(1),
864                ..Default::default()
865            }),
866            metrics: Arc::new(MetricsRecorder::default()),
867        };
868        (pool, peer)
869    }
870
871    #[tokio::test]
872    async fn cancellation_before_notification_preserves_progress() {
873        let (pool, _peer) = single_session_pool().await;
874        tokio::time::pause();
875        let held = pool.acquire().await.unwrap();
876        let mut first = Box::pin(pool.acquire());
877        let mut second = Box::pin(pool.acquire());
878        poll_fn(|cx| {
879            assert!(first.as_mut().poll(cx).is_pending());
880            assert!(second.as_mut().poll(cx).is_pending());
881            Poll::Ready(())
882        })
883        .await;
884        assert_eq!(pool.inner.read().waiters.len(), 2);
885
886        drop(first);
887        drop(held);
888
889        let _session = second
890            .await
891            .expect("the remaining waiter should acquire the returned session");
892    }
893
894    #[tokio::test]
895    async fn cancellation_after_notification_preserves_progress() {
896        let (pool, _peer) = single_session_pool().await;
897        tokio::time::pause();
898        let held = pool.acquire().await.unwrap();
899        let mut first = Box::pin(pool.acquire());
900        let mut second = Box::pin(pool.acquire());
901        poll_fn(|cx| {
902            assert!(first.as_mut().poll(cx).is_pending());
903            assert!(second.as_mut().poll(cx).is_pending());
904            Poll::Ready(())
905        })
906        .await;
907        assert_eq!(pool.inner.read().waiters.len(), 2);
908
909        // Returning the only session notifies the first waiter, which is never polled again.
910        drop(held);
911        assert_eq!(pool.inner.read().waiters.len(), 1);
912        drop(first);
913
914        let _session = second.await.unwrap_or_else(|err| {
915            let state = pool.inner.read();
916            panic!(
917                "remaining waiter failed: {err}; idle={}, in_use={}, waiters={}",
918                state.available_sessions.len(),
919                state.num_inuse,
920                state.waiters.len()
921            );
922        });
923    }
924
925    #[tokio::test]
926    async fn cancellation_after_replenishment_preserves_progress() {
927        let (pool, _peer) = single_session_pool().await;
928        tokio::time::pause();
929        // Hold the session outside the pool to simulate an in-flight creation RPC.
930        let created = {
931            let mut sessions = pool.inner.write();
932            sessions.num_creating = 1;
933            sessions.available_sessions.pop_front().unwrap()
934        };
935        let mut first = Box::pin(pool.acquire());
936        let mut second = Box::pin(pool.acquire());
937        let mut third = Box::pin(pool.acquire());
938        poll_fn(|cx| {
939            assert!(first.as_mut().poll(cx).is_pending());
940            assert!(second.as_mut().poll(cx).is_pending());
941            assert!(third.as_mut().poll(cx).is_pending());
942            Poll::Ready(())
943        })
944        .await;
945
946        pool.inner.write().replenish(1, Ok(vec![created]));
947        assert_eq!(pool.inner.read().waiters.len(), 2);
948        drop(first);
949        assert_eq!(pool.inner.read().waiters.len(), 1);
950        drop(second);
951
952        let session = third
953            .await
954            .expect("successive cancellations should pass on the notification");
955        {
956            let sessions = pool.inner.read();
957            assert_eq!(sessions.num_inuse, 1);
958            assert_eq!(sessions.num_creating, 0);
959            assert!(sessions.available_sessions.is_empty());
960            assert!(sessions.waiters.is_empty());
961        }
962        drop(session);
963        assert_eq!(pool.inner.read().num_inuse, 0);
964        assert_eq!(pool.inner.read().available_sessions.len(), 1);
965    }
966
967    async fn assert_rush(use_invalidate: bool, config: SessionConfig) -> Arc<SessionManager> {
968        let cm = ConnectionManager::new(
969            4,
970            &Environment::Emulator("localhost:9010".to_string()),
971            "",
972            &ConnectionOptions::default(),
973        )
974        .await
975        .unwrap();
976        let sm = SessionManager::new(DATABASE, cm, config, false, Arc::new(MetricsRecorder::default()))
977            .await
978            .unwrap();
979
980        let counter = Arc::new(AtomicI64::new(0));
981        let mut spawns = Vec::with_capacity(100);
982        for _ in 0..100 {
983            let sm = sm.clone();
984            let counter = Arc::clone(&counter);
985            spawns.push(tokio::spawn(async move {
986                let mut session = sm.get().await.unwrap();
987                if use_invalidate {
988                    session.delete().await;
989                }
990                counter.fetch_add(1, Ordering::SeqCst);
991                sleep(Duration::from_millis(300)).await;
992            }));
993        }
994        for handler in spawns {
995            let _ = handler.await;
996        }
997        sm
998    }
999
1000    #[tokio::test(flavor = "multi_thread")]
1001    #[serial]
1002    async fn test_health_check_checked() {
1003        let cm = ConnectionManager::new(
1004            4,
1005            &Environment::Emulator("localhost:9010".to_string()),
1006            "",
1007            &ConnectionOptions::default(),
1008        )
1009        .await
1010        .unwrap();
1011        let session_alive_trust_duration = Duration::from_millis(10);
1012        let config = SessionConfig {
1013            min_opened: 5,
1014            session_alive_trust_duration,
1015            max_opened: 5,
1016            ..Default::default()
1017        };
1018        let sm = std::sync::Arc::new(
1019            SessionManager::new(DATABASE, cm, config, false, Arc::new(MetricsRecorder::default()))
1020                .await
1021                .unwrap(),
1022        );
1023        sleep(Duration::from_secs(1)).await;
1024
1025        let cancel = CancellationToken::new();
1026        health_check(Instant::now(), session_alive_trust_duration, &sm.session_pool, cancel.clone()).await;
1027
1028        assert_eq!(sm.num_opened(), 5);
1029        tokio::time::sleep(Duration::from_millis(500)).await;
1030        cancel.cancel();
1031    }
1032
1033    #[tokio::test(flavor = "multi_thread")]
1034    #[serial]
1035    async fn test_health_check_not_checked() {
1036        let cm = ConnectionManager::new(
1037            4,
1038            &Environment::Emulator("localhost:9010".to_string()),
1039            "",
1040            &ConnectionOptions::default(),
1041        )
1042        .await
1043        .unwrap();
1044        let session_alive_trust_duration = Duration::from_secs(10);
1045        let config = SessionConfig {
1046            min_opened: 5,
1047            session_alive_trust_duration,
1048            max_opened: 5,
1049            ..Default::default()
1050        };
1051        let sm = Arc::new(
1052            SessionManager::new(DATABASE, cm, config, false, Arc::new(MetricsRecorder::default()))
1053                .await
1054                .unwrap(),
1055        );
1056        sleep(Duration::from_secs(1)).await;
1057
1058        let cancel = CancellationToken::new();
1059        health_check(Instant::now(), session_alive_trust_duration, &sm.session_pool, cancel.clone()).await;
1060
1061        assert_eq!(sm.num_opened(), 5);
1062        sleep(Duration::from_millis(500)).await;
1063        cancel.cancel();
1064    }
1065
1066    #[tokio::test(flavor = "multi_thread")]
1067    #[serial]
1068    async fn test_increase_session_and_idle_session_expired() {
1069        let conn_pool = ConnectionManager::new(
1070            4,
1071            &Environment::Emulator("localhost:9010".to_string()),
1072            "",
1073            &ConnectionOptions::default(),
1074        )
1075        .await
1076        .unwrap();
1077        let config = SessionConfig {
1078            idle_timeout: Duration::from_millis(10),
1079            min_opened: 10,
1080            max_idle: 20,
1081            max_opened: 45,
1082            ..Default::default()
1083        };
1084        let sm = SessionManager::new(DATABASE, conn_pool, config, false, Arc::new(MetricsRecorder::default()))
1085            .await
1086            .unwrap();
1087        {
1088            let mut sessions = Vec::new();
1089            for _ in 0..45 {
1090                sessions.push(sm.get().await.unwrap());
1091            }
1092
1093            // all the session are using
1094            assert_eq!(sm.num_opened(), 45);
1095            assert_eq!(sm.session_pool.inner.read().num_inuse, 45, "all the session are using");
1096            sleep(Duration::from_secs(1)).await;
1097        }
1098
1099        // idle session removed after drop
1100        let sessions = sm.session_pool.inner.read();
1101        assert_eq!(sessions.num_inuse, 0, "invalid num_inuse");
1102        assert_eq!(sessions.available_sessions.len(), 20, "invalid available sessions");
1103        assert_eq!(sessions.num_opened(), 20, "invalid num open");
1104        assert_eq!(sessions.waiters.len(), 0, "session waiters is 0");
1105    }
1106
1107    #[tokio::test(flavor = "multi_thread")]
1108    #[serial]
1109    async fn test_too_many_session_timeout() {
1110        let conn_pool = ConnectionManager::new(
1111            4,
1112            &Environment::Emulator("localhost:9010".to_string()),
1113            "",
1114            &ConnectionOptions::default(),
1115        )
1116        .await
1117        .unwrap();
1118        let config = SessionConfig {
1119            idle_timeout: Duration::from_millis(10),
1120            min_opened: 10,
1121            max_idle: 20,
1122            max_opened: 45,
1123            session_get_timeout: Duration::from_secs(1),
1124            ..Default::default()
1125        };
1126        let sm = Arc::new(
1127            SessionManager::new(DATABASE, conn_pool, config.clone(), false, Arc::new(MetricsRecorder::default()))
1128                .await
1129                .unwrap(),
1130        );
1131        let mu = Arc::new(RwLock::new(Vec::new()));
1132        let mut awaiters = Vec::with_capacity(100);
1133        for _ in 0..100 {
1134            let sm = sm.clone();
1135            let mu = mu.clone();
1136            awaiters.push(tokio::spawn(async move {
1137                let session = sm.get().await;
1138                mu.write().push(session);
1139                0
1140            }))
1141        }
1142        for handler in awaiters {
1143            let _ = handler.await;
1144        }
1145        let sessions = mu.read();
1146        for i in 0..sessions.len() - 1 {
1147            let session = &sessions[i];
1148            if i >= config.max_opened {
1149                assert!(session.is_err(), "must err {i}");
1150                match session.as_ref().err().unwrap() {
1151                    SessionError::SessionGetTimeout => {}
1152                    _ => {
1153                        panic!("must be session timeout error")
1154                    }
1155                }
1156            } else {
1157                assert!(session.is_ok(), "must ok {i}");
1158            }
1159        }
1160        let pool = sm.session_pool.inner.read();
1161        assert_eq!(pool.num_opened(), config.max_opened);
1162        assert_eq!(pool.waiters.len(), 100 - config.max_opened); //include timeout sessions
1163    }
1164
1165    #[tokio::test(flavor = "multi_thread")]
1166    #[serial]
1167    async fn test_rush_invalidate() {
1168        let config = SessionConfig {
1169            session_get_timeout: Duration::from_secs(20),
1170            min_opened: 10,
1171            max_idle: 20,
1172            max_opened: 45,
1173            ..Default::default()
1174        };
1175        let sm = assert_rush(true, config.clone()).await;
1176        {
1177            let sessions = sm.session_pool.inner.read();
1178            let available_sessions = sessions.available_sessions.len();
1179            assert_eq!(sessions.num_inuse, 0);
1180            assert_eq!(sessions.waiters.len(), 0);
1181            assert_eq!(sessions.orphans.len(), 0);
1182            assert!(
1183                available_sessions <= config.max_opened && available_sessions >= config.min_opened,
1184                "now is {available_sessions}"
1185            );
1186        }
1187        sm.close().await;
1188    }
1189
1190    #[tokio::test(flavor = "multi_thread")]
1191    #[serial]
1192    async fn test_rush() {
1193        let config = SessionConfig {
1194            min_opened: 10,
1195            max_idle: 20,
1196            max_opened: 45,
1197            ..Default::default()
1198        };
1199        let sm = assert_rush(false, config.clone()).await;
1200        {
1201            let sessions = sm.session_pool.inner.read();
1202            let available_sessions = sessions.available_sessions.len();
1203            assert_eq!(sessions.num_inuse, 0);
1204            assert_eq!(sessions.waiters.len(), 0);
1205            assert_eq!(sessions.orphans.len(), 0);
1206            assert!(
1207                available_sessions <= config.max_opened && available_sessions >= config.min_opened,
1208                "now is {available_sessions}"
1209            );
1210        }
1211        sm.close().await;
1212    }
1213
1214    #[tokio::test(flavor = "multi_thread")]
1215    #[serial]
1216    async fn test_rush_with_invalidate() {
1217        let config = SessionConfig {
1218            min_opened: 10,
1219            max_idle: 20,
1220            max_opened: 45,
1221            ..Default::default()
1222        };
1223        let sm = assert_rush(true, config.clone()).await;
1224        {
1225            let sessions = sm.session_pool.inner.read();
1226            let available_sessions = sessions.available_sessions.len();
1227            assert_eq!(sessions.num_inuse, 0);
1228            assert_eq!(sessions.waiters.len(), 0);
1229            assert_eq!(sessions.orphans.len(), 0);
1230            assert!(
1231                available_sessions <= config.max_opened && available_sessions >= config.min_opened,
1232                "now is {available_sessions}"
1233            );
1234        }
1235        sm.close().await;
1236    }
1237
1238    #[tokio::test(flavor = "multi_thread")]
1239    #[serial]
1240    async fn test_rush_with_health_check() {
1241        let config = SessionConfig {
1242            session_alive_trust_duration: Duration::from_millis(10),
1243            refresh_interval: Duration::from_millis(250),
1244            session_get_timeout: Duration::from_secs(20),
1245            min_opened: 10,
1246            max_idle: 20,
1247            max_opened: 45,
1248            ..Default::default()
1249        };
1250        let sm = assert_rush(false, config.clone()).await;
1251        sleep(Duration::from_secs(2)).await;
1252        {
1253            let sessions = sm.session_pool.inner.read();
1254            let available_sessions = sessions.available_sessions.len();
1255            assert!(sessions.num_inuse <= 1, "num_inuse is {}", sessions.num_inuse);
1256            assert_eq!(sessions.waiters.len(), 0);
1257            assert_eq!(sessions.orphans.len(), 0);
1258            assert!(
1259                available_sessions <= config.max_opened && available_sessions >= config.max_idle - 1,
1260                "now is {available_sessions}"
1261            );
1262        }
1263        sm.close().await;
1264    }
1265
1266    #[tokio::test(flavor = "multi_thread")]
1267    #[serial]
1268    async fn test_rush_with_health_check_and_invalidate() {
1269        let config = SessionConfig {
1270            session_alive_trust_duration: Duration::from_millis(10),
1271            refresh_interval: Duration::from_millis(250),
1272            session_get_timeout: Duration::from_secs(20),
1273            min_opened: 10,
1274            max_idle: 20,
1275            max_opened: 45,
1276            ..Default::default()
1277        };
1278        let sm = assert_rush(true, config.clone()).await;
1279        sleep(Duration::from_secs(2)).await;
1280        {
1281            let sessions = sm.session_pool.inner.read();
1282            let available_sessions = sessions.available_sessions.len();
1283            assert!(sessions.num_inuse <= 1, "num_inuse is {}", sessions.num_inuse);
1284            assert_eq!(sessions.waiters.len(), 0);
1285            assert_eq!(sessions.orphans.len(), 0);
1286            assert!(
1287                available_sessions <= config.max_opened && available_sessions >= config.min_opened - 1,
1288                "now is {available_sessions}"
1289            );
1290        }
1291        sm.close().await;
1292    }
1293
1294    #[tokio::test(flavor = "multi_thread")]
1295    #[serial]
1296    async fn test_rush_with_idle_expired() {
1297        let config = SessionConfig {
1298            min_opened: 10,
1299            max_idle: 20,
1300            max_opened: 45,
1301            idle_timeout: Duration::from_millis(1),
1302            ..Default::default()
1303        };
1304        let sm = assert_rush(false, config.clone()).await;
1305        {
1306            let sessions = sm.session_pool.inner.read();
1307            assert_eq!(sessions.num_inuse, 0);
1308            assert_eq!(sessions.waiters.len(), 0);
1309            assert_eq!(sessions.orphans.len(), config.max_opened - config.max_idle);
1310            assert_eq!(sessions.available_sessions.len(), config.max_idle);
1311        }
1312        sm.close().await;
1313    }
1314
1315    #[tokio::test(flavor = "multi_thread")]
1316    #[serial]
1317    async fn test_rush_with_health_check_and_idle_expired() {
1318        let config = SessionConfig {
1319            session_alive_trust_duration: Duration::from_millis(10),
1320            refresh_interval: Duration::from_millis(250),
1321            session_get_timeout: Duration::from_secs(20),
1322            min_opened: 10,
1323            max_idle: 20,
1324            max_opened: 45,
1325            idle_timeout: Duration::from_millis(1),
1326            ..Default::default()
1327        };
1328        let sm = assert_rush(false, config.clone()).await;
1329        sleep(Duration::from_secs(1)).await;
1330        {
1331            let sessions = sm.session_pool.inner.read();
1332            assert!(sessions.num_inuse <= 1, "num_inuse is {}", sessions.num_inuse);
1333            assert_eq!(sessions.waiters.len(), 0);
1334            assert_eq!(sessions.orphans.len(), 0);
1335            let available_sessions = sessions.available_sessions.len();
1336            assert!(
1337                available_sessions >= config.min_opened - 1 && available_sessions <= config.max_idle,
1338                "now is {available_sessions}"
1339            );
1340        }
1341        sm.close().await;
1342    }
1343
1344    #[tokio::test(flavor = "multi_thread")]
1345    #[serial]
1346    async fn test_rush_with_health_check_and_idle_expired_and_invalid() {
1347        let config = SessionConfig {
1348            session_alive_trust_duration: Duration::from_millis(10),
1349            refresh_interval: Duration::from_millis(250),
1350            session_get_timeout: Duration::from_secs(20),
1351            min_opened: 10,
1352            max_idle: 20,
1353            max_opened: 45,
1354            idle_timeout: Duration::from_millis(1),
1355            ..Default::default()
1356        };
1357        let sm = assert_rush(true, config.clone()).await;
1358        sleep(Duration::from_secs(2)).await;
1359        {
1360            let sessions = sm.session_pool.inner.read();
1361            assert!(sessions.num_inuse <= 1, "num_inuse is {}", sessions.num_inuse);
1362            // health checker removes orphans
1363            assert_eq!(sessions.orphans.len(), 0);
1364            assert_eq!(sessions.waiters.len(), 0, "invalid waiters");
1365            let available_sessions = sessions.available_sessions.len();
1366            assert!(
1367                available_sessions >= config.min_opened - 1 && available_sessions <= config.max_idle,
1368                "now is {available_sessions}"
1369            );
1370        }
1371        sm.close().await;
1372    }
1373
1374    #[tokio::test(flavor = "multi_thread")]
1375    #[serial]
1376    async fn test_close() {
1377        let cm = ConnectionManager::new(
1378            4,
1379            &Environment::Emulator("localhost:9010".to_string()),
1380            "",
1381            &ConnectionOptions::default(),
1382        )
1383        .await
1384        .unwrap();
1385        let config = SessionConfig::default();
1386        let sm = SessionManager::new(DATABASE, cm, config.clone(), false, Arc::new(MetricsRecorder::default()))
1387            .await
1388            .unwrap();
1389        assert_eq!(sm.num_opened(), config.min_opened);
1390        sm.close().await;
1391        assert_eq!(sm.num_opened(), 0);
1392        assert_eq!(sm.session_pool.inner.read().orphans.len(), 0);
1393    }
1394
1395    #[tokio::test(flavor = "multi_thread")]
1396    #[serial]
1397    async fn test_drop_cancels_background_tasks() {
1398        let cm = ConnectionManager::new(
1399            4,
1400            &Environment::Emulator("localhost:9010".to_string()),
1401            "",
1402            &ConnectionOptions::default(),
1403        )
1404        .await
1405        .unwrap();
1406        let config = SessionConfig {
1407            min_opened: 5,
1408            max_opened: 10,
1409            ..Default::default()
1410        };
1411        let sm = SessionManager::new(DATABASE, cm, config, false, Arc::new(MetricsRecorder::default()))
1412            .await
1413            .unwrap();
1414
1415        let cancel = sm.cancel.clone();
1416        let pool = Arc::clone(&sm.session_pool.inner);
1417
1418        drop(sm);
1419        assert!(cancel.is_cancelled());
1420
1421        // The background tasks must release their references to the session pool.
1422        let deadline = Instant::now() + Duration::from_secs(5);
1423        while Arc::strong_count(&pool) > 1 {
1424            assert!(Instant::now() < deadline, "background tasks did not stop after drop");
1425            sleep(Duration::from_millis(50)).await;
1426        }
1427    }
1428
1429    #[tokio::test(flavor = "multi_thread")]
1430    #[serial]
1431    async fn test_batch_create_sessions() {
1432        let cm = ConnectionManager::new(
1433            1,
1434            &Environment::Emulator("localhost:9010".to_string()),
1435            "",
1436            &ConnectionOptions::default(),
1437        )
1438        .await
1439        .unwrap();
1440        let client = cm
1441            .conn()
1442            .with_metrics(Arc::new(MetricsRecorder::default()))
1443            .with_metadata(client_metadata(DATABASE));
1444        let session_count = 125;
1445        let result = batch_create_sessions(client.clone(), DATABASE, session_count, false).await;
1446        match result {
1447            Ok(created) => {
1448                assert_eq!(session_count, created.len());
1449                for mut s in created {
1450                    let ping_result = s
1451                        .spanner_client
1452                        .execute_sql(
1453                            ExecuteSqlRequest {
1454                                session: s.session.name.to_string(),
1455                                transaction: None,
1456                                sql: "SELECT 1".to_string(),
1457                                params: None,
1458                                param_types: Default::default(),
1459                                resume_token: vec![],
1460                                query_mode: 0,
1461                                partition_token: vec![],
1462                                seqno: 0,
1463                                query_options: None,
1464                                request_options: None,
1465                                directed_read_options: None,
1466                                data_boost_enabled: false,
1467                                last_statement: false,
1468                            },
1469                            false,
1470                            None,
1471                        )
1472                        .await;
1473                    assert!(ping_result.is_ok());
1474                }
1475            }
1476            Err(err) => panic!("{err:?}"),
1477        }
1478    }
1479}