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
#[cfg(feature = "bigtable")]
use bigtable_rs::{
    bigtable::{BigTable, Error},
    google::bigtable::v2::{
        mutate_rows_request::Entry, MutateRowsRequest, Mutation, ReadRowsRequest, RowSet,
    },
};
#[cfg(feature = "bigtable")]
use std::collections::HashMap;
#[cfg(feature = "bigtable")]
use std::time::Duration;
use tokio::task::JoinHandle;
#[cfg(feature = "bigtable")]
use tonic::Code;
#[cfg(feature = "bigtable")]
use tracing::{error, info, warn};

#[cfg(feature = "bigtable")]
use crate::utils::backoff::obtain_next_interval;

#[cfg(feature = "bigtable")]
fn process_bt_status(
    status: tonic::Status,
    retry_limit: &usize,
    mut retry_count: usize,
    task_table_name: &str,
) -> usize {
    match status.code() {
        // Do nothing.
        Code::NotFound | Code::Ok | Code::OutOfRange => {}
        Code::ResourceExhausted => {
            warn!("BigTable resources are currently exhausted. Let's wait");
        }
        Code::Unknown => {
            error!(
                "There was an issue ingesting {} data to BigTable. {:?}",
                task_table_name, status
            );
            retry_count += 1;
        }
        Code::Cancelled => {
            warn!("BigTable request cancelled on our side. Trying again");
        }
        Code::InvalidArgument => {
            error!(
                "Invalid Argument for ingestion {} data to BigTable. {:?}",
                task_table_name, status
            );
            retry_count = retry_limit.clone();
        }
        Code::DeadlineExceeded => {
            warn!(
                "BigTable DeadlineExceeded. Let's wait; Data ingestion \
                                    might be too overwhelming at the moment."
            );
        }
        Code::AlreadyExists => {
            error!(
                "Row/s already exists for {} data. {:?}",
                task_table_name, status
            );
            retry_count = retry_limit.clone();
        }
        Code::PermissionDenied => {
            error!(
                "Invalid Permissions for ingesting {} data to \
                                    BigTable. {:?}",
                task_table_name, status
            );
            retry_count = retry_limit.clone();
        }
        Code::FailedPrecondition => {
            warn!("BigTable failed precondition. Let's wait and try again.");
        }
        Code::Aborted => {
            warn!("BigTable request aborted. Let's wait and try again.");
        }
        Code::Unimplemented => {
            error!(
                "Unimplemented API.. | table: {} | reason: {:?}",
                task_table_name, status
            );
            retry_count = retry_limit.clone();
        }
        Code::Internal => {
            error!(
                "BigTable internal error. Report!! | table: {} | \
                                    reason: {:?}",
                task_table_name, status
            );
            retry_count = retry_limit.clone();
        }
        Code::Unavailable => {
            warn!("BigTable resources are currently unavailable. Let's wait");
        }
        Code::DataLoss => {
            error!(
                "BigTable DataLoss while ingesting {} data to \
                                    BigTable. {:?}",
                task_table_name, status
            );
            retry_count = retry_limit.clone();
        }
        Code::Unauthenticated => {
            error!(
                "Invalid Authentication for ingesting {} data to \
                                    BigTable. {:?}",
                task_table_name, status
            );
            retry_count = retry_limit.clone();
        }
    }

    if retry_count.eq(retry_limit) {
        error!("Ditching this job.");
    }

    retry_count
}

#[cfg(feature = "bigtable")]
pub async fn ingest_entries(
    bt_client: &mut BigTable,
    table_name: String,
    table_prefix: String,
    mutations_per_entry: usize,
    entries: Vec<Entry>,
    retry_limit: &usize,
    retry_interval: &Duration,
) {
    let mut bt_tasks: Vec<_> = Vec::new();

    // Chunk by 100k mutations, via mutations_per_entry
    let chunks = entries.chunks(100000 / mutations_per_entry);
    let chunk_count = chunks.len();
    for (idx, chunk) in chunks.enumerate() {
        let mut chunk_rows = chunk.to_owned();
        let mut client = bt_client.clone();
        let mut retry_count = 0;
        let task_table_name = table_name.clone();
        let task_table_prefix = table_prefix.clone();
        let task_retry_limit = retry_limit.clone();
        let task_retry_interval = retry_interval.clone();
        let task_chunk_count = chunk_count.clone();

        info!("Writing to BT");
        info!("{:?}", task_table_name);

        bt_tasks.push(tokio::spawn(async move {
            loop {
                let push_result = client
                    .mutate_rows(MutateRowsRequest {
                        table_name: client.get_full_table_name(&task_table_name),
                        entries: chunk_rows.clone(),
                        ..MutateRowsRequest::default()
                    })
                    .await;

                if let Err(err) = push_result {
                    // error!("There was an issue ingesting {} data to BigTable. {:?}", task_table_name, err);

                    // Check varying types of errors and only increment retry_count if bad.
                    match err {
                        Error::AccessTokenError(error) => {
                            error!(
                                "AccessTokenError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count = task_retry_limit;
                        }
                        Error::CertificateError(error) => {
                            error!(
                                "CertificateError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count = task_retry_limit;
                        }
                        Error::GCPAuthError(error) => {
                            error!(
                                "GCPAuthError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count = task_retry_limit;
                        }
                        Error::IoError(error) => {
                            error!(
                                "IoError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count += 1;
                        }
                        Error::TransportError(tonic_tpt_err) => {
                            error!(
                                "TransportError while ingesting {} data to BigTable. {:?}",
                                task_table_name, tonic_tpt_err
                            );
                            retry_count += 1;
                        }
                        Error::ChunkError(error) => {
                            error!(
                                "ChunkError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count = task_retry_limit;
                        }
                        Error::RowWriteFailed => {
                            error!(
                                "RowWriteFailed while ingesting {} data to BigTable. {:?}",
                                task_table_name, err
                            );
                            retry_count += 1;
                        }
                        Error::RpcError(tonic_status) => {
                            retry_count = process_bt_status(
                                tonic_status,
                                &task_retry_limit,
                                task_chunk_count,
                                task_table_prefix.as_str(),
                            );
                        }
                        Error::TimeoutError(seconds) => {
                            error!(
                                "BigTable ingestion timed out after {} seconds. Trying again | \
                                table: {} | reason: {:?}",
                                seconds, task_table_name, err
                            );
                        }
                        // Do nothing, read-based errors.
                        Error::ObjectCorrupt(_) | Error::ObjectNotFound(_) | Error::RowNotFound => {
                        }
                    }

                    if &retry_count >= &task_retry_limit {
                        error!("Retry limit exceeded. Abandoning ship.");
                        break;
                    }

                    // Sleep for the backoff interval
                    let interval =
                        obtain_next_interval(&retry_count, &task_retry_limit, &task_retry_interval);

                    tokio::time::sleep(interval.unwrap()).await;
                } else {
                    // Push may not be successful, check if the GCP req is successful
                    if let Ok(mut gcp_result) = push_result {
                        // Since its successful, check if the Inner GCP msg is successful
                        match gcp_result.message().await {
                            Ok(msg) => {
                                // Ensure a message from GCP actually comes back
                                if let Some(gcp_res) = msg {
                                    // Iterate every entry im pushing
                                    // if one of the entries fail, we should add it to
                                    // a new collection to re-ingest again.
                                    let mut failed = false;
                                    let mut new_rows = Vec::new();
                                    let orig_size = gcp_res.entries.len();
                                    for entry in gcp_res.entries {
                                        match entry.status {
                                            Some(code) => {
                                                if code.code != 0 {
                                                    failed = true;
                                                    new_rows.push(
                                                        chunk_rows[entry.index as usize].clone(),
                                                    );
                                                }
                                            }
                                            None => {} // ???
                                        }
                                    }

                                    if failed {
                                        chunk_rows = new_rows.to_owned();

                                        warn!(
                                            "{}/{} entries failed to ingest. Trying again",
                                            chunk_rows.len(),
                                            orig_size
                                        );
                                    } else {
                                        match &task_table_prefix.is_empty() {
                                            true => {
                                                info!(
                                                    "{}/{} {} push complete!",
                                                    idx + 1,
                                                    &task_chunk_count,
                                                    &task_table_name
                                                );
                                            }
                                            _ => {
                                                info!(
                                                    "{}/{} {}/{} push complete!",
                                                    idx + 1,
                                                    &task_chunk_count,
                                                    &task_table_name,
                                                    &task_table_prefix
                                                );
                                            }
                                        }
                                        break;
                                    }
                                } else {
                                    error!("Empty message from GCP! Trying again...");
                                }
                            }
                            Err(tonic_status) => {
                                retry_count = process_bt_status(
                                    tonic_status,
                                    &task_retry_limit,
                                    task_chunk_count,
                                    task_table_prefix.as_str(),
                                );

                                if &retry_count >= &task_retry_limit {
                                    error!("Retry limit exceeded. Abandoning ship.");
                                    break;
                                }
                            }
                        }
                    } else {
                        error!("GCP Dispatch failed! Trying again...");
                    }
                }
            }
        }));
    }

    for task in bt_tasks {
        task.await.unwrap();
    }
}

#[cfg(feature = "bigtable")]
pub async fn check_entries(
    bt_client: &mut BigTable,
    table_name: String,
    table_prefix: String,
    mutations_per_entry: usize,
    entries: Vec<Entry>,
    retry_limit: &usize,
    retry_interval: &Duration,
) -> Vec<Entry> {
    let mut bt_tasks: Vec<JoinHandle<Vec<Entry>>> = Vec::new();
    let mut entries_to_push = vec![];

    // Chunk by 100k mutations, via mutations_per_entry
    let chunks = entries.chunks(100000 / mutations_per_entry);
    let chunk_count = chunks.len();
    for (_idx, chunk) in chunks.enumerate() {
        let chunk_rows = chunk.to_owned();
        let mut entry_map: HashMap<Vec<u8>, Vec<Mutation>> = HashMap::new();
        for entry in chunk_rows {
            entry_map.insert(entry.row_key, entry.mutations);
        }

        let mut client = bt_client.clone();
        let mut retry_count = 0;
        let task_table_name = table_name.clone();
        let task_table_prefix = table_prefix.clone();
        let task_retry_limit = retry_limit.clone();
        let task_retry_interval = retry_interval.clone();
        let task_chunk_count = chunk_count.clone();

        info!("Reading from BT");
        info!("{:?}", task_table_name);

        bt_tasks.push(tokio::spawn(async move {
            let mut cloned_entry_map = entry_map.clone();
            let mut entry_input = vec![];
            loop {
                let read_result = client
                    .read_rows(ReadRowsRequest {
                        table_name: client.get_full_table_name(&task_table_name),
                        rows: Some(RowSet {
                            row_keys: cloned_entry_map.keys().map(|key| key.clone()).collect(),
                            row_ranges: vec![],
                        }),
                        ..ReadRowsRequest::default()
                    })
                    .await;

                if let Err(err) = read_result {
                    // Check varying types of errors and only increment retry_count if bad.
                    match err {
                        Error::AccessTokenError(error) => {
                            error!(
                                "AccessTokenError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count = task_retry_limit;
                        }
                        Error::CertificateError(error) => {
                            error!(
                                "CertificateError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count = task_retry_limit;
                        }
                        Error::GCPAuthError(error) => {
                            error!(
                                "GCPAuthError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count = task_retry_limit;
                        }
                        Error::IoError(error) => {
                            error!(
                                "IoError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count += 1;
                        }
                        Error::TransportError(tonic_tpt_err) => {
                            error!(
                                "TransportError while ingesting {} data to BigTable. {:?}",
                                task_table_name, tonic_tpt_err
                            );
                            retry_count += 1;
                        }
                        Error::ChunkError(error) => {
                            error!(
                                "ChunkError for ingesting {} data to BigTable. {:?}",
                                task_table_name, error
                            );
                            retry_count = task_retry_limit;
                        }
                        Error::RowWriteFailed => {
                            error!(
                                "RowWriteFailed while ingesting {} data to BigTable. {:?}",
                                task_table_name, err
                            );
                            retry_count += 1;
                        }
                        Error::RpcError(tonic_status) => {
                            retry_count = process_bt_status(
                                tonic_status,
                                &task_retry_limit,
                                task_chunk_count,
                                task_table_prefix.as_str(),
                            );
                        }
                        Error::TimeoutError(seconds) => {
                            error!(
                                "BigTable ingestion timed out after {} seconds. Trying again | \
                                table: {} | reason: {:?}",
                                seconds, task_table_name, err
                            );
                        }
                        // Do nothing, read-based errors.
                        Error::ObjectCorrupt(_) | Error::ObjectNotFound(_) | Error::RowNotFound => {
                        }
                    }

                    if &retry_count >= &task_retry_limit {
                        error!("Retry limit exceeded. Abandoning ship.");
                        break;
                    }

                    // Sleep for the backoff interval
                    let interval =
                        obtain_next_interval(&retry_count, &task_retry_limit, &task_retry_interval);

                    tokio::time::sleep(interval.unwrap()).await;
                } else {
                    if let Ok(gcp_result) = read_result {
                        // We want to remove all the entries that have been found in BT
                        for (key, _cell_val) in gcp_result {
                            // let idx = rowkeys_to_check
                            cloned_entry_map.remove(&key);
                        }
                    }
                    // cloned_entry_map.clone().values().map()
                    entry_input = cloned_entry_map
                        .clone()
                        .iter()
                        .map(|(key, val)| Entry {
                            row_key: key.to_owned(),
                            mutations: val.to_owned(),
                        })
                        .collect();
                }
            }
            entry_input
        }));
    }

    // We want to append all the entries that are not in BT and try to add them in
    for task in bt_tasks {
        let ret = task.await;
        match ret {
            Ok(mut entries) => entries_to_push.append(&mut entries),
            Err(_) => error!("There was an error retrieving entries"),
        }
    }

    info!("There are {} transactions missing!", &entries_to_push.len());

    entries_to_push
}