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