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
pub use crate::codec::EncoderError;

use crate::frame::{self, GoAway, Reason, StreamId};
use crate::stream::StreamRef;

#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ConnectionError {
    #[error("Go away: {0}")]
    GoAway(Reason),
    #[error("Unknown stream id in {0} frame")]
    UnknownStream(&'static str),
    #[error("Encoder error: {0}")]
    Encoder(#[from] EncoderError),
    #[error("Decoder error: {0}")]
    Decoder(#[from] frame::FrameError),
    #[error("{0:?} is closed")]
    StreamClosed(StreamId),
    /// An invalid stream identifier was provided
    #[error("An invalid stream identifier was provided")]
    InvalidStreamId,
    #[error("Unexpected setting ack received")]
    UnexpectedSettingsAck,
    /// Missing pseudo header
    #[error("Missing pseudo header {0:?}")]
    MissingPseudo(&'static str),
    /// Missing pseudo header
    #[error("Unexpected pseudo header {0:?}")]
    UnexpectedPseudo(&'static str),
    /// Window update value is zero
    #[error("Window update value is zero")]
    ZeroWindowUpdateValue,
    #[error("Window value is overflowed")]
    WindowValueOverflow,
    /// Keep-alive timeout
    #[error("Keep-alive timeout")]
    KeepaliveTimeout,
}

impl ConnectionError {
    pub fn to_goaway(&self) -> GoAway {
        match self {
            ConnectionError::GoAway(reason) => GoAway::new(*reason),
            ConnectionError::Encoder(_) => {
                GoAway::new(Reason::PROTOCOL_ERROR).set_data("error during frame encoding")
            }
            ConnectionError::Decoder(_) => {
                GoAway::new(Reason::PROTOCOL_ERROR).set_data("error during frame decoding")
            }
            ConnectionError::MissingPseudo(s) => GoAway::new(Reason::PROTOCOL_ERROR)
                .set_data(format!("Missing pseudo header {:?}", s)),
            ConnectionError::UnexpectedPseudo(s) => GoAway::new(Reason::PROTOCOL_ERROR)
                .set_data(format!("Unexpected pseudo header {:?}", s)),
            ConnectionError::UnknownStream(_) => {
                GoAway::new(Reason::PROTOCOL_ERROR).set_data("unknown stream")
            }
            ConnectionError::InvalidStreamId => GoAway::new(Reason::PROTOCOL_ERROR)
                .set_data("An invalid stream identifier was provided"),
            ConnectionError::StreamClosed(s) => {
                GoAway::new(Reason::STREAM_CLOSED).set_data(format!("{:?} is closed", s))
            }
            ConnectionError::UnexpectedSettingsAck => {
                GoAway::new(Reason::PROTOCOL_ERROR).set_data("received unexpected settings ack")
            }
            ConnectionError::ZeroWindowUpdateValue => GoAway::new(Reason::PROTOCOL_ERROR)
                .set_data("zero value for window update frame is not allowed"),
            ConnectionError::WindowValueOverflow => GoAway::new(Reason::FLOW_CONTROL_ERROR)
                .set_data("updated value for window is overflowed"),
            ConnectionError::KeepaliveTimeout => {
                GoAway::new(Reason::NO_ERROR).set_data("keep-alive timeout")
            }
        }
    }
}

#[derive(Debug, Clone, thiserror::Error)]
#[error("Stream error: {kind:?}")]
pub(crate) struct StreamErrorInner {
    kind: StreamError,
    stream: StreamRef,
}

impl StreamErrorInner {
    pub(crate) fn new(stream: StreamRef, kind: StreamError) -> Self {
        Self { kind, stream }
    }

    pub(crate) fn into_inner(self) -> (StreamRef, StreamError) {
        (self.stream, self.kind)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
pub enum StreamError {
    #[error("Stream in idle state: {0}")]
    Idle(&'static str),
    #[error("Stream is closed")]
    Closed,
    #[error("Window value is overflowed")]
    WindowOverflowed,
    #[error("Zero value for window")]
    WindowZeroUpdateValue,
    #[error("Trailers headers without end of stream flags")]
    TrailersWithoutEos,
    #[error("Invalid content length")]
    InvalidContentLength,
    #[error("Payload length does not match content-length header")]
    WrongPayloadLength,
    #[error("Non-empty payload for HEAD response")]
    NonEmptyPayload,
    #[error("Stream has been reset with {0}")]
    Reset(Reason),
}

impl StreamError {
    #[inline]
    pub(crate) fn reason(&self) -> Reason {
        match self {
            StreamError::Idle(_) => Reason::PROTOCOL_ERROR,
            StreamError::Closed => Reason::STREAM_CLOSED,
            StreamError::WindowOverflowed => Reason::FLOW_CONTROL_ERROR,
            StreamError::WindowZeroUpdateValue => Reason::PROTOCOL_ERROR,
            StreamError::TrailersWithoutEos => Reason::PROTOCOL_ERROR,
            StreamError::InvalidContentLength => Reason::PROTOCOL_ERROR,
            StreamError::WrongPayloadLength => Reason::PROTOCOL_ERROR,
            StreamError::NonEmptyPayload => Reason::PROTOCOL_ERROR,
            StreamError::Reset(r) => *r,
        }
    }
}

/// Operation errors
#[derive(Debug, Clone, thiserror::Error)]
pub enum OperationError {
    #[error("{0:?}")]
    Stream(#[from] StreamError),

    #[error("{0}")]
    Connection(#[from] ConnectionError),

    /// Cannot process operation for idle stream
    #[error("Cannot process operation for idle stream")]
    Idle,

    /// Cannot process operation for stream in payload state
    #[error("Cannot process operation for stream in payload state")]
    Payload,

    // /// Ping timeout
    // #[error("Ping timeout")]
    // PingTimeout,
    /// Stream is closed
    #[error("Stream is closed {0:?}")]
    Closed(Option<Reason>),

    /// Stream has been reset from the peer
    #[error("Stream has been reset from the peer with {0}")]
    RemoteReset(Reason),

    /// Stream has been reset from local side
    #[error("Stream has been reset from local side with {0}")]
    LocalReset(Reason),

    /// The stream ID space is overflowed
    ///
    /// A new connection is needed.
    #[error("The stream ID space is overflowed")]
    OverflowedStreamId,

    /// Disconnected
    #[error("Connection is closed")]
    Disconnected,
}