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
use crate::api::operation::parameter::RequestParameter;
use crate::inline::InlineApi;
use crate::reference::resolve_local_reference;
use crate::{description_to_doc_attr, CodeGenerator};

use convert_case::{Case, Casing};
use http::Method;
use indexmap::IndexMap;
use openapiv3::{Operation, PathItem, ReferenceOr, Schema};
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use unzip_n::unzip_n;

use std::borrow::Cow;
use std::collections::HashMap;

mod parameter;
mod request_body;
mod response;

unzip_n!(5);

/// A single API operation (e.g., `GET /foo`).
pub(crate) struct PathOperation {
  pub method: Method,
  pub op: Operation,
  /// HTTP request path of the operation (e.g., `/foo`).
  pub request_path: String,
}

/// Collect all API operations into a flattened `Vec`.
pub(crate) fn collect_operations(
  openapi: &InlineApi,
  openapi_inline_mapping: &serde_yaml::Mapping,
) -> Vec<PathOperation> {
  openapi
    .paths
    .iter()
    .flat_map(|(request_path, path_item_or_ref)| {
      let path_item = match path_item_or_ref {
        ReferenceOr::Item(path_item) => Cow::Borrowed(path_item),
        ReferenceOr::Reference { reference } => {
          Cow::Owned(resolve_local_reference::<PathItem>(reference, openapi_inline_mapping).target)
        }
      };

      match path_item {
        Cow::Borrowed(item) => vec![
          item.get.as_ref().map(|op| (Method::GET, op.to_owned())),
          item.put.as_ref().map(|op| (Method::PUT, op.to_owned())),
          item.post.as_ref().map(|op| (Method::POST, op.to_owned())),
          item
            .delete
            .as_ref()
            .map(|op| (Method::DELETE, op.to_owned())),
          item
            .options
            .as_ref()
            .map(|op| (Method::OPTIONS, op.to_owned())),
          item.head.as_ref().map(|op| (Method::HEAD, op.to_owned())),
          item.patch.as_ref().map(|op| (Method::PATCH, op.to_owned())),
          item.trace.as_ref().map(|op| (Method::TRACE, op.to_owned())),
        ],
        Cow::Owned(item) => vec![
          item.get.map(|op| (Method::GET, op)),
          item.put.map(|op| (Method::PUT, op)),
          item.post.map(|op| (Method::POST, op)),
          item.delete.map(|op| (Method::DELETE, op)),
          item.options.map(|op| (Method::OPTIONS, op)),
          item.head.map(|op| (Method::HEAD, op)),
          item.patch.map(|op| (Method::PATCH, op)),
          item.trace.map(|op| (Method::TRACE, op)),
        ],
      }
      .into_iter()
      .flatten()
      .map(move |(method, op)| PathOperation {
        method,
        op,
        request_path: request_path.to_owned(),
      })
    })
    .collect()
}

/// A generated single API operation (e.g., `GET /foo`).
pub struct ApiOperation {
  /// Match case for the API dispatcher from `operation_id` to the handler wrapper.
  pub api_dispatcher_case: TokenStream,

  /// Handler function the user must implement.
  pub handler_impl: TokenStream,

  /// Prototype for the handler function the user must implement.
  pub handler_prototype: TokenStream,

  /// Definition for wrapper function for the handler that parses parameters and implements logging,
  /// authentication, etc.
  ///
  /// This function calls the user's handler.
  pub handler_wrapper: TokenStream,

  /// Definition for operation response type enum with one variant for each HTTP status code.
  pub response_type_enum: TokenStream,

  /// Identifier for the operation response type.
  pub response_type_ident: Ident,
}

impl CodeGenerator {
  pub(crate) fn gen_api_operation(
    &self,
    mod_name: &str,
    operation: &PathOperation,
    openapi_inline: &serde_yaml::Mapping,
    components_schemas: &IndexMap<String, ReferenceOr<Schema>>,
    generated_models: &HashMap<Ident, TokenStream>,
  ) -> ApiOperation {
    let PathOperation {
      method,
      request_path,
      op,
    } = operation;

    let operation_id = op
      .operation_id
      .as_ref()
      .unwrap_or_else(|| panic!("no operation_id for {request_path}"));

    let request_body = op
      .request_body
      .as_ref()
      .map(|request_body| match request_body {
        ReferenceOr::Item(request) => Cow::Borrowed(request),
        ReferenceOr::Reference { reference } => {
          Cow::Owned(resolve_local_reference(reference, openapi_inline).target)
        }
      });

    let body_parameter = request_body.and_then(|request_body| {
      self.gen_request_body(
        request_path,
        request_body.as_ref(),
        openapi_inline,
        components_schemas,
        generated_models,
      )
    });

    let (param_call_values, log_params, param_doc_attrs, param_signatures, param_parse_assignments) =
      op.parameters
        .iter()
        .map(|parameter| match parameter {
          ReferenceOr::Reference { reference } => self.gen_request_parameter(
            &resolve_local_reference(reference, openapi_inline).target,
            components_schemas,
            generated_models,
          ),
          ReferenceOr::Item(parameter) => {
            self.gen_request_parameter(parameter, components_schemas, generated_models)
          }
        })
        .chain(body_parameter)
        .map(
          |RequestParameter {
             call_value,
             doc_attr,
             log_param,
             signature,
             wrapper_parse_assignment,
           }| {
            (
              call_value,
              log_param,
              doc_attr,
              signature,
              wrapper_parse_assignment,
            )
          },
        )
        .unzip_n::<TokenStream, TokenStream, TokenStream, TokenStream, TokenStream>();

    let func_name_snake = operation_id.to_case(Case::Snake);
    let func_name_ident = self.identifier(&func_name_snake);
    let handler_wrapper_name_ident =
      Ident::new(&format!("handle_{func_name_snake}"), Span::call_site());
    let response_type_ident =
      self.identifier(&format!("{}Response", operation_id.to_case(Case::Pascal)));

    let response_type_enum = self.gen_operation_response_type_enum(
      mod_name,
      &func_name_snake,
      &response_type_ident,
      operation,
      openapi_inline,
      components_schemas,
      generated_models,
    );

    let is_unauthenticated = op
      .security
      .as_ref()
      .map(|security| security.iter().any(|sec| sec.is_empty()))
      .unwrap_or(false);
    let (maybe_authenticate, auth_ok_proto_arg, auth_ok_doc_attr, auth_ok_call_arg, wrapper) =
      if is_unauthenticated {
        (
          quote! {
            log::debug!("Request does not require authentication");
          },
          quote! {},
          quote! {},
          quote! {},
          quote! { wrap_handler_unauthed },
        )
      } else {
        (
          quote! {
            log::trace!("Authenticating request");
            let auth_ok = match middleware.authenticate(
              #operation_id,
              &request.headers,
              &request.request_context,
              &lambda_context,
            ).await {
              Ok(auth_ok) => auth_ok,
              Err(err) => return err,
            };
          },
          quote! {
            auth_ok: Self::AuthOk,
          },
          quote! {
            /// * `auth_ok` - Output of [`Middleware::authenticate`] representing the authenticated
            ///   user's identity
          },
          quote! {
            auth_ok,
          },
          quote! { wrap_handler_authed },
        )
      };

    let description_doc_attr = op
      .description
      .as_ref()
      .map(|description| {
        let doc_attr = description_to_doc_attr(description);
        quote! {
          #doc_attr
          ///
        }
      })
      .unwrap_or_default();

    let method_upper = method.as_str();
    let handler_prototype = quote! {
      #description_doc_attr
      #[doc = concat!("Endpoint: `", #method_upper, " ", #request_path, "`")]
      ///
      #[doc = concat!("Operation ID: `", #operation_id, "`")]
      ///
      /// # Arguments
      ///
      #param_doc_attrs
      /// * `headers` - HTTP request headers
      /// * `request_context` - API Gateway request context. Contains information about the AWS
      ///   account/resources that invoked the Lambda function and Cognito identity information
      ///   about the client (if configured for the API Gateway).
      /// * `lambda_context` Lambda function execution context
      #auth_ok_doc_attr
      async fn #func_name_ident(
        &self,
        #param_signatures
        headers: HeaderMap,
        request_context: ApiGatewayProxyRequestContext,
        lambda_context: LambdaContext,
        #auth_ok_proto_arg
      ) -> Result<(#response_type_ident, HeaderMap), Self::HandlerError>;
    };

    let handler_impl = quote! {
      async fn #func_name_ident(
        &self,
        #param_signatures
        headers: HeaderMap,
        request_context: ApiGatewayProxyRequestContext,
        lambda_context: LambdaContext,
        #auth_ok_proto_arg
      ) -> Result<(#response_type_ident, HeaderMap), Self::HandlerError> {
        todo!()
      }
    };

    let handler_wrapper = quote! {
      async fn #handler_wrapper_name_ident<A, M>(
        api: &A,
        request: ApiGatewayProxyRequest,
        lambda_context: LambdaContext,
        middleware: &M,
      )-> HttpResponse
      where
        A: Api<AuthOk = <M as Middleware>::AuthOk> + Sync,
        M: Middleware + Sync,
      {
        log::info!(concat!("Handling HTTP ", #method_upper, " {} ({})"), #request_path, #operation_id);

        #param_parse_assignments
        #log_params

        #maybe_authenticate

        middleware.#wrapper(
          |headers, request_context, lambda_context, #auth_ok_call_arg| async move {
            let (response, response_headers) = match api
              .#func_name_ident(
                #param_call_values
                headers,
                request_context,
                lambda_context,
                #auth_ok_call_arg
              )
              .await
            {
              Ok((response, response_headers)) => (response, response_headers),
              Err(err) => return api.respond_to_handler_error(err).await,
            };

            log::trace!("Response: {response:#?}");
            log::trace!("Returning response headers: {response_headers:#?}");

            match response.into_http_response(response_headers) {
              Ok(response) => response,
              Err(err) => api.respond_to_event_error(err).await,
            }
          },
          #operation_id,
          request.headers,
          request.request_context,
          lambda_context,
          #auth_ok_call_arg
        )
        .await
      }
    };

    let api_dispatcher_case = quote! {
      #operation_id => #handler_wrapper_name_ident(
        api,
        request,
        lambda_context,
        middleware,
      ).await,
    };

    ApiOperation {
      api_dispatcher_case,
      handler_impl,
      handler_prototype,
      handler_wrapper,
      response_type_enum,
      response_type_ident,
    }
  }
}