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
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.

#![feature(box_patterns)]
#![feature(min_specialization)]

#[allow(unused_extern_crates)]
extern crate tikv_alloc;

mod lock;
mod timestamp;
mod types;
mod write;

use std::io;

pub use lock::{Lock, LockType};
pub use timestamp::{TimeStamp, TsSet};
pub use types::{
    is_short_value, Key, KvPair, Mutation, MutationType, OldValue, OldValues, TxnExtra,
    TxnExtraScheduler, Value, WriteBatchFlags, SHORT_VALUE_MAX_LEN,
};
pub use write::{Write, WriteRef, WriteType};

use error_code::{self, ErrorCode, ErrorCodeExt};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum ErrorInner {
    #[error("{0}")]
    Io(#[from] io::Error),
    #[error("{0}")]
    Codec(#[from] tikv_util::codec::Error),
    #[error("bad format lock data")]
    BadFormatLock,
    #[error("bad format write data")]
    BadFormatWrite,
    #[error("key is locked (backoff or cleanup) {0:?}")]
    KeyIsLocked(kvproto::kvrpcpb::LockInfo),
}

impl ErrorInner {
    pub fn maybe_clone(&self) -> Option<ErrorInner> {
        match self {
            ErrorInner::Codec(e) => e.maybe_clone().map(ErrorInner::Codec),
            ErrorInner::BadFormatLock => Some(ErrorInner::BadFormatLock),
            ErrorInner::BadFormatWrite => Some(ErrorInner::BadFormatWrite),
            ErrorInner::KeyIsLocked(info) => Some(ErrorInner::KeyIsLocked(info.clone())),
            ErrorInner::Io(_) => None,
        }
    }
}

#[derive(Debug, Error)]
#[error(transparent)]
pub struct Error(#[from] pub Box<ErrorInner>);

impl Error {
    pub fn maybe_clone(&self) -> Option<Error> {
        self.0.maybe_clone().map(Error::from)
    }
}

impl From<ErrorInner> for Error {
    #[inline]
    fn from(e: ErrorInner) -> Self {
        Error(Box::new(e))
    }
}

impl<T: Into<ErrorInner>> From<T> for Error {
    #[inline]
    default fn from(err: T) -> Self {
        let err = err.into();
        err.into()
    }
}

pub type Result<T> = std::result::Result<T, Error>;

impl ErrorCodeExt for Error {
    fn error_code(&self) -> ErrorCode {
        match self.0.as_ref() {
            ErrorInner::Io(_) => error_code::storage::IO,
            ErrorInner::Codec(e) => e.error_code(),
            ErrorInner::BadFormatLock => error_code::storage::BAD_FORMAT_LOCK,
            ErrorInner::BadFormatWrite => error_code::storage::BAD_FORMAT_WRITE,
            ErrorInner::KeyIsLocked(_) => error_code::storage::KEY_IS_LOCKED,
        }
    }
}