|
| 1 | +use super::status_code::StatusCode; |
| 2 | +use super::Status; |
| 3 | + |
| 4 | +/// Represents a gRPC status on the server. |
| 5 | +/// |
| 6 | +/// This is a separate type from `Status` to prevent accidental conversion and |
| 7 | +/// leaking of sensitive information from the server to the client. |
| 8 | +#[derive(Debug, Clone)] |
| 9 | +pub struct ServerStatus(Status); |
| 10 | + |
| 11 | +impl std::ops::Deref for ServerStatus { |
| 12 | + type Target = Status; |
| 13 | + |
| 14 | + fn deref(&self) -> &Self::Target { |
| 15 | + &self.0 |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +impl ServerStatus { |
| 20 | + /// Create a new `ServerStatus` with the given code and message. |
| 21 | + pub fn new(code: StatusCode, message: impl Into<String>) -> Self { |
| 22 | + ServerStatus(Status::new(code, message)) |
| 23 | + } |
| 24 | + |
| 25 | + /// Create a new `ServerStatus` from a `Status`. |
| 26 | + pub fn from_status(status: Status) -> Self { |
| 27 | + ServerStatus(status) |
| 28 | + } |
| 29 | + |
| 30 | + /// Converts the `ServerStatus` to a `Status` for client responses. |
| 31 | + pub(crate) fn into_status(self) -> Status { |
| 32 | + self.0 |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +#[cfg(test)] |
| 37 | +mod tests { |
| 38 | + use super::*; |
| 39 | + |
| 40 | + #[test] |
| 41 | + fn test_server_status_new() { |
| 42 | + let status = ServerStatus::new(StatusCode::Ok, "ok"); |
| 43 | + assert_eq!(status.code(), StatusCode::Ok); |
| 44 | + assert_eq!(status.message(), "ok"); |
| 45 | + } |
| 46 | + |
| 47 | + #[test] |
| 48 | + fn test_server_status_deref() { |
| 49 | + let status = ServerStatus::new(StatusCode::Ok, "ok"); |
| 50 | + assert_eq!(status.code(), StatusCode::Ok); |
| 51 | + } |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn test_server_status_from_status() { |
| 55 | + let status = Status::new(StatusCode::Ok, "ok"); |
| 56 | + let server_status = ServerStatus::from_status(status); |
| 57 | + assert_eq!(server_status.code(), StatusCode::Ok); |
| 58 | + } |
| 59 | + |
| 60 | + #[test] |
| 61 | + fn test_server_status_into_status() { |
| 62 | + let server_status = ServerStatus::new(StatusCode::Ok, "ok"); |
| 63 | + let status = server_status.into_status(); |
| 64 | + assert_eq!(status.code(), StatusCode::Ok); |
| 65 | + } |
| 66 | +} |
0 commit comments