google-cloud-spanner 0.34.1-preview

Google Cloud Client Libraries for Rust - Spanner
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::client::Spanner;
use crate::model::{CreateSessionRequest, Session};
use crate::{RequestOptions, Result};
use std::sync::{Arc, RwLock, Weak};
use std::time::Duration;
use tokio::time::{Instant, sleep};

/// The interval at which the background task checks if the session needs replacement.
pub(crate) const SESSION_MAINTENANCE_INTERVAL: Duration = Duration::from_secs(3600);

/// The maximum age of a session before it is considered for replacement.
/// Multiplexed sessions are designed to live for 28 days, but we rotate them
/// every 7 days to be safe.
pub(crate) const SESSION_MAINTENANCE_AGE: Duration = Duration::from_secs(7 * 24 * 3600);

#[derive(Debug)]
pub(crate) struct ManagedSessionMaintainer {
    pub(crate) spanner: Spanner,
    pub(crate) session: RwLock<ManagedSession>,
    pub(crate) database_name: String,
    pub(crate) database_role: String,
    pub(crate) options: RequestOptions,
}

#[derive(Debug)]
pub(crate) struct ManagedSession {
    pub(crate) session: Arc<Session>,
    pub(crate) created_at: Instant,
}

impl ManagedSessionMaintainer {
    pub(crate) fn session_name(&self) -> String {
        self.session
            .read()
            .expect("failed to read session")
            .session
            .name
            .clone()
    }

    /// Creates a new `ManagedSessionMaintainer` with an initial session,
    /// and spawns a background task to periodically check and rotate the session.
    pub(crate) async fn create_and_start_maintenance(
        spanner: Spanner,
        database_name: String,
        database_role: String,
        options: RequestOptions,
    ) -> Result<Arc<Self>> {
        let session =
            Self::create_session(&spanner, &database_name, &database_role, &options).await?;

        let maintainer = Arc::new(ManagedSessionMaintainer {
            spanner,
            session: RwLock::new(ManagedSession {
                session: Arc::new(session),
                created_at: Instant::now(),
            }),
            database_name,
            database_role,
            options,
        });

        let weak_maintainer = Arc::downgrade(&maintainer);
        tokio::spawn(async move {
            Self::maintenance_loop(
                weak_maintainer,
                SESSION_MAINTENANCE_INTERVAL,
                SESSION_MAINTENANCE_AGE,
            )
            .await;
        });

        Ok(maintainer)
    }

    async fn check_and_replace_session(&self, age: Duration) -> Result<()> {
        let should_replace = {
            let guard = self.session.read().expect("failed to read session");
            guard.created_at.elapsed() >= age
        };

        if should_replace {
            self.replace_session().await?;
        }
        Ok(())
    }

    async fn replace_session(&self) -> Result<()> {
        let new_session = Self::create_session(
            &self.spanner,
            &self.database_name,
            &self.database_role,
            &self.options,
        )
        .await?;

        let mut guard = self.session.write().expect("failed to write session");
        *guard = ManagedSession {
            session: Arc::new(new_session),
            created_at: Instant::now(),
        };
        tracing::info!(
            "Successfully replaced multiplexed session for {}",
            self.database_name
        );
        Ok(())
    }

    async fn create_session(
        spanner: &Spanner,
        database_name: &str,
        database_role: &str,
        options: &RequestOptions,
    ) -> Result<Session> {
        let request = CreateSessionRequest::new()
            .set_database(database_name)
            .set_session(
                Session::new()
                    .set_multiplexed(true)
                    .set_creator_role(database_role),
            );

        spanner
            .create_session(request, options.clone(), spanner.next_channel_hint())
            .await
    }

    async fn maintenance_loop(
        maintainer: Weak<ManagedSessionMaintainer>,
        interval: Duration,
        age: Duration,
    ) {
        sleep(interval).await;
        while let Some(m) = maintainer.upgrade() {
            Self::maintain(m, age).await;
            sleep(interval).await;
        }
    }

    /// Performs a single maintenance iteration.
    async fn maintain(maintainer: Arc<ManagedSessionMaintainer>, age: Duration) {
        if let Err(e) = maintainer.check_and_replace_session(age).await {
            tracing::warn!(
                "Failed to check and replace session for {}: {}. Retrying in 1 hour.",
                maintainer.database_name,
                e
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use gaxi::grpc::tonic::Response;
    use google_cloud_auth::credentials::anonymous::Builder as Anonymous;
    use google_cloud_test_macros::tokio_test_no_panics;
    use spanner_grpc_mock::google::spanner::v1::Session as GrpcSession;
    use spanner_grpc_mock::{MockSpanner, start};

    #[tokio_test_no_panics]
    async fn session_maintenance() {
        let mut mock = MockSpanner::new();
        let mut seq = mockall::Sequence::new();

        mock.expect_create_session()
            .once()
            .in_sequence(&mut seq)
            .returning(|_| {
                Ok(Response::new(GrpcSession {
                    name:
                        "projects/test-project/instances/test-instance/databases/test-db/sessions/1"
                            .to_string(),
                    multiplexed: true,
                    ..Default::default()
                }))
            });

        mock.expect_create_session()
            .once()
            .in_sequence(&mut seq)
            .returning(|_| {
                Ok(Response::new(GrpcSession {
                    name:
                        "projects/test-project/instances/test-instance/databases/test-db/sessions/2"
                            .to_string(),
                    multiplexed: true,
                    ..Default::default()
                }))
            });

        let (address, _server) = start("0.0.0.0:0", mock)
            .await
            .expect("Failed to start mock server");
        let spanner = Spanner::builder()
            .with_endpoint(address)
            .with_credentials(Anonymous::new().build())
            .build()
            .await
            .expect("Failed to build client");

        let maintainer = ManagedSessionMaintainer::create_and_start_maintenance(
            spanner,
            "projects/test-project/instances/test-instance/databases/test-db".to_string(),
            "test-role".to_string(),
            RequestOptions::default(),
        )
        .await
        .expect("Failed to create ManagedSessionMaintainer");

        {
            let session = maintainer
                .session
                .read()
                .expect("failed to read session")
                .session
                .clone();
            assert_eq!(
                session.name,
                "projects/test-project/instances/test-instance/databases/test-db/sessions/1"
            );
        }

        // Modify created_at to be in the past (older than 7 days)
        {
            let mut guard = maintainer.session.write().expect("failed to write session");
            guard.created_at = Instant::now() - Duration::from_secs(7 * 24 * 3600 + 3600);
        }

        // Manually trigger maintenance check
        maintainer
            .check_and_replace_session(SESSION_MAINTENANCE_AGE)
            .await
            .expect("Failed to check and replace session");

        {
            let session = maintainer
                .session
                .read()
                .expect("failed to read session")
                .session
                .clone();
            assert_eq!(
                session.name,
                "projects/test-project/instances/test-instance/databases/test-db/sessions/2"
            );
        }
    }

    #[tokio_test_no_panics]
    async fn maintain_success() {
        let mut mock = MockSpanner::new();
        mock.expect_create_session().once().returning(|_| {
            Ok(Response::new(GrpcSession {
                name: "projects/test-project/instances/test-instance/databases/test-db/sessions/1"
                    .to_string(),
                multiplexed: true,
                ..Default::default()
            }))
        });

        let (address, _server) = start("0.0.0.0:0", mock)
            .await
            .expect("Failed to start mock server");
        let spanner = Spanner::builder()
            .with_endpoint(address)
            .with_credentials(Anonymous::new().build())
            .build()
            .await
            .expect("Failed to build client");

        let maintainer = ManagedSessionMaintainer::create_and_start_maintenance(
            spanner,
            "projects/test-project/instances/test-instance/databases/test-db".to_string(),
            "test-role".to_string(),
            RequestOptions::default(),
        )
        .await
        .expect("Failed to create ManagedSessionMaintainer");

        let weak = Arc::downgrade(&maintainer);
        let m = weak.upgrade().expect("should be alive");
        ManagedSessionMaintainer::maintain(m, SESSION_MAINTENANCE_AGE).await;
    }

    #[tokio_test_no_panics]
    async fn maintain_dropped() {
        let weak = Weak::<ManagedSessionMaintainer>::new();
        assert!(weak.upgrade().is_none());
    }

    #[tokio_test_no_panics]
    async fn check_and_replace_session_no_op() {
        let mut mock = MockSpanner::new();
        mock.expect_create_session().once().returning(|_| {
            Ok(Response::new(GrpcSession {
                name: "projects/test-project/instances/test-instance/databases/test-db/sessions/1"
                    .to_string(),
                multiplexed: true,
                ..Default::default()
            }))
        });

        let (address, _server) = start("0.0.0.0:0", mock)
            .await
            .expect("Failed to start mock server");
        let spanner = Spanner::builder()
            .with_endpoint(address)
            .with_credentials(Anonymous::new().build())
            .build()
            .await
            .expect("Failed to build client");

        let maintainer = ManagedSessionMaintainer::create_and_start_maintenance(
            spanner,
            "projects/test-project/instances/test-instance/databases/test-db".to_string(),
            "test-role".to_string(),
            RequestOptions::default(),
        )
        .await
        .expect("Failed to create ManagedSessionMaintainer");

        // Call check_and_replace_session with full age (7 days).
        // The session is still valid, and should not be replaced.
        maintainer
            .check_and_replace_session(SESSION_MAINTENANCE_AGE)
            .await
            .expect("Failed to check and replace session");

        // Verify session is still the same.
        let session = maintainer
            .session
            .read()
            .expect("failed to read session")
            .session
            .clone();
        assert_eq!(
            session.name,
            "projects/test-project/instances/test-instance/databases/test-db/sessions/1"
        );
    }

    #[tokio_test_no_panics]
    async fn maintain_creation_fails() {
        let mut mock = MockSpanner::new();
        let mut seq = mockall::Sequence::new();

        // 1st call succeeds (initialization)
        mock.expect_create_session()
            .once()
            .in_sequence(&mut seq)
            .returning(|_| {
                Ok(Response::new(GrpcSession {
                    name:
                        "projects/test-project/instances/test-instance/databases/test-db/sessions/1"
                            .to_string(),
                    multiplexed: true,
                    ..Default::default()
                }))
            });

        // 2nd call fails (maintenance)
        mock.expect_create_session()
            .once()
            .in_sequence(&mut seq)
            .returning(|_| Err(gaxi::grpc::tonic::Status::internal("mock failure")));

        let (address, _server) = start("0.0.0.0:0", mock)
            .await
            .expect("Failed to start mock server");
        let spanner = Spanner::builder()
            .with_endpoint(address)
            .with_credentials(Anonymous::new().build())
            .build()
            .await
            .expect("Failed to build client");

        let maintainer = ManagedSessionMaintainer::create_and_start_maintenance(
            spanner,
            "projects/test-project/instances/test-instance/databases/test-db".to_string(),
            "test-role".to_string(),
            RequestOptions::default(),
        )
        .await
        .expect("Failed to create ManagedSessionMaintainer");

        // Age the session
        {
            let mut guard = maintainer.session.write().expect("failed to write session");
            guard.created_at = Instant::now() - Duration::from_secs(7 * 24 * 3600 + 3600);
        }

        let weak = Arc::downgrade(&maintainer);
        let m = weak.upgrade().expect("should be alive");
        ManagedSessionMaintainer::maintain(m, SESSION_MAINTENANCE_AGE).await;

        // Verify session is still the old one!
        let session = maintainer
            .session
            .read()
            .expect("failed to read session")
            .session
            .clone();
        assert_eq!(
            session.name,
            "projects/test-project/instances/test-instance/databases/test-db/sessions/1"
        );
    }

    #[tokio_test_no_panics]
    async fn transaction_session_consistency_across_retries() {
        use crate::database_client::DatabaseClient;
        use crate::transaction_retry_policy::tests::create_aborted_status;
        use spanner_grpc_mock::google::spanner::v1 as mock_v1;
        use spanner_grpc_mock::google::spanner::v1::result_set_stats::RowCount;

        let mut mock = MockSpanner::new();
        let mut seq = mockall::Sequence::new();

        // 1st call succeeds (initialization)
        mock.expect_create_session()
            .once()
            .in_sequence(&mut seq)
            .returning(|_| {
                Ok(Response::new(mock_v1::Session {
                    name: "projects/p/instances/i/databases/d/sessions/1".to_string(),
                    multiplexed: true,
                    ..Default::default()
                }))
            });

        // 2nd call succeeds (forced replacement)
        mock.expect_create_session()
            .once()
            .in_sequence(&mut seq)
            .returning(|_| {
                Ok(Response::new(mock_v1::Session {
                    name: "projects/p/instances/i/databases/d/sessions/2".to_string(),
                    multiplexed: true,
                    ..Default::default()
                }))
            });

        // Mock begin_transaction (twice)
        mock.expect_begin_transaction().times(2).returning(|req| {
            let req = req.into_inner();
            assert_eq!(req.session, "projects/p/instances/i/databases/d/sessions/1");
            Ok(Response::new(mock_v1::Transaction {
                id: vec![1, 2, 3],
                ..Default::default()
            }))
        });

        // Mock execute_sql for update (attempt 1)
        mock.expect_execute_sql().once().returning(|req| {
            let req = req.into_inner();
            assert_eq!(req.session, "projects/p/instances/i/databases/d/sessions/1");

            Ok(Response::new(mock_v1::ResultSet {
                metadata: Some(mock_v1::ResultSetMetadata {
                    transaction: Some(mock_v1::Transaction {
                        id: vec![1, 2, 3],
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                stats: Some(mock_v1::ResultSetStats {
                    row_count: Some(RowCount::RowCountExact(1)),
                    ..Default::default()
                }),
                ..Default::default()
            }))
        });

        // Mock commit returning Aborted
        mock.expect_commit().once().returning(|req| {
            let req = req.into_inner();
            assert_eq!(req.session, "projects/p/instances/i/databases/d/sessions/1");
            Err(create_aborted_status(std::time::Duration::from_nanos(1)))
        });

        // Mock execute_sql for update (retry attempt)
        mock.expect_execute_sql().once().returning(|req| {
            let req = req.into_inner();
            assert_eq!(req.session, "projects/p/instances/i/databases/d/sessions/1");

            Ok(Response::new(mock_v1::ResultSet {
                metadata: Some(mock_v1::ResultSetMetadata {
                    transaction: Some(mock_v1::Transaction {
                        id: vec![1, 2, 3],
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                stats: Some(mock_v1::ResultSetStats {
                    row_count: Some(RowCount::RowCountExact(1)),
                    ..Default::default()
                }),
                ..Default::default()
            }))
        });

        // Mock commit returning success
        mock.expect_commit().once().returning(|req| {
            let req = req.into_inner();
            assert_eq!(req.session, "projects/p/instances/i/databases/d/sessions/1");
            Ok(Response::new(mock_v1::CommitResponse {
                commit_timestamp: Some(prost_types::Timestamp {
                    seconds: 123456789,
                    nanos: 0,
                }),
                ..Default::default()
            }))
        });

        let (address, _server) = start("0.0.0.0:0", mock)
            .await
            .expect("Failed to start mock server");

        let spanner = Spanner::builder()
            .with_endpoint(address)
            .with_credentials(Anonymous::new().build())
            .build()
            .await
            .expect("Failed to build client");

        let maintainer = ManagedSessionMaintainer::create_and_start_maintenance(
            spanner.clone(),
            "projects/p/instances/i/databases/d".to_string(),
            "test-role".to_string(),
            RequestOptions::default(),
        )
        .await
        .expect("Failed to create ManagedSessionMaintainer");

        let db_client = DatabaseClient {
            spanner,
            session_maintainer: maintainer.clone(),
            leader_aware_routing_enabled: true,
        };

        // 1. Create builder (captures session 1)
        let runner = db_client
            .read_write_transaction()
            .build()
            .await
            .expect("Failed to build runner");

        // 2. Force rotation
        maintainer
            .replace_session()
            .await
            .expect("Failed to replace session");

        // Verify that the maintainer now has session 2
        assert_eq!(
            maintainer.session_name(),
            "projects/p/instances/i/databases/d/sessions/2"
        );

        // 3. Run transaction
        let result = runner
            .run(
                |tx: crate::read_write_transaction::ReadWriteTransaction| async move {
                    let count = tx.execute_update("UPDATE Users SET active = true").await?;
                    assert_eq!(count, 1);
                    Ok(())
                },
            )
            .await;

        result.expect("Transaction failed");
    }
}