sui_kvstore/bigtable/
client.rs

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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use crate::bigtable::metrics::KvMetrics;
use crate::bigtable::proto::bigtable::v2::bigtable_client::BigtableClient as BigtableInternalClient;
use crate::bigtable::proto::bigtable::v2::mutate_rows_request::Entry;
use crate::bigtable::proto::bigtable::v2::mutation::SetCell;
use crate::bigtable::proto::bigtable::v2::read_rows_response::cell_chunk::RowStatus;
use crate::bigtable::proto::bigtable::v2::row_range::EndKey;
use crate::bigtable::proto::bigtable::v2::{
    mutation, MutateRowsRequest, MutateRowsResponse, Mutation, ReadRowsRequest, RowRange, RowSet,
};
use crate::{Checkpoint, KeyValueStoreReader, KeyValueStoreWriter, TransactionData};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use gcp_auth::{Token, TokenProvider};
use http::{HeaderValue, Request, Response};
use prometheus::Registry;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};
use std::task::{Context, Poll};
use std::time::Duration;
use std::time::Instant;
use sui_types::base_types::{ObjectID, TransactionDigest};
use sui_types::digests::CheckpointDigest;
use sui_types::full_checkpoint_content::CheckpointData;
use sui_types::messages_checkpoint::CheckpointSequenceNumber;
use sui_types::object::Object;
use sui_types::storage::ObjectKey;
use tonic::body::BoxBody;
use tonic::codegen::Service;
use tonic::transport::{Certificate, Channel, ClientTlsConfig};
use tonic::Streaming;
use tracing::error;

const OBJECTS_TABLE: &str = "objects";
const TRANSACTIONS_TABLE: &str = "transactions";
const CHECKPOINTS_TABLE: &str = "checkpoints";
const CHECKPOINTS_BY_DIGEST_TABLE: &str = "checkpoints_by_digest";
const WATERMARK_TABLE: &str = "watermark";

const COLUMN_FAMILY_NAME: &str = "sui";
const DEFAULT_COLUMN_QUALIFIER: &str = "";
const CHECKPOINT_SUMMARY_COLUMN_QUALIFIER: &str = "s";
const CHECKPOINT_SIGNATURES_COLUMN_QUALIFIER: &str = "sg";
const CHECKPOINT_CONTENTS_COLUMN_QUALIFIER: &str = "c";
const TRANSACTION_COLUMN_QUALIFIER: &str = "tx";
const EFFECTS_COLUMN_QUALIFIER: &str = "ef";
const EVENTS_COLUMN_QUALIFIER: &str = "ev";
const TIMESTAMP_COLUMN_QUALIFIER: &str = "ts";
const CHECKPOINT_NUMBER_COLUMN_QUALIFIER: &str = "cn";

type Bytes = Vec<u8>;

#[derive(Clone)]
struct AuthChannel {
    channel: Channel,
    policy: String,
    token_provider: Option<Arc<dyn TokenProvider>>,
    token: Arc<RwLock<Option<Arc<Token>>>>,
}

#[derive(Clone)]
pub struct BigTableClient {
    table_prefix: String,
    client: BigtableInternalClient<AuthChannel>,
    client_name: String,
    metrics: Option<Arc<KvMetrics>>,
}

#[async_trait]
impl KeyValueStoreWriter for BigTableClient {
    async fn save_objects(&mut self, objects: &[&Object]) -> Result<()> {
        let mut items = Vec::with_capacity(objects.len());
        for object in objects {
            let object_key = ObjectKey(object.id(), object.version());
            items.push((
                Self::raw_object_key(&object_key)?,
                vec![(DEFAULT_COLUMN_QUALIFIER, bcs::to_bytes(object)?)],
            ));
        }
        self.multi_set(OBJECTS_TABLE, items).await
    }

    async fn save_transactions(&mut self, transactions: &[TransactionData]) -> Result<()> {
        let mut items = Vec::with_capacity(transactions.len());
        for transaction in transactions {
            let cells = vec![
                (
                    TRANSACTION_COLUMN_QUALIFIER,
                    bcs::to_bytes(&transaction.transaction)?,
                ),
                (
                    EFFECTS_COLUMN_QUALIFIER,
                    bcs::to_bytes(&transaction.effects)?,
                ),
                (EVENTS_COLUMN_QUALIFIER, bcs::to_bytes(&transaction.events)?),
                (
                    TIMESTAMP_COLUMN_QUALIFIER,
                    bcs::to_bytes(&transaction.timestamp)?,
                ),
                (
                    CHECKPOINT_NUMBER_COLUMN_QUALIFIER,
                    bcs::to_bytes(&transaction.checkpoint_number)?,
                ),
            ];
            items.push((transaction.transaction.digest().inner().to_vec(), cells));
        }
        self.multi_set(TRANSACTIONS_TABLE, items).await
    }

    async fn save_checkpoint(&mut self, checkpoint: &CheckpointData) -> Result<()> {
        let summary = &checkpoint.checkpoint_summary.data();
        let contents = &checkpoint.checkpoint_contents;
        let signatures = &checkpoint.checkpoint_summary.auth_sig();
        let key = summary.sequence_number.to_be_bytes().to_vec();
        let cells = vec![
            (CHECKPOINT_SUMMARY_COLUMN_QUALIFIER, bcs::to_bytes(summary)?),
            (
                CHECKPOINT_SIGNATURES_COLUMN_QUALIFIER,
                bcs::to_bytes(signatures)?,
            ),
            (
                CHECKPOINT_CONTENTS_COLUMN_QUALIFIER,
                bcs::to_bytes(contents)?,
            ),
        ];
        self.multi_set(CHECKPOINTS_TABLE, [(key.clone(), cells)])
            .await?;
        self.multi_set(
            CHECKPOINTS_BY_DIGEST_TABLE,
            [(
                checkpoint.checkpoint_summary.digest().inner().to_vec(),
                vec![(DEFAULT_COLUMN_QUALIFIER, key)],
            )],
        )
        .await
    }

    async fn save_watermark(&mut self, watermark: CheckpointSequenceNumber) -> Result<()> {
        let key = watermark.to_be_bytes().to_vec();
        self.multi_set(
            WATERMARK_TABLE,
            [(key, vec![(DEFAULT_COLUMN_QUALIFIER, vec![])])],
        )
        .await
    }
}

#[async_trait]
impl KeyValueStoreReader for BigTableClient {
    async fn get_objects(&mut self, object_keys: &[ObjectKey]) -> Result<Vec<Object>> {
        let keys: Result<_, _> = object_keys.iter().map(Self::raw_object_key).collect();
        let mut objects = vec![];
        for row in self.multi_get(OBJECTS_TABLE, keys?).await? {
            for (_, value) in row {
                objects.push(bcs::from_bytes(&value)?);
            }
        }
        Ok(objects)
    }

    async fn get_transactions(
        &mut self,
        transactions: &[TransactionDigest],
    ) -> Result<Vec<TransactionData>> {
        let keys = transactions.iter().map(|tx| tx.inner().to_vec()).collect();
        let mut result = vec![];
        for row in self.multi_get(TRANSACTIONS_TABLE, keys).await? {
            let mut transaction = None;
            let mut effects = None;
            let mut events = None;
            let mut timestamp = 0;
            let mut checkpoint_number = 0;

            for (column, value) in row {
                match std::str::from_utf8(&column)? {
                    TRANSACTION_COLUMN_QUALIFIER => transaction = Some(bcs::from_bytes(&value)?),
                    EFFECTS_COLUMN_QUALIFIER => effects = Some(bcs::from_bytes(&value)?),
                    EVENTS_COLUMN_QUALIFIER => events = Some(bcs::from_bytes(&value)?),
                    TIMESTAMP_COLUMN_QUALIFIER => timestamp = bcs::from_bytes(&value)?,
                    CHECKPOINT_NUMBER_COLUMN_QUALIFIER => {
                        checkpoint_number = bcs::from_bytes(&value)?
                    }
                    _ => error!("unexpected column {:?} in transactions table", column),
                }
            }
            result.push(TransactionData {
                transaction: transaction.ok_or_else(|| anyhow!("transaction field is missing"))?,
                effects: effects.ok_or_else(|| anyhow!("effects field is missing"))?,
                events: events.ok_or_else(|| anyhow!("events field is missing"))?,
                timestamp,
                checkpoint_number,
            })
        }
        Ok(result)
    }

    async fn get_checkpoints(
        &mut self,
        sequence_numbers: &[CheckpointSequenceNumber],
    ) -> Result<Vec<Checkpoint>> {
        let keys = sequence_numbers
            .iter()
            .map(|sq| sq.to_be_bytes().to_vec())
            .collect();
        let mut checkpoints = vec![];
        for row in self.multi_get(CHECKPOINTS_TABLE, keys).await? {
            let mut summary = None;
            let mut contents = None;
            let mut signatures = None;
            for (column, value) in row {
                match std::str::from_utf8(&column)? {
                    CHECKPOINT_SUMMARY_COLUMN_QUALIFIER => summary = Some(bcs::from_bytes(&value)?),
                    CHECKPOINT_CONTENTS_COLUMN_QUALIFIER => {
                        contents = Some(bcs::from_bytes(&value)?)
                    }
                    CHECKPOINT_SIGNATURES_COLUMN_QUALIFIER => {
                        signatures = Some(bcs::from_bytes(&value)?)
                    }
                    _ => error!("unexpected column {:?} in checkpoints table", column),
                }
            }
            let checkpoint = Checkpoint {
                summary: summary.ok_or_else(|| anyhow!("summary field is missing"))?,
                contents: contents.ok_or_else(|| anyhow!("contents field is missing"))?,
                signatures: signatures.ok_or_else(|| anyhow!("signatures field is missing"))?,
            };
            checkpoints.push(checkpoint);
        }
        Ok(checkpoints)
    }

    async fn get_checkpoint_by_digest(
        &mut self,
        digest: CheckpointDigest,
    ) -> Result<Option<Checkpoint>> {
        let key = digest.inner().to_vec();
        let mut response = self
            .multi_get(CHECKPOINTS_BY_DIGEST_TABLE, vec![key])
            .await?;
        if let Some(row) = response.pop() {
            if let Some((_, value)) = row.into_iter().next() {
                let sequence_number = u64::from_be_bytes(value.as_slice().try_into()?);
                if let Some(chk) = self.get_checkpoints(&[sequence_number]).await?.pop() {
                    return Ok(Some(chk));
                }
            }
        }
        Ok(None)
    }

    async fn get_latest_checkpoint(&mut self) -> Result<CheckpointSequenceNumber> {
        let upper_limit = u64::MAX.to_be_bytes().to_vec();
        match self
            .reversed_scan(WATERMARK_TABLE, upper_limit)
            .await?
            .pop()
        {
            Some((key_bytes, _)) => Ok(u64::from_be_bytes(key_bytes.as_slice().try_into()?)),
            None => Ok(0),
        }
    }

    async fn get_latest_object(&mut self, object_id: &ObjectID) -> Result<Option<Object>> {
        let upper_limit = Self::raw_object_key(&ObjectKey::max_for_id(object_id))?;
        if let Some((_, row)) = self.reversed_scan(OBJECTS_TABLE, upper_limit).await?.pop() {
            if let Some((_, value)) = row.into_iter().next() {
                return Ok(Some(bcs::from_bytes(&value)?));
            }
        }
        Ok(None)
    }
}

impl BigTableClient {
    pub async fn new_local(instance_id: String) -> Result<Self> {
        let emulator_host = std::env::var("BIGTABLE_EMULATOR_HOST")?;
        let auth_channel = AuthChannel {
            channel: Channel::from_shared(format!("http://{emulator_host}"))?.connect_lazy(),
            policy: "https://www.googleapis.com/auth/bigtable.data".to_string(),
            token_provider: None,
            token: Arc::new(RwLock::new(None)),
        };
        Ok(Self {
            table_prefix: format!("projects/emulator/instances/{}/tables/", instance_id),
            client: BigtableInternalClient::new(auth_channel),
            client_name: "local".to_string(),
            metrics: None,
        })
    }

    pub async fn new_remote(
        instance_id: String,
        is_read_only: bool,
        timeout: Option<Duration>,
        client_name: String,
        registry: Option<&Registry>,
    ) -> Result<Self> {
        let policy = if is_read_only {
            "https://www.googleapis.com/auth/bigtable.data.readonly"
        } else {
            "https://www.googleapis.com/auth/bigtable.data"
        };
        let token_provider = gcp_auth::provider().await?;
        let tls_config = ClientTlsConfig::new()
            .ca_certificate(Certificate::from_pem(include_bytes!("./proto/google.pem")))
            .domain_name("bigtable.googleapis.com");
        let mut endpoint = Channel::from_static("https://bigtable.googleapis.com")
            .http2_keep_alive_interval(Duration::from_secs(60))
            .keep_alive_while_idle(true)
            .tls_config(tls_config)?;
        if let Some(timeout) = timeout {
            endpoint = endpoint.timeout(timeout);
        }
        let table_prefix = format!(
            "projects/{}/instances/{}/tables/",
            token_provider.project_id().await?,
            instance_id
        );
        let auth_channel = AuthChannel {
            channel: endpoint.connect_lazy(),
            policy: policy.to_string(),
            token_provider: Some(token_provider),
            token: Arc::new(RwLock::new(None)),
        };
        Ok(Self {
            table_prefix,
            client: BigtableInternalClient::new(auth_channel),
            client_name,
            metrics: registry.map(KvMetrics::new),
        })
    }

    pub async fn mutate_rows(
        &mut self,
        request: MutateRowsRequest,
    ) -> Result<Streaming<MutateRowsResponse>> {
        Ok(self.client.mutate_rows(request).await?.into_inner())
    }

    pub async fn read_rows(
        &mut self,
        request: ReadRowsRequest,
    ) -> Result<Vec<(Vec<u8>, Vec<(Vec<u8>, Vec<u8>)>)>> {
        let mut result = vec![];
        let mut response = self.client.read_rows(request).await?.into_inner();

        let mut row_key = None;
        let mut row = vec![];
        let mut cell_value = vec![];
        let mut cell_name = None;
        let mut timestamp = 0;

        while let Some(message) = response.message().await? {
            for mut chunk in message.chunks.into_iter() {
                // new row check
                if !chunk.row_key.is_empty() {
                    row_key = Some(chunk.row_key);
                }
                match chunk.qualifier {
                    // new cell started
                    Some(qualifier) => {
                        if let Some(cell_name) = cell_name {
                            row.push((cell_name, cell_value));
                            cell_value = vec![];
                        }
                        cell_name = Some(qualifier);
                        timestamp = chunk.timestamp_micros;
                        cell_value.append(&mut chunk.value);
                    }
                    None => {
                        if chunk.timestamp_micros == 0 {
                            cell_value.append(&mut chunk.value);
                        } else if chunk.timestamp_micros >= timestamp {
                            // newer version of cell is available
                            timestamp = chunk.timestamp_micros;
                            cell_value = chunk.value;
                        }
                    }
                }
                if chunk.row_status.is_some() {
                    if let Some(RowStatus::CommitRow(_)) = chunk.row_status {
                        if let Some(cell_name) = cell_name {
                            row.push((cell_name, cell_value));
                        }
                        if let Some(row_key) = row_key {
                            result.push((row_key, row));
                        }
                    }
                    row_key = None;
                    row = vec![];
                    cell_value = vec![];
                    cell_name = None;
                }
            }
        }
        Ok(result)
    }

    async fn multi_set(
        &mut self,
        table_name: &str,
        values: impl IntoIterator<Item = (Bytes, Vec<(&str, Bytes)>)> + std::marker::Send,
    ) -> Result<()> {
        for chunk in values.into_iter().collect::<Vec<_>>().chunks(50_000) {
            self.multi_set_internal(table_name, chunk.iter().cloned())
                .await?;
        }
        Ok(())
    }

    async fn multi_set_internal(
        &mut self,
        table_name: &str,
        values: impl IntoIterator<Item = (Bytes, Vec<(&str, Bytes)>)> + std::marker::Send,
    ) -> Result<()> {
        let mut entries = vec![];
        for (row_key, cells) in values {
            let mutations = cells
                .into_iter()
                .map(|(column_name, value)| Mutation {
                    mutation: Some(mutation::Mutation::SetCell(SetCell {
                        family_name: COLUMN_FAMILY_NAME.to_string(),
                        column_qualifier: column_name.to_owned().into_bytes(),
                        // The timestamp of the cell into which new data should be written.
                        // Use -1 for current Bigtable server time.
                        timestamp_micros: -1,
                        value,
                    })),
                })
                .collect();
            entries.push(Entry { row_key, mutations });
        }
        let request = MutateRowsRequest {
            table_name: format!("{}{}", self.table_prefix, table_name),
            entries,
            ..MutateRowsRequest::default()
        };
        let mut response = self.mutate_rows(request).await?;
        while let Some(part) = response.message().await? {
            for entry in part.entries {
                if let Some(status) = entry.status {
                    if status.code != 0 {
                        return Err(anyhow!(
                            "bigtable write failed {} {}",
                            status.code,
                            status.message
                        ));
                    }
                }
            }
        }
        Ok(())
    }

    pub async fn multi_get(
        &mut self,
        table_name: &str,
        keys: Vec<Vec<u8>>,
    ) -> Result<Vec<Vec<(Bytes, Bytes)>>> {
        let start_time = Instant::now();
        let num_keys_requested = keys.len();
        let result = self.multi_get_internal(table_name, keys).await;
        let elapsed_ms = start_time.elapsed().as_millis() as f64;
        let labels = [&self.client_name, table_name];
        match &self.metrics {
            None => result,
            Some(metrics) => match result {
                Err(e) => {
                    metrics.kv_get_errors.with_label_values(&labels).inc();
                    Err(e)
                }
                Ok(result) => {
                    metrics
                        .kv_get_batch_size
                        .with_label_values(&labels)
                        .observe(num_keys_requested as f64);
                    if num_keys_requested > result.len() {
                        metrics
                            .kv_get_not_found
                            .with_label_values(&labels)
                            .inc_by((num_keys_requested - result.len()) as u64);
                    }
                    metrics
                        .kv_get_success
                        .with_label_values(&labels)
                        .inc_by(result.len() as u64);

                    metrics
                        .kv_get_latency_ms
                        .with_label_values(&labels)
                        .observe(elapsed_ms);
                    if num_keys_requested > 0 {
                        metrics
                            .kv_get_latency_ms_per_key
                            .with_label_values(&labels)
                            .observe(elapsed_ms / num_keys_requested as f64);
                    }
                    Ok(result)
                }
            },
        }
    }

    pub async fn multi_get_internal(
        &mut self,
        table_name: &str,
        keys: Vec<Vec<u8>>,
    ) -> Result<Vec<Vec<(Bytes, Bytes)>>> {
        let request = ReadRowsRequest {
            table_name: format!("{}{}", self.table_prefix, table_name),
            rows_limit: keys.len() as i64,
            rows: Some(RowSet {
                row_keys: keys,
                row_ranges: vec![],
            }),
            ..ReadRowsRequest::default()
        };
        let mut result = vec![];
        for (_, cells) in self.read_rows(request).await? {
            result.push(cells);
        }
        Ok(result)
    }

    async fn reversed_scan(
        &mut self,
        table_name: &str,
        upper_limit: Bytes,
    ) -> Result<Vec<(Bytes, Vec<(Bytes, Bytes)>)>> {
        let start_time = Instant::now();
        let result = self.reversed_scan_internal(table_name, upper_limit).await;
        let elapsed_ms = start_time.elapsed().as_millis() as f64;
        let labels = [&self.client_name, table_name];
        match &self.metrics {
            Some(metrics) => match result {
                Ok(result) => {
                    metrics.kv_scan_success.with_label_values(&labels).inc();
                    if result.is_empty() {
                        metrics.kv_scan_not_found.with_label_values(&labels).inc();
                    }
                    metrics
                        .kv_scan_latency_ms
                        .with_label_values(&labels)
                        .observe(elapsed_ms);
                    Ok(result)
                }
                Err(e) => {
                    metrics.kv_scan_error.with_label_values(&labels).inc();
                    Err(e)
                }
            },
            None => result,
        }
    }

    async fn reversed_scan_internal(
        &mut self,
        table_name: &str,
        upper_limit: Bytes,
    ) -> Result<Vec<(Bytes, Vec<(Bytes, Bytes)>)>> {
        let range = RowRange {
            start_key: None,
            end_key: Some(EndKey::EndKeyClosed(upper_limit)),
        };
        let request = ReadRowsRequest {
            table_name: format!("{}{}", self.table_prefix, table_name),
            rows_limit: 1,
            rows: Some(RowSet {
                row_keys: vec![],
                row_ranges: vec![range],
            }),
            reversed: true,
            ..ReadRowsRequest::default()
        };
        self.read_rows(request).await
    }

    fn raw_object_key(object_key: &ObjectKey) -> Result<Vec<u8>> {
        let mut raw_key = object_key.0.to_vec();
        raw_key.extend(object_key.1.value().to_be_bytes());
        Ok(raw_key)
    }
}

impl Service<Request<BoxBody>> for AuthChannel {
    type Response = Response<BoxBody>;
    type Error = Box<dyn std::error::Error + Send + Sync>;
    #[allow(clippy::type_complexity)]
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.channel.poll_ready(cx).map_err(Into::into)
    }

    fn call(&mut self, mut request: Request<BoxBody>) -> Self::Future {
        let cloned_channel = self.channel.clone();
        let cloned_token = self.token.clone();
        let mut inner = std::mem::replace(&mut self.channel, cloned_channel);
        let policy = self.policy.clone();
        let token_provider = self.token_provider.clone();

        let mut auth_token = None;
        if token_provider.is_some() {
            let guard = self.token.read().expect("failed to acquire a read lock");
            if let Some(token) = &*guard {
                if !token.has_expired() {
                    auth_token = Some(token.clone());
                }
            }
        }

        Box::pin(async move {
            if let Some(ref provider) = token_provider {
                let token = match auth_token {
                    None => {
                        let new_token = provider.token(&[policy.as_ref()]).await?;
                        let mut guard = cloned_token.write().unwrap();
                        *guard = Some(new_token.clone());
                        new_token
                    }
                    Some(token) => token,
                };
                let token_string = token.as_str().parse::<String>()?;
                let header =
                    HeaderValue::from_str(format!("Bearer {}", token_string.as_str()).as_str())?;
                request.headers_mut().insert("authorization", header);
            }
            // enable reverse scan
            let header = HeaderValue::from_static("CAE=");
            request.headers_mut().insert("bigtable-features", header);
            Ok(inner.call(request).await?)
        })
    }
}