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
//! Implementation of utilities for working with responses in `salvo` and `reqwest`.

use crate::prelude::*;

#[cfg(feature = "salvo")]
use salvo::http::HeaderValue;

#[cfg(feature = "salvo")]
use salvo::hyper::header::CONTENT_TYPE;

#[cfg(feature = "salvo")]
use salvo::oapi::{EndpointOutRegister, ToSchema};

#[cfg(feature = "salvo")]
use salvo::{Request, Response};

#[cfg(feature = "salvo")]
use salvo::Writer as ServerResponseWriter;

#[cfg(feature = "salvo")]
use salvo::fs::NamedFile;

#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
use serde::Serialize;

#[cfg(feature = "reqwest")]
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
use serde::de::DeserializeOwned;

/// Macro to define the function that called the response.
#[macro_export]
macro_rules! fn_name {
  () => {{
    fn f() {}
    fn type_name_of<T>(_: T) -> &'static str {
      std::any::type_name::<T>()
    }
    let name = type_name_of(f);
    
    // For `#[endpoint]` path can be shortened as follows:
    match name[..name.len() - 3].rsplit("::").nth(2) {
      Some(el) => el,
      None => &name[..name.len() - 3],
    }
  }};
}

/// Macro for automating `EndpointOutRegister` implementations (for simple types)
#[cfg(feature = "salvo")]
macro_rules! impl_oapi_endpoint_out {
  ($t:tt, $c:expr) => {
    impl EndpointOutRegister for $t {
      #[inline]
      fn register(components: &mut salvo::oapi::Components, operation: &mut salvo::oapi::Operation) {
        operation.responses.insert(
          "200",
          salvo::oapi::Response::new("Ok").add_content($c, String::to_schema(components)),
        );
      }
    }
  };
}

/// Macro for automating `EndpointOutRegister` implementations (for template types)
#[cfg(feature = "salvo")]
macro_rules! impl_oapi_endpoint_out_t {
  ($t:tt, $c:expr) => {
    impl<T> EndpointOutRegister for $t<T> {
      #[inline]
      fn register(components: &mut salvo::oapi::Components, operation: &mut salvo::oapi::Operation) {
        operation.responses.insert(
          "200",
          salvo::oapi::Response::new("Ok").add_content($c, String::to_schema(components)),
        );
      }
    }
  };
}

/// Sends 200 without data.
#[cfg(feature = "salvo")]
pub struct OK(pub &'static str);

#[cfg(feature = "salvo")]
impl_oapi_endpoint_out!(OK, "text/plain");

#[cfg(feature = "salvo")]
#[macro_export]
macro_rules! ok { () => { Ok(OK(cc_utils::fn_name!())) }; }

#[cfg(feature = "salvo")]
#[salvo::async_trait]
impl ServerResponseWriter for OK {
  async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
    res.status_code(StatusCode::OK);
    res.render("");
    log::debug!("[{}] => Received and sent result 200", self.0);
  }
}

/// Sends 200 and plain text.
#[cfg(feature = "salvo")]
#[derive(Debug)]
pub struct Plain(pub String, pub &'static str);

#[cfg(feature = "salvo")]
impl_oapi_endpoint_out!(Plain, "text/plain");

#[cfg(feature = "salvo")]
#[macro_export]
macro_rules! plain { ($e:expr) => { Ok(Plain($e, cc_utils::fn_name!())) }; }

#[cfg(feature = "salvo")]
#[salvo::async_trait]
impl ServerResponseWriter for Plain {
  async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
    res.status_code(StatusCode::OK);
    res.render(&self.0);
    log::debug!("[{}] => Received and sent result 200 with text: {}", self.1, self.0);
  }
}

/// Sends 200 and HTML.
#[cfg(feature = "salvo")]
#[derive(Debug)]
pub struct Html(pub String, pub &'static str);

#[cfg(feature = "salvo")]
impl_oapi_endpoint_out!(Html, "text/html");

#[cfg(feature = "salvo")]
#[macro_export]
macro_rules! html { ($e:expr) => { Ok(Html($e, cc_utils::fn_name!())) }; }

#[cfg(feature = "salvo")]
#[salvo::async_trait]
impl ServerResponseWriter for Html {
  async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
    res.status_code(StatusCode::OK);
    res.render(salvo::writing::Text::Html(&self.0));
    log::debug!("[{}] => Received and sent result 200 with HTML", self.1);
  }
}

/// Sends 200 and file.
#[cfg(feature = "salvo")]
#[derive(Debug)]
pub struct File(pub String, pub String, pub &'static str);

#[cfg(feature = "salvo")]
impl_oapi_endpoint_out!(File, "application/octet-stream");

/// File response.
///
/// Usage:
///
/// ```rust
/// use cc_utils::prelude::*;
/// use salvo::prelude::*;
///
/// pub async fn some_endpoint() -> MResult<File> {
///   file!("filepath", "Normal file name")
/// }
/// ```
#[cfg(feature = "salvo")]
#[macro_export]
macro_rules! file { ($e1:expr, $e2:expr) => { Ok(File($e1, $e2, cc_utils::fn_name!())) }; }

#[cfg(feature = "salvo")]
#[salvo::async_trait]
impl ServerResponseWriter for File {
  async fn write(self, req: &mut Request, _depot: &mut Depot, res: &mut Response) {
    res.status_code(StatusCode::OK);
    NamedFile::builder(&self.0).attached_name(&self.1).use_last_modified(true).send(req.headers(), res).await;
    log::debug!("[{}] => Received and sent result 200 with file {}", self.2, self.1);
  }
}

/// Sends 200 and JSON.
#[cfg(feature = "salvo")]
#[derive(Debug)]
pub struct Json<T>(pub T, pub &'static str);

#[cfg(feature = "salvo")]
impl_oapi_endpoint_out_t!(Json, "application/json");

#[cfg(feature = "salvo")]
#[macro_export]
macro_rules! json { ($e:expr) => { Ok(Json($e, cc_utils::fn_name!())) }; }

#[cfg(feature = "salvo")]
#[salvo::async_trait]
impl<T: Serialize + Send> ServerResponseWriter for Json<T> {
  async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
    res.status_code(StatusCode::OK);
    res.render(salvo::writing::Json(self.0));
    log::debug!("[{}] => Received and sent result 200 with JSON", self.1);
  }
}

/// Sends 200 and MsgPack.
#[cfg(feature = "salvo")]
#[derive(Debug)]
pub struct MsgPack<T>(pub T, pub &'static str);

#[cfg(feature = "salvo")]
impl_oapi_endpoint_out_t!(MsgPack, "application/msgpack");

#[cfg(feature = "salvo")]
#[macro_export]
macro_rules! msgpack { ($e:expr) => { Ok(MsgPack($e, cc_utils::fn_name!())) }; }

#[cfg(feature = "salvo")]
#[salvo::async_trait]
impl<T: Serialize + Send> ServerResponseWriter for MsgPack<T> {
  async fn write(self, req: &mut Request, depot: &mut Depot, res: &mut Response) {
    res.status_code(StatusCode::OK);
    match rmp_serde::to_vec(&self.0) {
      Ok(bytes) => {
        res.headers_mut().insert(CONTENT_TYPE, HeaderValue::from_static("application/msgpack; charset=utf-8"));
        log::debug!("[{}] => Sending bytes: {:?}", self.1, bytes);
        res.write_body(bytes).ok();
        log::debug!("[{}] => Received and sent result 200 with MsgPack", self.1);
      }
      Err(e) => {
        log::error!("[{}] => Failed to serialize data: {:?}", e, self.1);
        ErrorResponse::from("Failed to serialize data.").with_500().build().write(req, depot, res).await;
      }
    }
  }
}

#[cfg(feature = "reqwest")]
#[allow(async_fn_in_trait)]
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
pub trait MsgPackResponse {
  async fn msgpack<T: DeserializeOwned>(self) -> CResult<T>;
}

#[cfg(feature = "reqwest")]
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
impl MsgPackResponse for reqwest::Response {
  async fn msgpack<T: DeserializeOwned>(self) -> CResult<T> {
    let full = self.bytes().await?;
    rmp_serde::from_slice(&full).consider_cli(None)
  }
}