ecli_server_codegen/server/
mod.rs

1use futures::{future, future::BoxFuture, future::FutureExt, stream, stream::TryStreamExt, Stream};
2use hyper::header::{HeaderName, HeaderValue, CONTENT_TYPE};
3use hyper::{Body, HeaderMap, Request, Response, StatusCode};
4use log::warn;
5#[allow(unused_imports)]
6use std::convert::{TryFrom, TryInto};
7use std::error::Error;
8use std::future::Future;
9use std::marker::PhantomData;
10use std::task::{Context, Poll};
11pub use swagger::auth::Authorization;
12use swagger::auth::Scopes;
13use swagger::{ApiError, BodyExt, Has, RequestParser, XSpanIdString};
14use url::form_urlencoded;
15
16use crate::header;
17#[allow(unused_imports)]
18use crate::models;
19
20pub use crate::context;
21
22type ServiceFuture = BoxFuture<'static, Result<Response<Body>, crate::ServiceError>>;
23
24use crate::{
25    Api, GetTaskListResponse, GetTaskLogByIdResponse, PauseTaskByIdResponse,
26    ResumeTaskByIdResponse, StartTaskResponse, StopTaskByIdResponse,
27};
28
29mod paths {
30    use lazy_static::lazy_static;
31
32    lazy_static! {
33        pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(vec![
34            r"^/log$",
35            r"^/pause$",
36            r"^/resume$",
37            r"^/stop$",
38            r"^/task$"
39        ])
40        .expect("Unable to create global regex set");
41    }
42    pub(crate) static ID_LOG: usize = 0;
43    pub(crate) static ID_PAUSE: usize = 1;
44    pub(crate) static ID_RESUME: usize = 2;
45    pub(crate) static ID_STOP: usize = 3;
46    pub(crate) static ID_TASK: usize = 4;
47}
48
49pub struct MakeService<T, C>
50where
51    T: Api<C> + Clone + Send + 'static,
52    C: Has<XSpanIdString> + Send + Sync + 'static,
53{
54    api_impl: T,
55    marker: PhantomData<C>,
56}
57
58impl<T, C> MakeService<T, C>
59where
60    T: Api<C> + Clone + Send + 'static,
61    C: Has<XSpanIdString> + Send + Sync + 'static,
62{
63    pub fn new(api_impl: T) -> Self {
64        MakeService {
65            api_impl,
66            marker: PhantomData,
67        }
68    }
69}
70
71impl<T, C, Target> hyper::service::Service<Target> for MakeService<T, C>
72where
73    T: Api<C> + Clone + Send + 'static,
74    C: Has<XSpanIdString> + Send + Sync + 'static,
75{
76    type Response = Service<T, C>;
77    type Error = crate::ServiceError;
78    type Future = future::Ready<Result<Self::Response, Self::Error>>;
79
80    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
81        Poll::Ready(Ok(()))
82    }
83
84    fn call(&mut self, target: Target) -> Self::Future {
85        futures::future::ok(Service::new(self.api_impl.clone()))
86    }
87}
88
89fn method_not_allowed() -> Result<Response<Body>, crate::ServiceError> {
90    Ok(Response::builder()
91        .status(StatusCode::METHOD_NOT_ALLOWED)
92        .body(Body::empty())
93        .expect("Unable to create Method Not Allowed response"))
94}
95
96pub struct Service<T, C>
97where
98    T: Api<C> + Clone + Send + 'static,
99    C: Has<XSpanIdString> + Send + Sync + 'static,
100{
101    api_impl: T,
102    marker: PhantomData<C>,
103}
104
105impl<T, C> Service<T, C>
106where
107    T: Api<C> + Clone + Send + 'static,
108    C: Has<XSpanIdString> + Send + Sync + 'static,
109{
110    pub fn new(api_impl: T) -> Self {
111        Service {
112            api_impl,
113            marker: PhantomData,
114        }
115    }
116}
117
118impl<T, C> Clone for Service<T, C>
119where
120    T: Api<C> + Clone + Send + 'static,
121    C: Has<XSpanIdString> + Send + Sync + 'static,
122{
123    fn clone(&self) -> Self {
124        Service {
125            api_impl: self.api_impl.clone(),
126            marker: self.marker,
127        }
128    }
129}
130
131impl<T, C> hyper::service::Service<(Request<Body>, C)> for Service<T, C>
132where
133    T: Api<C> + Clone + Send + Sync + 'static,
134    C: Has<XSpanIdString> + Send + Sync + 'static,
135{
136    type Response = Response<Body>;
137    type Error = crate::ServiceError;
138    type Future = ServiceFuture;
139
140    fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
141        self.api_impl.poll_ready(cx)
142    }
143
144    fn call(&mut self, req: (Request<Body>, C)) -> Self::Future {
145        async fn run<T, C>(
146            mut api_impl: T,
147            req: (Request<Body>, C),
148        ) -> Result<Response<Body>, crate::ServiceError>
149        where
150            T: Api<C> + Clone + Send + 'static,
151            C: Has<XSpanIdString> + Send + Sync + 'static,
152        {
153            let (request, context) = req;
154            let (parts, body) = request.into_parts();
155            let (method, uri, headers) = (parts.method, parts.uri, parts.headers);
156            let path = paths::GLOBAL_REGEX_SET.matches(uri.path());
157
158            match method {
159                // GetTaskList - GET /task
160                hyper::Method::GET if path.matched(paths::ID_TASK) => {
161                    let result = api_impl.get_task_list(&context).await;
162                    let mut response = Response::new(Body::empty());
163                    response.headers_mut().insert(
164                        HeaderName::from_static("x-span-id"),
165                        HeaderValue::from_str(
166                            (&context as &dyn Has<XSpanIdString>)
167                                .get()
168                                .0
169                                .clone()
170                                .as_str(),
171                        )
172                        .expect("Unable to create X-Span-ID header value"),
173                    );
174
175                    match result {
176                        Ok(rsp) => match rsp {
177                            GetTaskListResponse::ListOfRunningTasks(body) => {
178                                *response.status_mut() = StatusCode::from_u16(200)
179                                    .expect("Unable to turn 200 into a StatusCode");
180                                response.headers_mut().insert(
181                                                        CONTENT_TYPE,
182                                                        HeaderValue::from_str("application/json")
183                                                            .expect("Unable to create Content-Type header for GET_TASK_LIST_LIST_OF_RUNNING_TASKS"));
184                                let body = serde_json::to_string(&body)
185                                    .expect("impossible to fail to serialize");
186                                *response.body_mut() = Body::from(body);
187                            }
188                        },
189                        Err(_) => {
190                            // Application code returned an error. This should not happen, as the implementation should
191                            // return a valid response.
192                            *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
193                            *response.body_mut() = Body::from("An internal error occurred");
194                        }
195                    }
196
197                    Ok(response)
198                }
199
200                // GetTaskLogById - POST /log
201                hyper::Method::POST if path.matched(paths::ID_LOG) => {
202                    // Body parameters (note that non-required body parameters will ignore garbage
203                    // values, rather than causing a 400 response). Produce warning header and logs for
204                    // any unused fields.
205                    let result = body.into_raw().await;
206                    match result {
207                            Ok(body) => {
208                                let mut unused_elements = Vec::new();
209                                let param_get_task_log_request: Option<models::GetTaskLogRequest> = if !body.is_empty() {
210                                    let deserializer = &mut serde_json::Deserializer::from_slice(&*body);
211                                    match serde_ignored::deserialize(deserializer, |path| {
212                                            warn!("Ignoring unknown field in body: {}", path);
213                                            unused_elements.push(path.to_string());
214                                    }) {
215                                        Ok(param_get_task_log_request) => param_get_task_log_request,
216                                        Err(e) => return Ok(Response::builder()
217                                                        .status(StatusCode::BAD_REQUEST)
218                                                        .body(Body::from(format!("Couldn't parse body parameter GetTaskLogRequest - doesn't match schema: {}", e)))
219                                                        .expect("Unable to create Bad Request response for invalid body parameter GetTaskLogRequest due to schema")),
220                                    }
221                                } else {
222                                    None
223                                };
224                                let param_get_task_log_request = match param_get_task_log_request {
225                                    Some(param_get_task_log_request) => param_get_task_log_request,
226                                    None => return Ok(Response::builder()
227                                                        .status(StatusCode::BAD_REQUEST)
228                                                        .body(Body::from("Missing required body parameter GetTaskLogRequest"))
229                                                        .expect("Unable to create Bad Request response for missing body parameter GetTaskLogRequest")),
230                                };
231
232                                let result = api_impl.get_task_log_by_id(
233                                            param_get_task_log_request,
234                                        &context
235                                    ).await;
236                                let mut response = Response::new(Body::empty());
237                                response.headers_mut().insert(
238                                            HeaderName::from_static("x-span-id"),
239                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().as_str())
240                                                .expect("Unable to create X-Span-ID header value"));
241
242                                        if !unused_elements.is_empty() {
243                                            response.headers_mut().insert(
244                                                HeaderName::from_static("warning"),
245                                                HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str())
246                                                    .expect("Unable to create Warning header value"));
247                                        }
248
249                                        match result {
250                                            Ok(rsp) => match rsp {
251                                                GetTaskLogByIdResponse::InvalidHandle
252                                                    (body)
253                                                => {
254                                                    *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode");
255                                                    response.headers_mut().insert(
256                                                        CONTENT_TYPE,
257                                                        HeaderValue::from_str("application/json")
258                                                            .expect("Unable to create Content-Type header for GET_TASK_LOG_BY_ID_INVALID_HANDLE"));
259                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
260                                                    *response.body_mut() = Body::from(body);
261                                                },
262                                                GetTaskLogByIdResponse::TheLogFetched
263                                                    (body)
264                                                => {
265                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
266                                                    response.headers_mut().insert(
267                                                        CONTENT_TYPE,
268                                                        HeaderValue::from_str("application/json")
269                                                            .expect("Unable to create Content-Type header for GET_TASK_LOG_BY_ID_THE_LOG_FETCHED"));
270                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
271                                                    *response.body_mut() = Body::from(body);
272                                                },
273                                            },
274                                            Err(_) => {
275                                                // Application code returned an error. This should not happen, as the implementation should
276                                                // return a valid response.
277                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
278                                                *response.body_mut() = Body::from("An internal error occurred");
279                                            },
280                                        }
281
282                                        Ok(response)
283                            },
284                            Err(e) => Ok(Response::builder()
285                                                .status(StatusCode::BAD_REQUEST)
286                                                .body(Body::from(format!("Couldn't read body parameter GetTaskLogRequest: {}", e)))
287                                                .expect("Unable to create Bad Request response due to unable to read body parameter GetTaskLogRequest")),
288                        }
289                }
290
291                // PauseTaskById - POST /pause
292                hyper::Method::POST if path.matched(paths::ID_PAUSE) => {
293                    // Body parameters (note that non-required body parameters will ignore garbage
294                    // values, rather than causing a 400 response). Produce warning header and logs for
295                    // any unused fields.
296                    let result = body.into_raw().await;
297                    match result {
298                            Ok(body) => {
299                                let mut unused_elements = Vec::new();
300                                let param_simple_id_request: Option<models::SimpleIdRequest> = if !body.is_empty() {
301                                    let deserializer = &mut serde_json::Deserializer::from_slice(&*body);
302                                    match serde_ignored::deserialize(deserializer, |path| {
303                                            warn!("Ignoring unknown field in body: {}", path);
304                                            unused_elements.push(path.to_string());
305                                    }) {
306                                        Ok(param_simple_id_request) => param_simple_id_request,
307                                        Err(e) => return Ok(Response::builder()
308                                                        .status(StatusCode::BAD_REQUEST)
309                                                        .body(Body::from(format!("Couldn't parse body parameter SimpleIdRequest - doesn't match schema: {}", e)))
310                                                        .expect("Unable to create Bad Request response for invalid body parameter SimpleIdRequest due to schema")),
311                                    }
312                                } else {
313                                    None
314                                };
315                                let param_simple_id_request = match param_simple_id_request {
316                                    Some(param_simple_id_request) => param_simple_id_request,
317                                    None => return Ok(Response::builder()
318                                                        .status(StatusCode::BAD_REQUEST)
319                                                        .body(Body::from("Missing required body parameter SimpleIdRequest"))
320                                                        .expect("Unable to create Bad Request response for missing body parameter SimpleIdRequest")),
321                                };
322
323                                let result = api_impl.pause_task_by_id(
324                                            param_simple_id_request,
325                                        &context
326                                    ).await;
327                                let mut response = Response::new(Body::empty());
328                                response.headers_mut().insert(
329                                            HeaderName::from_static("x-span-id"),
330                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().as_str())
331                                                .expect("Unable to create X-Span-ID header value"));
332
333                                        if !unused_elements.is_empty() {
334                                            response.headers_mut().insert(
335                                                HeaderName::from_static("warning"),
336                                                HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str())
337                                                    .expect("Unable to create Warning header value"));
338                                        }
339
340                                        match result {
341                                            Ok(rsp) => match rsp {
342                                                PauseTaskByIdResponse::FailedToPause
343                                                    (body)
344                                                => {
345                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
346                                                    response.headers_mut().insert(
347                                                        CONTENT_TYPE,
348                                                        HeaderValue::from_str("application/json")
349                                                            .expect("Unable to create Content-Type header for PAUSE_TASK_BY_ID_FAILED_TO_PAUSE"));
350                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
351                                                    *response.body_mut() = Body::from(body);
352                                                },
353                                                PauseTaskByIdResponse::InvalidHandle
354                                                    (body)
355                                                => {
356                                                    *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode");
357                                                    response.headers_mut().insert(
358                                                        CONTENT_TYPE,
359                                                        HeaderValue::from_str("application/json")
360                                                            .expect("Unable to create Content-Type header for PAUSE_TASK_BY_ID_INVALID_HANDLE"));
361                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
362                                                    *response.body_mut() = Body::from(body);
363                                                },
364                                                PauseTaskByIdResponse::StatusOfPausingTheTask
365                                                    (body)
366                                                => {
367                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
368                                                    response.headers_mut().insert(
369                                                        CONTENT_TYPE,
370                                                        HeaderValue::from_str("application/json")
371                                                            .expect("Unable to create Content-Type header for PAUSE_TASK_BY_ID_STATUS_OF_PAUSING_THE_TASK"));
372                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
373                                                    *response.body_mut() = Body::from(body);
374                                                },
375                                            },
376                                            Err(_) => {
377                                                // Application code returned an error. This should not happen, as the implementation should
378                                                // return a valid response.
379                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
380                                                *response.body_mut() = Body::from("An internal error occurred");
381                                            },
382                                        }
383
384                                        Ok(response)
385                            },
386                            Err(e) => Ok(Response::builder()
387                                                .status(StatusCode::BAD_REQUEST)
388                                                .body(Body::from(format!("Couldn't read body parameter SimpleIdRequest: {}", e)))
389                                                .expect("Unable to create Bad Request response due to unable to read body parameter SimpleIdRequest")),
390                        }
391                }
392
393                // ResumeTaskById - POST /resume
394                hyper::Method::POST if path.matched(paths::ID_RESUME) => {
395                    // Body parameters (note that non-required body parameters will ignore garbage
396                    // values, rather than causing a 400 response). Produce warning header and logs for
397                    // any unused fields.
398                    let result = body.into_raw().await;
399                    match result {
400                            Ok(body) => {
401                                let mut unused_elements = Vec::new();
402                                let param_simple_id_request: Option<models::SimpleIdRequest> = if !body.is_empty() {
403                                    let deserializer = &mut serde_json::Deserializer::from_slice(&*body);
404                                    match serde_ignored::deserialize(deserializer, |path| {
405                                            warn!("Ignoring unknown field in body: {}", path);
406                                            unused_elements.push(path.to_string());
407                                    }) {
408                                        Ok(param_simple_id_request) => param_simple_id_request,
409                                        Err(e) => return Ok(Response::builder()
410                                                        .status(StatusCode::BAD_REQUEST)
411                                                        .body(Body::from(format!("Couldn't parse body parameter SimpleIdRequest - doesn't match schema: {}", e)))
412                                                        .expect("Unable to create Bad Request response for invalid body parameter SimpleIdRequest due to schema")),
413                                    }
414                                } else {
415                                    None
416                                };
417                                let param_simple_id_request = match param_simple_id_request {
418                                    Some(param_simple_id_request) => param_simple_id_request,
419                                    None => return Ok(Response::builder()
420                                                        .status(StatusCode::BAD_REQUEST)
421                                                        .body(Body::from("Missing required body parameter SimpleIdRequest"))
422                                                        .expect("Unable to create Bad Request response for missing body parameter SimpleIdRequest")),
423                                };
424
425                                let result = api_impl.resume_task_by_id(
426                                            param_simple_id_request,
427                                        &context
428                                    ).await;
429                                let mut response = Response::new(Body::empty());
430                                response.headers_mut().insert(
431                                            HeaderName::from_static("x-span-id"),
432                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().as_str())
433                                                .expect("Unable to create X-Span-ID header value"));
434
435                                        if !unused_elements.is_empty() {
436                                            response.headers_mut().insert(
437                                                HeaderName::from_static("warning"),
438                                                HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str())
439                                                    .expect("Unable to create Warning header value"));
440                                        }
441
442                                        match result {
443                                            Ok(rsp) => match rsp {
444                                                ResumeTaskByIdResponse::FailedToResume
445                                                    (body)
446                                                => {
447                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
448                                                    response.headers_mut().insert(
449                                                        CONTENT_TYPE,
450                                                        HeaderValue::from_str("application/json")
451                                                            .expect("Unable to create Content-Type header for RESUME_TASK_BY_ID_FAILED_TO_RESUME"));
452                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
453                                                    *response.body_mut() = Body::from(body);
454                                                },
455                                                ResumeTaskByIdResponse::InvalidHandle
456                                                    (body)
457                                                => {
458                                                    *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode");
459                                                    response.headers_mut().insert(
460                                                        CONTENT_TYPE,
461                                                        HeaderValue::from_str("application/json")
462                                                            .expect("Unable to create Content-Type header for RESUME_TASK_BY_ID_INVALID_HANDLE"));
463                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
464                                                    *response.body_mut() = Body::from(body);
465                                                },
466                                                ResumeTaskByIdResponse::StatusOfTheTask
467                                                    (body)
468                                                => {
469                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
470                                                    response.headers_mut().insert(
471                                                        CONTENT_TYPE,
472                                                        HeaderValue::from_str("application/json")
473                                                            .expect("Unable to create Content-Type header for RESUME_TASK_BY_ID_STATUS_OF_THE_TASK"));
474                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
475                                                    *response.body_mut() = Body::from(body);
476                                                },
477                                            },
478                                            Err(_) => {
479                                                // Application code returned an error. This should not happen, as the implementation should
480                                                // return a valid response.
481                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
482                                                *response.body_mut() = Body::from("An internal error occurred");
483                                            },
484                                        }
485
486                                        Ok(response)
487                            },
488                            Err(e) => Ok(Response::builder()
489                                                .status(StatusCode::BAD_REQUEST)
490                                                .body(Body::from(format!("Couldn't read body parameter SimpleIdRequest: {}", e)))
491                                                .expect("Unable to create Bad Request response due to unable to read body parameter SimpleIdRequest")),
492                        }
493                }
494
495                // StartTask - POST /task
496                hyper::Method::POST if path.matched(paths::ID_TASK) => {
497                    // Body parameters (note that non-required body parameters will ignore garbage
498                    // values, rather than causing a 400 response). Produce warning header and logs for
499                    // any unused fields.
500                    let result = body.into_raw().await;
501                    match result {
502                            Ok(body) => {
503                                let mut unused_elements = Vec::new();
504                                let param_start_task_request: Option<models::StartTaskRequest> = if !body.is_empty() {
505                                    let deserializer = &mut serde_json::Deserializer::from_slice(&*body);
506                                    match serde_ignored::deserialize(deserializer, |path| {
507                                            warn!("Ignoring unknown field in body: {}", path);
508                                            unused_elements.push(path.to_string());
509                                    }) {
510                                        Ok(param_start_task_request) => param_start_task_request,
511                                        Err(e) => return Ok(Response::builder()
512                                                        .status(StatusCode::BAD_REQUEST)
513                                                        .body(Body::from(format!("Couldn't parse body parameter StartTaskRequest - doesn't match schema: {}", e)))
514                                                        .expect("Unable to create Bad Request response for invalid body parameter StartTaskRequest due to schema")),
515                                    }
516                                } else {
517                                    None
518                                };
519                                let param_start_task_request = match param_start_task_request {
520                                    Some(param_start_task_request) => param_start_task_request,
521                                    None => return Ok(Response::builder()
522                                                        .status(StatusCode::BAD_REQUEST)
523                                                        .body(Body::from("Missing required body parameter StartTaskRequest"))
524                                                        .expect("Unable to create Bad Request response for missing body parameter StartTaskRequest")),
525                                };
526
527                                let result = api_impl.start_task(
528                                            param_start_task_request,
529                                        &context
530                                    ).await;
531                                let mut response = Response::new(Body::empty());
532                                response.headers_mut().insert(
533                                            HeaderName::from_static("x-span-id"),
534                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().as_str())
535                                                .expect("Unable to create X-Span-ID header value"));
536
537                                        if !unused_elements.is_empty() {
538                                            response.headers_mut().insert(
539                                                HeaderName::from_static("warning"),
540                                                HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str())
541                                                    .expect("Unable to create Warning header value"));
542                                        }
543
544                                        match result {
545                                            Ok(rsp) => match rsp {
546                                                StartTaskResponse::InvalidArguments
547                                                    (body)
548                                                => {
549                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
550                                                    response.headers_mut().insert(
551                                                        CONTENT_TYPE,
552                                                        HeaderValue::from_str("application/json")
553                                                            .expect("Unable to create Content-Type header for START_TASK_INVALID_ARGUMENTS"));
554                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
555                                                    *response.body_mut() = Body::from(body);
556                                                },
557                                                StartTaskResponse::ListOfRunningTasks
558                                                    (body)
559                                                => {
560                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
561                                                    response.headers_mut().insert(
562                                                        CONTENT_TYPE,
563                                                        HeaderValue::from_str("application/json")
564                                                            .expect("Unable to create Content-Type header for START_TASK_LIST_OF_RUNNING_TASKS"));
565                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
566                                                    *response.body_mut() = Body::from(body);
567                                                },
568                                            },
569                                            Err(_) => {
570                                                // Application code returned an error. This should not happen, as the implementation should
571                                                // return a valid response.
572                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
573                                                *response.body_mut() = Body::from("An internal error occurred");
574                                            },
575                                        }
576
577                                        Ok(response)
578                            },
579                            Err(e) => Ok(Response::builder()
580                                                .status(StatusCode::BAD_REQUEST)
581                                                .body(Body::from(format!("Couldn't read body parameter StartTaskRequest: {}", e)))
582                                                .expect("Unable to create Bad Request response due to unable to read body parameter StartTaskRequest")),
583                        }
584                }
585
586                // StopTaskById - POST /stop
587                hyper::Method::POST if path.matched(paths::ID_STOP) => {
588                    // Body parameters (note that non-required body parameters will ignore garbage
589                    // values, rather than causing a 400 response). Produce warning header and logs for
590                    // any unused fields.
591                    let result = body.into_raw().await;
592                    match result {
593                            Ok(body) => {
594                                let mut unused_elements = Vec::new();
595                                let param_simple_id_request: Option<models::SimpleIdRequest> = if !body.is_empty() {
596                                    let deserializer = &mut serde_json::Deserializer::from_slice(&*body);
597                                    match serde_ignored::deserialize(deserializer, |path| {
598                                            warn!("Ignoring unknown field in body: {}", path);
599                                            unused_elements.push(path.to_string());
600                                    }) {
601                                        Ok(param_simple_id_request) => param_simple_id_request,
602                                        Err(e) => return Ok(Response::builder()
603                                                        .status(StatusCode::BAD_REQUEST)
604                                                        .body(Body::from(format!("Couldn't parse body parameter SimpleIdRequest - doesn't match schema: {}", e)))
605                                                        .expect("Unable to create Bad Request response for invalid body parameter SimpleIdRequest due to schema")),
606                                    }
607                                } else {
608                                    None
609                                };
610                                let param_simple_id_request = match param_simple_id_request {
611                                    Some(param_simple_id_request) => param_simple_id_request,
612                                    None => return Ok(Response::builder()
613                                                        .status(StatusCode::BAD_REQUEST)
614                                                        .body(Body::from("Missing required body parameter SimpleIdRequest"))
615                                                        .expect("Unable to create Bad Request response for missing body parameter SimpleIdRequest")),
616                                };
617
618                                let result = api_impl.stop_task_by_id(
619                                            param_simple_id_request,
620                                        &context
621                                    ).await;
622                                let mut response = Response::new(Body::empty());
623                                response.headers_mut().insert(
624                                            HeaderName::from_static("x-span-id"),
625                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().as_str())
626                                                .expect("Unable to create X-Span-ID header value"));
627
628                                        if !unused_elements.is_empty() {
629                                            response.headers_mut().insert(
630                                                HeaderName::from_static("warning"),
631                                                HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str())
632                                                    .expect("Unable to create Warning header value"));
633                                        }
634
635                                        match result {
636                                            Ok(rsp) => match rsp {
637                                                StopTaskByIdResponse::StatusOfStoppingTheTask
638                                                    (body)
639                                                => {
640                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
641                                                    response.headers_mut().insert(
642                                                        CONTENT_TYPE,
643                                                        HeaderValue::from_str("application/json")
644                                                            .expect("Unable to create Content-Type header for STOP_TASK_BY_ID_STATUS_OF_STOPPING_THE_TASK"));
645                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
646                                                    *response.body_mut() = Body::from(body);
647                                                },
648                                                StopTaskByIdResponse::InvalidHandle
649                                                    (body)
650                                                => {
651                                                    *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode");
652                                                    response.headers_mut().insert(
653                                                        CONTENT_TYPE,
654                                                        HeaderValue::from_str("application/json")
655                                                            .expect("Unable to create Content-Type header for STOP_TASK_BY_ID_INVALID_HANDLE"));
656                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
657                                                    *response.body_mut() = Body::from(body);
658                                                },
659                                                StopTaskByIdResponse::FailedToTerminate
660                                                    (body)
661                                                => {
662                                                    *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode");
663                                                    response.headers_mut().insert(
664                                                        CONTENT_TYPE,
665                                                        HeaderValue::from_str("application/json")
666                                                            .expect("Unable to create Content-Type header for STOP_TASK_BY_ID_FAILED_TO_TERMINATE"));
667                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
668                                                    *response.body_mut() = Body::from(body);
669                                                },
670                                            },
671                                            Err(_) => {
672                                                // Application code returned an error. This should not happen, as the implementation should
673                                                // return a valid response.
674                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
675                                                *response.body_mut() = Body::from("An internal error occurred");
676                                            },
677                                        }
678
679                                        Ok(response)
680                            },
681                            Err(e) => Ok(Response::builder()
682                                                .status(StatusCode::BAD_REQUEST)
683                                                .body(Body::from(format!("Couldn't read body parameter SimpleIdRequest: {}", e)))
684                                                .expect("Unable to create Bad Request response due to unable to read body parameter SimpleIdRequest")),
685                        }
686                }
687
688                _ if path.matched(paths::ID_LOG) => method_not_allowed(),
689                _ if path.matched(paths::ID_PAUSE) => method_not_allowed(),
690                _ if path.matched(paths::ID_RESUME) => method_not_allowed(),
691                _ if path.matched(paths::ID_STOP) => method_not_allowed(),
692                _ if path.matched(paths::ID_TASK) => method_not_allowed(),
693                _ => Ok(Response::builder()
694                    .status(StatusCode::NOT_FOUND)
695                    .body(Body::empty())
696                    .expect("Unable to create Not Found response")),
697            }
698        }
699        Box::pin(run(self.api_impl.clone(), req))
700    }
701}
702
703/// Request parser for `Api`.
704pub struct ApiRequestParser;
705impl<T> RequestParser<T> for ApiRequestParser {
706    fn parse_operation_id(request: &Request<T>) -> Option<&'static str> {
707        let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path());
708        match *request.method() {
709            // GetTaskList - GET /task
710            hyper::Method::GET if path.matched(paths::ID_TASK) => Some("GetTaskList"),
711            // GetTaskLogById - POST /log
712            hyper::Method::POST if path.matched(paths::ID_LOG) => Some("GetTaskLogById"),
713            // PauseTaskById - POST /pause
714            hyper::Method::POST if path.matched(paths::ID_PAUSE) => Some("PauseTaskById"),
715            // ResumeTaskById - POST /resume
716            hyper::Method::POST if path.matched(paths::ID_RESUME) => Some("ResumeTaskById"),
717            // StartTask - POST /task
718            hyper::Method::POST if path.matched(paths::ID_TASK) => Some("StartTask"),
719            // StopTaskById - POST /stop
720            hyper::Method::POST if path.matched(paths::ID_STOP) => Some("StopTaskById"),
721            _ => None,
722        }
723    }
724}