bigquery 0.10.0

Library provides a simple API for Google BigQuery based on the gRPC Storage Read/Write and v2 APIs
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
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
//! The crate's error type and the pieces it is built from.
//!
//! Every fallible call in this crate returns [`BigQueryError`]. BigQuery reports failures over
//! gRPC with a status code and a message only, with no `details()` payload, so the
//! classification here is by [`tonic::Code`](gcloud_sdk::tonic::Code), plus the message for the
//! rate-limit errors that BigQuery sends under non-retryable codes.

use crate::{BigQueryJobRef, BigQueryTablePlan, BigQueryTableRef};
use gcloud_sdk::tonic::Code;
use rsb_derive::Builder;
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;

/// The main error type for all BigQuery operations.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum BigQueryError {
    /// An error from the client side rather than from BigQuery: authentication, the token source,
    /// channel setup, etc., or a response from BigQuery that the crate cannot use.
    SystemError(BigQuerySystemError),
    /// An error reported by BigQuery that has no more specific variant.
    DatabaseError(BigQueryDatabaseError),
    /// The resource already exists (`ALREADY_EXISTS`), or a schema sync found the table
    /// changed since it read it (`FAILED_PRECONDITION` on its `if-match`).
    DataConflictError(BigQueryDataConflictError),
    /// The resource was not found (`NOT_FOUND`). A dataset or job looked up in the wrong
    /// `location` is reported this way too.
    DataNotFoundError(BigQueryDataNotFoundError),
    /// The caller passed parameters that cannot be sent at all.
    InvalidParametersError(BigQueryInvalidParametersError),
    /// A row or parameter that the crate could not write.
    SerializeError(BigQuerySerializationError),
    /// A value that the crate could not read into the target type.
    DeserializeError(BigQuerySerializationError),
    /// BigQuery rejected rows of one append; nothing of that batch was written.
    RowErrors(BigQueryRowErrors),
    /// The rows or the projection do not match the table's schema.
    SchemaMismatchError(BigQuerySchemaMismatchError),
    /// A write stream in a state that cannot take the call.
    WriteStreamError(BigQueryWriteStreamError),
    /// A job that finished with errors. Boxed, since its details would make every
    /// `BigQueryResult` larger.
    JobError(Box<BigQueryJobError>),
    /// A schema sync refused its plan and wrote nothing. Boxed, since it carries the plan.
    SchemaChangeRefused(Box<BigQuerySchemaChangeRefusedError>),
    /// A column list that [`from_type`](crate::BigQuerySchemaColumnsBuilder::from_type) could
    /// not infer, refused by `.plan()` and `.sync()` before any request.
    SchemaInferenceError(BigQuerySchemaInferenceError),
}

impl BigQueryError {
    /// Builds an [`InvalidParametersError`](BigQueryError::InvalidParametersError) naming the
    /// offending field and why it was rejected.
    pub(crate) fn invalid_parameters(field: impl Into<String>, error: impl Into<String>) -> Self {
        BigQueryError::InvalidParametersError(BigQueryInvalidParametersError::new(
            BigQueryInvalidParametersPublicDetails::new(field.into(), error.into()),
        ))
    }

    /// An [`InvalidParametersError`](BigQueryError::InvalidParametersError) for the field
    /// `table`, naming `table` and `what` about it the crate does not handle.
    pub(crate) fn unsupported_table(
        table: &gcloud_sdk::google::cloud::bigquery::v2::Table,
        what: String,
    ) -> Self {
        let id = table
            .table_reference
            .as_ref()
            .map(|reference| {
                format!(
                    "{}.{}.{}",
                    reference.project_id, reference.dataset_id, reference.table_id
                )
            })
            .unwrap_or_default();
        BigQueryError::invalid_parameters("table", format!("{id}: {what}"))
    }

    /// Builds a [`SystemError`](BigQueryError::SystemError) with a crate-defined `code`.
    pub(crate) fn system(code: &str, message: impl Into<String>) -> Self {
        BigQueryError::SystemError(BigQuerySystemError::new(
            BigQueryErrorPublicGenericDetails::new(code.to_string()),
            message.into(),
        ))
    }

    /// Builds a [`SystemError`](BigQueryError::SystemError) with the code `UNEXPECTED_RESPONSE`,
    /// for a response from BigQuery that the crate cannot use: a field it requires left out, or
    /// a form it did not ask for. It is not the caller's input that is wrong.
    pub(crate) fn unexpected_response(message: impl Into<String>) -> Self {
        Self::system("UNEXPECTED_RESPONSE", message)
    }

    /// Builds a [`DatabaseError`](BigQueryError::DatabaseError) under the gRPC `code`.
    pub(crate) fn database(code: Code, details: impl Into<String>, retry_possible: bool) -> Self {
        Self::database_with_code(&code_name(code), details, retry_possible)
    }

    /// Builds a [`DatabaseError`](BigQueryError::DatabaseError) under a crate-defined `code`,
    /// for a failure below gRPC.
    fn database_with_code(code: &str, details: impl Into<String>, retry_possible: bool) -> Self {
        BigQueryError::DatabaseError(BigQueryDatabaseError::new(
            BigQueryErrorPublicGenericDetails::new(code.to_string()),
            details.into(),
            retry_possible,
        ))
    }

    /// Builds a [`SchemaMismatchError`](BigQueryError::SchemaMismatchError) on `table`.
    pub(crate) fn schema_mismatch(
        code: &str,
        table: BigQueryTableRef,
        details: impl Into<String>,
    ) -> Self {
        BigQueryError::SchemaMismatchError(BigQuerySchemaMismatchError::new(
            BigQueryErrorPublicGenericDetails::new(code.to_string()),
            table,
            details.into(),
        ))
    }

    /// Builds a [`WriteStreamError`](BigQueryError::WriteStreamError) on the write stream named
    /// `stream`.
    pub(crate) fn write_stream(
        code: &str,
        stream: impl Into<String>,
        details: impl Into<String>,
    ) -> Self {
        BigQueryError::WriteStreamError(BigQueryWriteStreamError::new(
            BigQueryErrorPublicGenericDetails::new(code.to_string()),
            stream.into(),
            details.into(),
        ))
    }

    /// Whether this is a [`DatabaseError`](BigQueryError::DatabaseError) that BigQuery reported
    /// under the gRPC `code`.
    pub(crate) fn has_code(&self, code: Code) -> bool {
        matches!(self, BigQueryError::DatabaseError(err) if err.public.code == code_name(code))
    }

    /// Turns the `FAILED_PRECONDITION` that BigQuery sends for a write whose `if-match` etag is
    /// stale into a [`DataConflictError`](BigQueryError::DataConflictError). `stale` says what
    /// changed and what the caller should do; BigQuery's own message follows it. Any other
    /// error is returned as it is.
    pub(crate) fn on_stale_etag(self, stale: impl FnOnce() -> String) -> Self {
        match self {
            BigQueryError::DatabaseError(err)
                if err.public.code == code_name(Code::FailedPrecondition) =>
            {
                BigQueryError::DataConflictError(BigQueryDataConflictError::new(
                    err.public,
                    format!("{} {}", stale(), err.details),
                ))
            }
            other => other,
        }
    }

    /// Whether sending the same request again might succeed.
    pub fn retry_possible(&self) -> bool {
        matches!(self, BigQueryError::DatabaseError(err) if err.retry_possible)
    }
}

/// The name a gRPC code is reported under in [`BigQueryErrorPublicGenericDetails::code`].
pub(crate) fn code_name(code: Code) -> String {
    format!("{code:?}")
}

impl Display for BigQueryError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match *self {
            BigQueryError::SystemError(ref err) => err.fmt(f),
            BigQueryError::DatabaseError(ref err) => err.fmt(f),
            BigQueryError::DataConflictError(ref err) => err.fmt(f),
            BigQueryError::DataNotFoundError(ref err) => err.fmt(f),
            BigQueryError::InvalidParametersError(ref err) => err.fmt(f),
            BigQueryError::SerializeError(ref err) => write!(f, "Serialize error: {err}"),
            BigQueryError::DeserializeError(ref err) => write!(f, "Deserialize error: {err}"),
            BigQueryError::RowErrors(ref err) => err.fmt(f),
            BigQueryError::SchemaMismatchError(ref err) => err.fmt(f),
            BigQueryError::WriteStreamError(ref err) => err.fmt(f),
            BigQueryError::JobError(ref err) => err.fmt(f),
            BigQueryError::SchemaChangeRefused(ref err) => err.fmt(f),
            BigQueryError::SchemaInferenceError(ref err) => err.fmt(f),
        }
    }
}

impl Error for BigQueryError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match *self {
            BigQueryError::SystemError(ref err) => Some(err),
            BigQueryError::DatabaseError(ref err) => Some(err),
            BigQueryError::DataConflictError(ref err) => Some(err),
            BigQueryError::DataNotFoundError(ref err) => Some(err),
            BigQueryError::InvalidParametersError(ref err) => Some(err),
            BigQueryError::SerializeError(ref err) => Some(err),
            BigQueryError::DeserializeError(ref err) => Some(err),
            BigQueryError::RowErrors(ref err) => Some(err),
            BigQueryError::SchemaMismatchError(ref err) => Some(err),
            BigQueryError::WriteStreamError(ref err) => Some(err),
            BigQueryError::JobError(ref err) => Some(err.as_ref()),
            BigQueryError::SchemaChangeRefused(ref err) => Some(err.as_ref()),
            BigQueryError::SchemaInferenceError(ref err) => Some(err),
        }
    }
}

/// Details shared by most error kinds.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryErrorPublicGenericDetails {
    /// The gRPC status code name (`Unavailable`, `PermissionDenied`, ...) or, for failures below
    /// gRPC, a crate-defined code such as `CONNECTION_CLOSED`.
    pub code: String,
}

impl Display for BigQueryErrorPublicGenericDetails {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "Error code: {}", self.code)
    }
}

/// An error from the client side rather than from BigQuery.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQuerySystemError {
    /// Generic public details about the error.
    pub public: BigQueryErrorPublicGenericDetails,
    /// What failed.
    pub message: String,
}

impl Display for BigQuerySystemError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "BigQuery system/internal error: {}. {}",
            self.public, self.message
        )
    }
}

impl Error for BigQuerySystemError {}

/// An error reported by BigQuery.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryDatabaseError {
    /// Generic public details about the error.
    pub public: BigQueryErrorPublicGenericDetails,
    /// The status as BigQuery reported it.
    pub details: String,
    /// Whether sending the same request again might succeed.
    pub retry_possible: bool,
}

impl Display for BigQueryDatabaseError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "Database general error occurred: {}. {}. Retry possibility: {}",
            self.public, self.details, self.retry_possible
        )
    }
}

impl Error for BigQueryDatabaseError {}

/// The resource already exists, or changed since it was read.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryDataConflictError {
    /// Generic public details about the error.
    pub public: BigQueryErrorPublicGenericDetails,
    /// The status as BigQuery reported it.
    pub details: String,
}

impl Display for BigQueryDataConflictError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "Database conflict error occurred: {}. {}",
            self.public, self.details
        )
    }
}

impl Error for BigQueryDataConflictError {}

/// The resource was not found.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryDataNotFoundError {
    /// Generic public details about the error.
    pub public: BigQueryErrorPublicGenericDetails,
    /// The status as BigQuery reported it, which names the missing resource.
    pub data_detail_message: String,
}

impl Display for BigQueryDataNotFoundError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "Data not found error occurred: {}. {}",
            self.public, self.data_detail_message
        )
    }
}

impl Error for BigQueryDataNotFoundError {}

/// Which parameter was invalid and why.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryInvalidParametersPublicDetails {
    /// The name of the parameter.
    pub field: String,
    /// Why it was rejected.
    pub error: String,
}

impl Display for BigQueryInvalidParametersPublicDetails {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "Invalid parameters error: {}. {}",
            self.field, self.error
        )
    }
}

/// The caller passed parameters that cannot be sent.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryInvalidParametersError {
    /// Which parameter was invalid and why.
    pub public: BigQueryInvalidParametersPublicDetails,
}

impl Display for BigQueryInvalidParametersError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "{}", self.public)
    }
}

impl Error for BigQueryInvalidParametersError {}

/// A value the crate's codecs could not convert, in either direction.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQuerySerializationError {
    /// Generic public details; the code is the kind's name, such as `TYPE_MISMATCH`.
    pub public: BigQueryErrorPublicGenericDetails,
    /// What went wrong.
    pub kind: BigQueryCodecErrorKind,
    /// Read: the row's offset in its read stream, or its index in an inline result.
    /// Write: the row's index in write order. `None` for a parameter.
    pub row: Option<u64>,
    /// The field path, e.g. `recs[1].v`; empty for the row itself.
    pub path: String,
    /// The failure as the codec or the target type's serde impl reported it.
    pub message: String,
}

impl Display for BigQuerySerializationError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "{}", self.public)?;
        if let Some(row) = self.row {
            write!(f, ", row {row}")?;
        }
        if !self.path.is_empty() {
            write!(f, ", field `{}`", self.path)?;
        }
        write!(f, ": {}", self.message)
    }
}

impl Error for BigQuerySerializationError {}

/// The kinds of [`BigQuerySerializationError`].
#[non_exhaustive]
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum BigQueryCodecErrorKind {
    /// The Rust form is not one the column's type accepts, in either direction.
    TypeMismatch,
    /// Read: a NULL into a target that is not an `Option`.
    NullForNonOption,
    /// Write: `None` for a REQUIRED field.
    NullForRequired,
    /// Write: `None` inside a REPEATED field.
    NullArrayElement,
    /// The value is outside the BigQuery type or outside the Rust target.
    OutOfRange,
    /// A text form that does not parse, such as a malformed DATE.
    InvalidText,
    /// Write: a field or map key with no column in the table schema.
    UnknownField,
    /// Write: a REQUIRED field the row never wrote.
    MissingRequiredField,
    /// A column type the crate does not handle, such as TIMESTAMP with picosecond precision.
    UnsupportedType,
    /// Write: one encoded row is larger than the request budget.
    RowTooLarge,
    /// An error raised by the target type's own serde impl.
    Custom,
}

impl BigQueryCodecErrorKind {
    /// The kind's name as an error code, such as `TYPE_MISMATCH`.
    pub fn code(self) -> &'static str {
        match self {
            BigQueryCodecErrorKind::TypeMismatch => "TYPE_MISMATCH",
            BigQueryCodecErrorKind::NullForNonOption => "NULL_FOR_NON_OPTION",
            BigQueryCodecErrorKind::NullForRequired => "NULL_FOR_REQUIRED",
            BigQueryCodecErrorKind::NullArrayElement => "NULL_ARRAY_ELEMENT",
            BigQueryCodecErrorKind::OutOfRange => "OUT_OF_RANGE",
            BigQueryCodecErrorKind::InvalidText => "INVALID_TEXT",
            BigQueryCodecErrorKind::UnknownField => "UNKNOWN_FIELD",
            BigQueryCodecErrorKind::MissingRequiredField => "MISSING_REQUIRED_FIELD",
            BigQueryCodecErrorKind::UnsupportedType => "UNSUPPORTED_TYPE",
            BigQueryCodecErrorKind::RowTooLarge => "ROW_TOO_LARGE",
            BigQueryCodecErrorKind::Custom => "CUSTOM",
        }
    }
}

impl Display for BigQueryCodecErrorKind {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        f.write_str(self.code())
    }
}

/// The rows BigQuery rejected in one append request.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryRowErrors {
    /// Generic public details; the code is `ROW_ERRORS`.
    pub public: BigQueryErrorPublicGenericDetails,
    /// The batch's index in send order.
    pub batch_index: u64,
    /// The write-order index of the batch's first row.
    pub first_row: u64,
    /// The number of rows in the batch, none of which were written.
    pub row_count: u64,
    /// The rows BigQuery named.
    pub errors: Vec<BigQueryRowError>,
}

impl Display for BigQueryRowErrors {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}: batch {} (rows {} to {}) was rejected with {} row errors",
            self.public,
            self.batch_index,
            self.first_row,
            (self.first_row + self.row_count).saturating_sub(1),
            self.errors.len()
        )?;
        if let Some(first) = self.errors.first() {
            write!(f, ", first: row {}: {}", first.row, first.message)?;
        }
        Ok(())
    }
}

impl Error for BigQueryRowErrors {}

/// One row BigQuery rejected.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryRowError {
    /// The row's index in write order.
    pub row: u64,
    /// BigQuery's code for the failure.
    pub code: String,
    /// BigQuery's message for the failure.
    pub message: String,
}

/// The rows or the projection do not match the table's schema.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQuerySchemaMismatchError {
    /// Generic public details about the error.
    pub public: BigQueryErrorPublicGenericDetails,
    /// The table whose schema did not match.
    pub table: BigQueryTableRef,
    /// What did not match, as BigQuery or the crate reported it.
    pub details: String,
}

impl Display for BigQuerySchemaMismatchError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "Schema mismatch on {}: {}. {}",
            self.table, self.public, self.details
        )
    }
}

impl Error for BigQuerySchemaMismatchError {}

/// A write stream in a state that cannot take the call.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryWriteStreamError {
    /// Generic public details; the code is the `StorageError` name, such as `STREAM_FINALIZED`.
    pub public: BigQueryErrorPublicGenericDetails,
    /// The write stream's resource name.
    pub stream: String,
    /// The error as BigQuery reported it.
    pub details: String,
}

impl Display for BigQueryWriteStreamError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "Write stream error on {}: {}. {}",
            self.stream, self.public, self.details
        )
    }
}

impl Error for BigQueryWriteStreamError {}

/// A job that finished with errors.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryJobError {
    /// Generic public details about the error.
    pub public: BigQueryErrorPublicGenericDetails,
    /// The failed job, when BigQuery named one.
    pub job: Option<BigQueryJobRef>,
    /// The job's `error_result` as BigQuery reported it.
    pub details: String,
    /// Every error the job reported.
    pub errors: Vec<BigQueryJobErrorEntry>,
}

impl Display for BigQueryJobError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "Job error: {}", self.public)?;
        if let Some(job) = &self.job {
            write!(f, ", job {}:{}", job.project_id, job.job_id)?;
        }
        write!(f, ". {}", self.details)
    }
}

impl Error for BigQueryJobError {}

/// A schema sync's plan has changes that are impossible in place, and the declaration does not
/// opt in to recreating the table, or opts in with `recreate_if_empty()` and the table is not
/// empty. Nothing was written.
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct BigQuerySchemaChangeRefusedError {
    /// The plan, with its `impossible` changes and its `refusal`.
    pub plan: BigQueryTablePlan,
}

impl Display for BigQuerySchemaChangeRefusedError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "Schema sync of {} refused, nothing was written: {} changes are impossible in place",
            self.plan.table,
            self.plan.impossible.len()
        )?;
        if let Some(refusal) = &self.plan.refusal {
            write!(f, " and {refusal}")?;
        }
        Ok(())
    }
}

impl Error for BigQuerySchemaChangeRefusedError {}

/// A column list that [`from_type`](crate::BigQuerySchemaColumnsBuilder::from_type) could not
/// infer, or a [`with`](crate::BigQuerySchemaColumns::with) path that names no inferred column.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQuerySchemaInferenceError {
    /// Why the column has no inferred type.
    pub kind: BigQuerySchemaInferenceErrorKind,
    /// The column path, dotted for a RECORD field such as `shipping.city`; `None` when the row
    /// type itself has no columns to infer.
    pub path: Option<String>,
}

impl Display for BigQuerySchemaInferenceError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match &self.path {
            None => write!(
                f,
                "Schema inference error: {}; declare the columns with `fields([..])`",
                self.kind
            ),
            Some(path) if self.kind == BigQuerySchemaInferenceErrorKind::UnknownColumn => {
                write!(f, "Schema inference error on `{path}`: {}", self.kind)
            }
            Some(path) if self.kind == BigQuerySchemaInferenceErrorKind::UnresolvedAlias => write!(
                f,
                "Schema inference error on `{path}`: {}; declare the columns with `fields([..])`",
                self.kind
            ),
            Some(path) => write!(
                f,
                "Schema inference error on `{path}`: {}; declare its type with `.with(..)`",
                self.kind
            ),
        }
    }
}

impl Error for BigQuerySchemaInferenceError {}

/// The kinds of [`BigQuerySchemaInferenceError`].
#[non_exhaustive]
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum BigQuerySchemaInferenceErrorKind {
    /// The row type is not a struct with named fields.
    NotAStruct,
    /// A map, or a struct with `#[serde(flatten)]`, which does not list its keys.
    UnknownKeys,
    /// A value whose `Deserialize` takes whatever it is given, such as `serde_json::Value` or
    /// an untagged enum.
    DynamicValue,
    /// An enum with a variant that carries data; a unit-variant enum is a STRING.
    EnumWithData,
    /// A text field that reads both DATE and DATETIME text, as `jiff::civil::Date` and
    /// `jiff::civil::DateTime` both do.
    DateOrDateTime,
    /// An array of arrays, which BigQuery has no column type for.
    NestedArray,
    /// An array of `Option`s, whose `None` BigQuery cannot store.
    NullableArrayElement,
    /// `()`, a unit or tuple struct, a tuple, an array of anything but `u8`, or an enum with no
    /// variants.
    NoColumnType,
    /// A RANGE whose element is not DATE, DATETIME or TIMESTAMP.
    RangeElement,
    /// A struct that contains itself.
    Recursive,
    /// A name of a struct with `#[serde(alias)]` names that inference cannot tell apart as a
    /// field's own name or an alias, because no field value it can build is accepted. Each such
    /// name is refused at its own path.
    UnresolvedAlias,
    /// A `Deserialize` impl that asked for something else when it was run again.
    Inconsistent,
    /// A [`with`](crate::BigQuerySchemaColumns::with) path that names no inferred column.
    UnknownColumn,
}

impl Display for BigQuerySchemaInferenceErrorKind {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        f.write_str(match self {
            BigQuerySchemaInferenceErrorKind::NotAStruct => {
                "the row type is not a struct with named fields"
            }
            BigQuerySchemaInferenceErrorKind::UnknownKeys => {
                "a map or a `#[serde(flatten)]` struct does not list its keys"
            }
            BigQuerySchemaInferenceErrorKind::DynamicValue => {
                "a self-describing value, such as `serde_json::Value` or an untagged enum, has \
                 no fixed type"
            }
            BigQuerySchemaInferenceErrorKind::EnumWithData => {
                "an enum with a variant that carries data has no column type"
            }
            BigQuerySchemaInferenceErrorKind::DateOrDateTime => {
                "the field reads both DATE and DATETIME text, as `jiff::civil::Date` and \
                 `jiff::civil::DateTime` both do"
            }
            BigQuerySchemaInferenceErrorKind::NestedArray => "BigQuery has no array of arrays",
            BigQuerySchemaInferenceErrorKind::NullableArrayElement => {
                "a BigQuery array cannot hold NULL elements"
            }
            BigQuerySchemaInferenceErrorKind::NoColumnType => {
                "`()`, a unit or tuple struct, a tuple, an array of anything but `u8` or an enum \
                 with no variants has no column type"
            }
            BigQuerySchemaInferenceErrorKind::RangeElement => {
                "a RANGE element must be DATE, DATETIME or TIMESTAMP"
            }
            BigQuerySchemaInferenceErrorKind::Recursive => "the type contains itself",
            BigQuerySchemaInferenceErrorKind::UnresolvedAlias => {
                "inference cannot tell whether this name is a field's own name or a \
                 `#[serde(alias)]`"
            }
            BigQuerySchemaInferenceErrorKind::Inconsistent => {
                "the type's `Deserialize` asked for something else when it was run again"
            }
            BigQuerySchemaInferenceErrorKind::UnknownColumn => {
                "`.with(..)` names no inferred column"
            }
        })
    }
}

/// One error a job reported, as in the v2 `ErrorProto`.
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryJobErrorEntry {
    /// A short code, such as `invalidQuery`.
    pub reason: String,
    /// Where the error occurred, if BigQuery said.
    pub location: String,
    /// A description of the error.
    pub message: String,
}

impl From<gcloud_sdk::error::Error> for BigQueryError {
    fn from(error: gcloud_sdk::error::Error) -> Self {
        BigQueryError::SystemError(BigQuerySystemError::new(
            BigQueryErrorPublicGenericDetails::new(format!("{:?}", error.kind())),
            format!("GCloud system error: {error}"),
        ))
    }
}

impl From<gcloud_sdk::tonic::Status> for BigQueryError {
    fn from(status: gcloud_sdk::tonic::Status) -> Self {
        let code = status.code();
        match code {
            Code::AlreadyExists => {
                BigQueryError::DataConflictError(BigQueryDataConflictError::new(
                    BigQueryErrorPublicGenericDetails::new(code_name(code)),
                    format!("{status}"),
                ))
            }
            Code::NotFound => BigQueryError::DataNotFoundError(BigQueryDataNotFoundError::new(
                BigQueryErrorPublicGenericDetails::new(code_name(code)),
                format!("{status}"),
            )),
            Code::Aborted | Code::Unavailable | Code::ResourceExhausted | Code::Internal => {
                Self::database(code, format!("{status}"), true)
            }
            Code::PermissionDenied | Code::InvalidArgument if is_rate_limit(&status) => {
                Self::database(code, format!("{status}"), true)
            }
            Code::Unknown => check_hyper_errors(status),
            Code::Cancelled if transport_cancelled(&status) => {
                BigQueryError::database_with_code("CONNECTION_CLOSED", format!("{status}"), true)
            }
            _ => Self::database(code, format!("{status}"), false),
        }
    }
}

/// Whether `status` is BigQuery's per-table or per-project rate limit. BigQuery reports it as
/// `PermissionDenied: Exceeded rate limits: ...` for `PatchTable` and as
/// `InvalidArgument: Job exceeded rate limits: ...` for DDL, so the code alone says it is
/// permanent while waiting is what makes it pass. Quota errors without "rate limits" are daily
/// or per-request quotas that waiting a few seconds does not clear.
fn is_rate_limit(status: &gcloud_sdk::tonic::Status) -> bool {
    status
        .message()
        .to_ascii_lowercase()
        .contains("exceeded rate limits")
}

/// Whether hyper cancelled the request under `status` because its connection closed before
/// the request went out, as when a call is sent on a connection the server has just dropped.
/// BigQuery never saw such a request, so sending it again is safe. A `Cancelled` the server
/// sent carries no hyper error and stays permanent.
fn transport_cancelled(status: &gcloud_sdk::tonic::Status) -> bool {
    hyper_error(status).is_some_and(hyper::Error::is_canceled)
}

/// The hyper error under `status`, anywhere in its source chain: a status the channel
/// reports carries tonic's transport error first and hyper's below it.
fn hyper_error(status: &gcloud_sdk::tonic::Status) -> Option<&hyper::Error> {
    std::iter::successors(status.source(), |&source| source.source())
        .find_map(|source| source.downcast_ref::<hyper::Error>())
}

/// Classifies an `Unknown` status by the transport error underneath it. A connection that
/// closed, timed out or broke mid-body ("error reading a body from connection") is worth
/// retrying: a stream resumes from its offset and a unary call is sent again. A request hyper
/// refused to send, or a response it could not parse, is not.
fn check_hyper_errors(status: gcloud_sdk::tonic::Status) -> BigQueryError {
    let lost = |code: &str, err: &hyper::Error| {
        BigQueryError::database_with_code(code, format!("Hyper error: {err}"), true)
    };
    match hyper_error(&status) {
        Some(err) if err.is_closed() => lost("CONNECTION_CLOSED", err),
        Some(err) if err.is_timeout() => lost("CONNECTION_TIMEOUT", err),
        Some(err) if err.is_user() || err.is_parse() => {
            BigQueryError::database(status.code(), format!("Hyper error: {err}"), false)
        }
        Some(err) => lost("CONNECTION_LOST", err),
        None if status.message().contains("transport error") => {
            BigQueryError::database_with_code("CONNECTION_ERROR", format!("{status}"), true)
        }
        None => BigQueryError::database(status.code(), format!("{status}"), false),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use gcloud_sdk::tonic::Status;
    use std::future::Future;
    use std::pin::Pin;
    use std::task::{ready, Context, Poll};
    use tokio::io::{AsyncRead, AsyncWrite};

    fn classify(code: Code, message: &str) -> BigQueryError {
        BigQueryError::from(Status::new(code, message))
    }

    #[test]
    fn transient_codes_are_retryable() {
        for code in [
            Code::Unavailable,
            Code::ResourceExhausted,
            Code::Aborted,
            Code::Internal,
        ] {
            let err = classify(code, "backend error");
            assert!(err.retry_possible(), "{code:?} must be retryable: {err}");
        }
    }

    #[test]
    fn permanent_codes_are_not_retryable() {
        for code in [
            Code::InvalidArgument,
            Code::PermissionDenied,
            Code::Unauthenticated,
            Code::FailedPrecondition,
            Code::OutOfRange,
            Code::Unimplemented,
        ] {
            let err = classify(
                code,
                "Syntax error: Unexpected identifier \"SELEC\" at [1:1]",
            );
            assert!(
                !err.retry_possible(),
                "{code:?} must not be retryable: {err}"
            );
            assert!(matches!(err, BigQueryError::DatabaseError(_)), "{err:?}");
        }
    }

    #[test]
    fn patch_rate_limit_under_permission_denied_is_retryable() {
        let err = classify(
            Code::PermissionDenied,
            "Exceeded rate limits: too many table update operations for this table. For more \
             information, see https://cloud.google.com/bigquery/docs/troubleshoot-quotas",
        );
        assert!(err.retry_possible(), "{err}");
    }

    #[test]
    fn ddl_rate_limit_under_invalid_argument_is_retryable() {
        let err = classify(
            Code::InvalidArgument,
            "Job exceeded rate limits: Your table exceeded quota for table update operations. \
             For more information, see https://cloud.google.com/bigquery/docs/troubleshoot-quotas",
        );
        assert!(err.retry_possible(), "{err}");
    }

    #[test]
    fn rate_limit_error_keeps_the_reported_code() {
        match classify(Code::PermissionDenied, "Exceeded rate limits: too many") {
            BigQueryError::DatabaseError(err) => assert_eq!(err.public.code, "PermissionDenied"),
            other => panic!("expected a database error, got {other:?}"),
        }
    }

    #[test]
    fn not_found_is_data_not_found() {
        let err = classify(
            Code::NotFound,
            "Not found: Dataset latestbit:ds was not found in location US",
        );
        match err {
            BigQueryError::DataNotFoundError(err) => {
                assert!(err.data_detail_message.contains("latestbit:ds"), "{err}");
            }
            other => panic!("expected DataNotFoundError, got {other:?}"),
        }
    }

    #[test]
    fn already_exists_is_data_conflict() {
        let err = classify(Code::AlreadyExists, "Already Exists: Dataset latestbit:ds");
        assert!(
            matches!(err, BigQueryError::DataConflictError(_)),
            "{err:?}"
        );
        assert!(!err.retry_possible());
    }

    #[test]
    fn unknown_transport_error_is_retryable() {
        let err = classify(Code::Unknown, "transport error");
        assert!(err.retry_possible(), "{err}");
    }

    /// Lets hyper's client run over an in-memory pipe.
    struct Pipe(tokio::io::DuplexStream);

    impl hyper::rt::Read for Pipe {
        fn poll_read(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            mut buf: hyper::rt::ReadBufCursor<'_>,
        ) -> Poll<std::io::Result<()>> {
            let mut bytes = [0; 1024];
            let mut read = tokio::io::ReadBuf::new(&mut bytes);
            ready!(Pin::new(&mut self.0).poll_read(cx, &mut read))?;
            buf.put_slice(read.filled());
            Poll::Ready(Ok(()))
        }
    }

    impl hyper::rt::Write for Pipe {
        fn poll_write(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<std::io::Result<usize>> {
            Pin::new(&mut self.0).poll_write(cx, buf)
        }

        fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Pin::new(&mut self.0).poll_flush(cx)
        }

        fn poll_shutdown(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
        ) -> Poll<std::io::Result<()>> {
            Pin::new(&mut self.0).poll_shutdown(cx)
        }
    }

    #[derive(Clone)]
    struct TokioExecutor;

    impl<F> hyper::rt::Executor<F> for TokioExecutor
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        fn execute(&self, future: F) {
            tokio::spawn(future);
        }
    }

    /// The status tonic reports for a call sent on an HTTP/2 connection that closed before the
    /// call went out.
    async fn call_on_a_closed_connection() -> Status {
        let (client, _server) = tokio::io::duplex(64 * 1024);
        let (mut sender, connection) =
            hyper::client::conn::http2::handshake(TokioExecutor, Pipe(client))
                .await
                .expect("the handshake only writes the preface");
        drop(connection);
        let request = hyper::Request::new(String::new());
        let error = sender
            .send_request(request)
            .await
            .expect_err("the connection is gone");
        Status::from_error(Box::new(error))
    }

    #[tokio::test]
    async fn call_cancelled_by_a_closed_connection_is_retryable() {
        let status = call_on_a_closed_connection().await;
        assert_eq!(status.code(), Code::Cancelled);

        let err = BigQueryError::from(status);

        assert!(err.retry_possible(), "{err}");
    }

    /// tonic's transport error, which carries hyper's error as its source.
    #[derive(Debug)]
    struct TransportError(hyper::Error);

    impl Display for TransportError {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            f.write_str("transport error")
        }
    }

    impl Error for TransportError {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            Some(&self.0)
        }
    }

    /// The status tonic reports for `error` under its transport error.
    fn under_transport_error(error: hyper::Error) -> Status {
        let status = Status::from_error(Box::new(TransportError(error)));
        assert_eq!(status.code(), Code::Unknown);
        status
    }

    #[tokio::test]
    async fn a_closed_connection_under_the_transport_error_is_connection_closed() {
        let (client, _server) = tokio::io::duplex(64 * 1024);
        let (mut sender, connection) =
            hyper::client::conn::http2::handshake::<_, _, String>(TokioExecutor, Pipe(client))
                .await
                .expect("the handshake only writes the preface");
        drop(connection);
        let closed = sender.ready().await.expect_err("the connection is gone");

        match BigQueryError::from(under_transport_error(closed)) {
            BigQueryError::DatabaseError(err) => {
                assert_eq!(err.public.code, "CONNECTION_CLOSED");
                assert!(err.retry_possible);
            }
            other => panic!("expected a database error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn a_request_hyper_refused_under_the_transport_error_is_not_retryable() {
        let (client, server) = tokio::io::duplex(64 * 1024);
        tokio::spawn(async move {
            if let Ok(mut connection) = h2::server::handshake(server).await {
                while connection.accept().await.is_some() {}
            }
        });
        let (mut sender, connection) =
            hyper::client::conn::http2::handshake(TokioExecutor, Pipe(client))
                .await
                .expect("the handshake only writes the preface");
        tokio::spawn(connection);
        let request = hyper::Request::builder()
            .method(hyper::Method::CONNECT)
            .uri("http://example.com")
            .body(String::from("a CONNECT over HTTP/2 takes no body"))
            .expect("a valid request");
        let refused = sender
            .send_request(request)
            .await
            .expect_err("hyper refuses a CONNECT with a body");
        assert!(refused.is_user(), "{refused:?}");

        let err = BigQueryError::from(under_transport_error(refused));

        assert!(!err.retry_possible(), "{err}");
    }

    #[test]
    fn cancelled_by_the_server_is_not_retryable() {
        let err = classify(Code::Cancelled, "operation was canceled");
        assert!(!err.retry_possible(), "{err}");
    }

    #[test]
    fn unknown_without_cause_is_not_retryable() {
        let err = classify(Code::Unknown, "something odd");
        assert!(!err.retry_possible(), "{err}");
    }
}