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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

use std::convert::{From, Into};
use std::error::Error as StdError;
use std::fmt::{Debug, Display, Formatter};
use std::{error, fmt, io, string};
use try_from::TryFrom;

use ::protocol::{TFieldIdentifier, TInputProtocol, TOutputProtocol, TStructIdentifier, TType};

// FIXME: should all my error structs impl error::Error as well?
// FIXME: should all fields in TransportError, ProtocolError and ApplicationError be optional?

/// Rift error type.
///
/// The error type defined here is used throughout this crate as well as in
/// all Thrift-compiler-generated Rust code. It falls into one of four
/// standard (i.e. defined by convention in Thrift implementations) categories.
/// These are:
///
/// 1. **Transport errors**: errors encountered while writing byes to the I/O
///    channel. These include "connection closed", "bind errors", etc.
/// 2. **Protocol errors**: errors encountered when processing a Thrift message
///    within the rift library. These include "exceeding size limits",
///    "unsupported protocol versions", etc.
/// 3. **Application errors**: errors encountered when Thrift-compiler-generated
///    'application' code encounters conditions that violate the spec. These
///    include "out-of-order messages", "missing required-field values", etc.
///    This category also functions as a catch-all: any error returned by
///    handler functions is automatically encoded as an `ApplicationError` and
///    returned to the caller.
/// 4. **User errors**: exception structs defined within the Thrift IDL.
///
/// With the exception of `Error::User`, each error variant encapsulates a
/// corresponding struct which encodes two required fields:
///
/// 1. kind: an enum indicating what kind of error was encountered
/// 2. message: string with human-readable error information
///
/// These two fields are encoded and sent over the wire to the remote. `kind`
/// is defined by convention while `message` is freeform. If none of the
/// enumerated error kinds seem suitable use the catch-all `Unknown`.
///
/// # Examples
///
/// Creating a `TransportError` explicitly.
///
/// Conversions are defined from `rift::TransportError`, `rift::ProtocolError`
/// and `rift::ApplicationError` to the corresponding `rift::Error` variant
/// (see `err2` below).
///
/// ```
/// use rift;
/// use rift::{TransportError, TransportErrorKind};
///
/// let err0: rift::Result<()> = Err(
///   rift::Error::Transport(
///     TransportError {
///       kind: TransportErrorKind::TimedOut,
///       message: format!("connection to server timed out")
///     }
///   )
/// );
///
/// let err1: rift::Result<()> = Err(
///   rift::Error::Transport(
///     TransportError::new(
///       TransportErrorKind::TimedOut,
///       format!("connection to server timed out")
///     )
///   )
/// );
///
/// let err2: rift::Result<()> = Err(
///   rift::Error::from(
///     TransportError::new(
///       TransportErrorKind::TimedOut,
///       format!("connection to server timed out")
///     )
///   )
/// );
///
/// ```
///
/// Creating an arbitrary error from a string
///
/// ```
/// use rift;
/// use rift::{ApplicationError, ApplicationErrorKind};
///
/// let err0: rift::Result<()> = Err(
///   rift::Error::from("This is an error")
/// );
///
/// // err0 is equivalent to...
///
/// let err1: rift::Result<()> = Err(
///   rift::Error::Application(
///     ApplicationError::new(
///       ApplicationErrorKind::Unknown,
///       format!("This is an error")
///     )
///   )
/// );
/// ```
///
/// Returning a user-defined (using the Thrift IDL) exception struct.
///
/// ```text
/// // Thrift IDL exception definition.
/// exception Xception {
///   1: i32 errorCode,
///   2: string message
/// }
/// ```
///
/// ```
/// use std::convert::From;
/// use std::error::Error;
/// use std::fmt;
/// use std::fmt::{Display, Formatter};
///
/// // auto-generated by the Thrift compiler
/// #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
/// pub struct Xception {
///   pub error_code: Option<i32>,
///   pub message: Option<String>,
/// }
///
/// // auto-generated by the Thrift compiler
/// impl Error for Xception {
///   fn description(&self) -> &str {
///     "remote service threw Xception"
///   }
/// }
///
/// // auto-generated by the Thrift compiler
/// impl From<Xception> for rift::Error {
///   fn from(e: Xception) -> Self {
///     rift::Error::User(Box::new(e))
///   }
/// }
///
/// // auto-generated by the Thrift compiler
/// impl Display for Xception {
///   fn fmt(&self, f: &mut Formatter) -> fmt::Result {
///     self.description().fmt(f)
///   }
/// }
///
/// // in user code...
/// let err: rift::Result<()> = Err(
///   rift::Error::from(Xception { error_code: Some(1), message: None })
/// );
///```
pub enum Error {
    /// Errors encountered while writing byes to the I/O channel.
    ///
    /// These include "connection closed", "bind errors", etc.
    Transport(TransportError),
    /// Errors encountered when processing a Thrift message within the rift
    /// library.
    ///
    /// These include "exceeding size limits", "unsupported protocol versions",
    /// etc.
    Protocol(ProtocolError),
    /// Errors encountered when Thrift-compiler-generated 'application' code
    /// encounters conditions that violate the spec.
    ///
    /// These include "out-of-order messages", "missing required-field values",
    /// etc. This variant also functions as a catch-all: any error returned by
    /// handler functions is automatically encoded as an `ApplicationError` and
    /// returned to the caller.
    Application(ApplicationError),
    /// Carries exception structs defined within the Thrift IDL.
    User(Box<error::Error + Sync + Send>),
}

impl Error {
    /// Read the wire representation of an application exception thrown by the
    /// remote Thrift endpoint into its corresponding rift `ApplicationError`
    /// representation.
    ///
    /// Application code should never call this method directly.
    pub fn read_application_error_from_in_protocol(i: &mut TInputProtocol) -> ::Result<ApplicationError> {
        let mut message = "general remote error".to_owned();
        let mut kind = ApplicationErrorKind::Unknown;

        try!(i.read_struct_begin());

        loop {
            let field_ident = try!(i.read_field_begin());

            if field_ident.field_type == TType::Stop {
                break;
            }

            let id = field_ident.id.expect("sender should always specify id for non-STOP field");

            match id {
                1 => {
                    let remote_message = try!(i.read_string());
                    try!(i.read_field_end());
                    message = remote_message;
                },
                2 => {
                    let remote_type_as_int = try!(i.read_i32());
                    let remote_kind: ApplicationErrorKind = TryFrom::try_from(remote_type_as_int).unwrap_or(ApplicationErrorKind::Unknown);
                    try!(i.read_field_end());
                    kind = remote_kind;
                },
                _ => {
                    try!(i.skip(field_ident.field_type));
                },
            }
        }

        try!(i.read_struct_end());

        Ok(ApplicationError { kind: kind, message: message })
    }

    /// Write an `ApplicationError` into its cross-platform wire representation.
    ///
    /// Application code should never call this method directly.
    pub fn write_application_error_to_out_protocol(e: &ApplicationError, o: &mut TOutputProtocol) -> ::Result<()> {
        try!(o.write_struct_begin(&TStructIdentifier { name: "TApplicationException".to_owned() }));

        let message_field = TFieldIdentifier::new("message", TType::String, 1);
        let type_field = TFieldIdentifier::new("type", TType::I32, 2);

        try!(o.write_field_begin(&message_field));
        try!(o.write_string(&e.message));
        try!(o.write_field_end());

        try!(o.write_field_begin(&type_field));
        try!(o.write_i32(e.kind as i32));
        try!(o.write_field_end());

        try!(o.write_field_stop());
        try!(o.write_struct_end());

        o.flush()
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Transport(ref e) => TransportError::description(&e),
            Error::Protocol(ref e) => ProtocolError::description(&e),
            Error::Application(ref e) => ApplicationError::description(&e),
            Error::User(ref e) => e.description(),
        }
    }
}

impl Debug for Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            Error::Transport(ref e) => Debug::fmt(&e, f),
            Error::Protocol(ref e) => Debug::fmt(&e, f),
            Error::Application(ref e) => Debug::fmt(&e, f),
            Error::User(ref e) => Debug::fmt(&e, f),
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            Error::Transport(ref e) => Display::fmt(&e, f),
            Error::Protocol(ref e) => Display::fmt(&e, f),
            Error::Application(ref e) => Display::fmt(&e, f),
            Error::User(ref e) => Display::fmt(&e, f),
        }
    }
}

impl From<String> for Error {
    fn from(s: String) -> Self {
       Error::Application(
           ApplicationError {
               kind: ApplicationErrorKind::Unknown,
               message: s,
           }
       )
    }
}

impl<'a> From<&'a str> for Error {
    fn from(s: &'a str) -> Self {
       Error::Application(
           ApplicationError {
               kind: ApplicationErrorKind::Unknown,
               message: String::from(s),
           }
       )
    }
}

impl From<TransportError> for Error {
    fn from(e: TransportError) -> Self {
       Error::Transport(e)
    }
}

impl From<ProtocolError> for Error {
    fn from(e: ProtocolError) -> Self {
       Error::Protocol(e)
    }
}

impl From<ApplicationError> for Error {
    fn from(e: ApplicationError) -> Self {
       Error::Application(e)
    }
}

/// Encodes information about I/O errors encountered within the rift library.
#[derive(Debug)]
pub struct TransportError {
    /// Specific I/O error kind.
    ///
    /// If a specific `TransportErrorKind` does not apply use
    /// `TransportErrorKind::Unknown`.
    pub kind: TransportErrorKind,
    /// Human-readable error message.
    pub message: String,
}

impl TransportError {
    /// Convenience constructor to create a new `TransportError` instance.
    pub fn new<S: Into<String>>(kind: TransportErrorKind, message: S) -> TransportError {
        TransportError { kind: kind, message: message.into() }
    }
}

/// A list specifying general categories of I/O error.
///
/// This list may grow, and it is not recommended to match against it.
#[derive(Clone, Copy, Eq, Debug, PartialEq)]
pub enum TransportErrorKind {
    /// Catch-all I/O error.
    Unknown      = 0,
    /// An I/O operation was attempted when the transport channel was not open.
    NotOpen      = 1,
    /// The transport channel cannot be opened because it was opened previously.
    AlreadyOpen  = 2,
    /// An I/O operation timed out.
    TimedOut     = 3,
    /// A read could not complete because no bytes were available.
    EndOfFile    = 4,
    /// An invalid (buffer/message) size was requested or received.
    NegativeSize = 5 ,
    /// Too large a buffer or message size was requested or received.
    SizeLimit    = 6,
}

impl TransportError {
    fn description(&self) -> &str {
        match self.kind {
            TransportErrorKind::Unknown => "transport error",
            TransportErrorKind::NotOpen => "not open",
            TransportErrorKind::AlreadyOpen => "already open",
            TransportErrorKind::TimedOut => "timed out",
            TransportErrorKind::EndOfFile => "end of file",
            TransportErrorKind::NegativeSize => "negative size message",
            TransportErrorKind::SizeLimit => "message too long",
        }
    }
}

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

impl TryFrom<i32> for TransportErrorKind {
    type Err = Error;
    fn try_from(from: i32) -> Result<Self, Self::Err> {
        match from {
            0 => Ok(TransportErrorKind::Unknown),
            1 => Ok(TransportErrorKind::NotOpen),
            2 => Ok(TransportErrorKind::AlreadyOpen),
            3 => Ok(TransportErrorKind::TimedOut),
            4 => Ok(TransportErrorKind::EndOfFile),
            5 => Ok(TransportErrorKind::NegativeSize),
            6 => Ok(TransportErrorKind::SizeLimit),
            _ => Err(
                Error::Protocol(
                    ProtocolError {
                        kind: ProtocolErrorKind::Unknown,
                        message: format!("cannot convert {} to TransportErrorKind", from)
                    }
                )
            )
        }
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        match err.kind() {
            io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionRefused | io::ErrorKind::NotConnected => Error::Transport(
                TransportError {
                    kind: TransportErrorKind::NotOpen,
                    message: err.description().to_owned(),
                }
            ),
            io::ErrorKind::AlreadyExists => Error::Transport(
                TransportError {
                    kind: TransportErrorKind::AlreadyOpen,
                    message: err.description().to_owned(),
                }
            ),
            io::ErrorKind::TimedOut => Error::Transport(
                TransportError {
                    kind: TransportErrorKind::TimedOut,
                    message: err.description().to_owned(),
                }
            ),
            io::ErrorKind::UnexpectedEof => Error::Transport(
                TransportError {
                    kind: TransportErrorKind::EndOfFile,
                    message: err.description().to_owned(),
                }
            ),
            _ => Error::Transport(
                TransportError {
                    kind: TransportErrorKind::Unknown,
                    message: err.description().to_owned(), // FIXME: use io error's debug string
                }
            ),
        }
    }
}

impl From<string::FromUtf8Error> for Error {
    fn from(err: string::FromUtf8Error) -> Self {
        Error::Protocol(
            ProtocolError {
                kind: ProtocolErrorKind::InvalidData,
                message: err.description().to_owned(), // FIXME: use fmt::Error's debug string
            }
        )
    }
}

/// Encodes information about errors encountered within rift library code.
#[derive(Debug)]
pub struct ProtocolError {
    /// Specific Thrift protocol error kind.
    ///
    /// If a specific `ProtocolErrorKind` does not apply use
    /// `ProtocolErrorKind::Unknown`.
    pub kind: ProtocolErrorKind,
    /// Human-readable error message.
    pub message: String,
}

impl ProtocolError {
    /// Convenience constructor to create a new `ProtocolError` instance.
    pub fn new<S: Into<String>>(kind: ProtocolErrorKind, message: S) -> ProtocolError {
        ProtocolError { kind: kind, message: message.into() }
    }
}

/// A list specifying general categories of rift library error.
///
/// This list may grow, and it is not recommended to match against it.
#[derive(Clone, Copy, Eq, Debug, PartialEq)]
pub enum ProtocolErrorKind {
    /// Catch-all library error.
    Unknown        = 0,
    /// An invalid argument was supplied to a library function, or invalid data
    /// was received from the remote Thrift service endpoint.
    InvalidData    = 1,
    /// An invalid size was received in a protocol-encoding field.
    NegativeSize   = 2,
    /// A Thrift message or field was too long.
    SizeLimit      = 3,
    /// Unsupported or unknown Thrift protocol version.
    BadVersion     = 4,
    /// A thrift protocol type, server type, or field type is unsupported.
    NotImplemented = 5,
    /// Reached the maximum nested depth to which an unknown field or container
    /// value could be skipped.
    DepthLimit     = 6,
}

impl ProtocolError {
    fn description(&self) -> &str {
        match self.kind {
            ProtocolErrorKind::Unknown => "protocol error",
            ProtocolErrorKind::InvalidData => "bad data",
            ProtocolErrorKind::NegativeSize => "negative message size",
            ProtocolErrorKind::SizeLimit => "message too long",
            ProtocolErrorKind::BadVersion => "invalid thrift version",
            ProtocolErrorKind::NotImplemented => "not implemented",
            ProtocolErrorKind::DepthLimit => "maximum skip depth reached",
        }
    }
}

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

impl TryFrom<i32> for ProtocolErrorKind {
    type Err = Error;
    fn try_from(from: i32) -> Result<Self, Self::Err> {
        match from {
            0 => Ok(ProtocolErrorKind::Unknown),
            1 => Ok(ProtocolErrorKind::InvalidData),
            2 => Ok(ProtocolErrorKind::NegativeSize),
            3 => Ok(ProtocolErrorKind::SizeLimit),
            4 => Ok(ProtocolErrorKind::BadVersion),
            5 => Ok(ProtocolErrorKind::NotImplemented),
            6 => Ok(ProtocolErrorKind::DepthLimit),
            _ => Err(
                Error::Protocol(
                    ProtocolError {
                        kind: ProtocolErrorKind::Unknown,
                        message: format!("cannot convert {} to ProtocolErrorKind", from)
                    }
                )
            )
        }
    }
}

/// Encodes information about errors encountered within auto-generated code
/// or within the user-implemented service handlers.
#[derive(Debug)]
pub struct ApplicationError {
    /// Specific Thrift application error kind.
    ///
    /// If a specific `ApplicationErrorKind` does not apply use
    /// `ApplicationErrorKind::Unknown`.
    pub kind: ApplicationErrorKind,
    /// Human-readable error message.
    pub message: String,
}

impl ApplicationError {
    /// Convenience constructor to create a new `ApplicationError` instance.
    pub fn new<S: Into<String>>(kind: ApplicationErrorKind, message: S) -> ApplicationError {
        ApplicationError { kind: kind, message: message.into() }
    }
}

/// A list specifying general categories of application error.
///
/// This list may grow, and it is not recommended to match against it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ApplicationErrorKind {
    /// Catch-all application error.
    Unknown               = 0,
    /// Service call made to/for an unknown service method.
    UnknownMethod         = 1,
    /// Received an unknown Thrift message type. That is, not one of the
    /// variants specified in `rift::protocol::TMessageType`.
    InvalidMessageType    = 2,
    /// Incoming Thrift reply does not specify the correct method name for the
    /// service call it's replying to.
    WrongMethodName       = 3,
    /// Auto-generated code received an out-of-order Thrift message.
    BadSequenceId         = 4,
    MissingResult         = 5,
    /// Auto-generated code failed unexpectedly.
    InternalError         = 6,
    /// Generic Thrift protocol error. When possible use `ProtocolError` with
    /// a specific `ProtocolErrorKind` instead.
    ProtocolError         = 7,
    /// Unknown. Only for compatibility with existing Thrift implementations.
    InvalidTransform      = 8, // ??
    /// Remote Thrift service endpoint requested, or is using, an unsupported
    /// wire encoding.
    InvalidProtocol       = 9, // ??
    /// Remote Thrift service endpoint requested, or is using, an unsupported
    /// auto-generated client type.
    UnsupportedClientType = 10, // ??
}

impl ApplicationError {
    fn description(&self) -> &str {
        match self.kind {
            ApplicationErrorKind::Unknown => "service error",
            ApplicationErrorKind::UnknownMethod => "unknown service method",
            ApplicationErrorKind::InvalidMessageType => "wrong message type received",
            ApplicationErrorKind::WrongMethodName => "unknown method reply received",
            ApplicationErrorKind::BadSequenceId => "out of order sequence id",
            ApplicationErrorKind::MissingResult => "missing method result",
            ApplicationErrorKind::InternalError => "remote service threw exception",
            ApplicationErrorKind::ProtocolError => "protocol error",
            ApplicationErrorKind::InvalidTransform => "invalid transform",
            ApplicationErrorKind::InvalidProtocol => "invalid protocol requested",
            ApplicationErrorKind::UnsupportedClientType => "unsupported protocol client",
        }
    }
}

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

impl TryFrom<i32> for ApplicationErrorKind {
    type Err = Error;
    fn try_from(from: i32) -> Result<Self, Self::Err> {
        match from {
            0 => Ok(ApplicationErrorKind::Unknown),
            1 => Ok(ApplicationErrorKind::UnknownMethod),
            2 => Ok(ApplicationErrorKind::InvalidMessageType),
            3 => Ok(ApplicationErrorKind::WrongMethodName),
            4 => Ok(ApplicationErrorKind::BadSequenceId),
            5 => Ok(ApplicationErrorKind::MissingResult),
            6 => Ok(ApplicationErrorKind::InternalError),
            7 => Ok(ApplicationErrorKind::ProtocolError),
            8 => Ok(ApplicationErrorKind::InvalidTransform),
            9 => Ok(ApplicationErrorKind::InvalidProtocol),
            10 => Ok(ApplicationErrorKind::UnsupportedClientType),
            _ => Err(
                Error::Application(
                    ApplicationError {
                        kind: ApplicationErrorKind::Unknown,
                        message: format!("cannot convert {} to ApplicationErrorKind", from)
                    }
                )
            )
        }
    }
}