Skip to content

[Core/Rust Server] Support multiple request body/response body types #19411

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

richardwhiuk
Copy link
Contributor

@richardwhiuk richardwhiuk commented Aug 21, 2024

Overview

Support a request / response which can have multiple body content types - e.g. in V3:

requestBody:
  content:
    application/json:
      schema:
        type: string
    application/xml:
      schema:
        type: string
responses:
  200:
    content:
      application/json:
        type: string
      application/xml:
        type: string

Details

Existing Changes

DefaultCodgen.fromResponse now takes the Operation ID as a parameter.

The following methods have been renamed for clarity:

ModelUtils:

getSchemaFromResponse -> getFirstSchemaFromResponse
getSchemaFromContent -> getFirstSchemaFromContent

DefaultCodegen:

hasBodyParameter -> hasFirstBodyParameter
fromRequestBodyToFormParameters -> fromFirstRequestBodyToFormParameters
getContentType -> getFirstContentType

Enabling Support

This is opt in for a generator - the generator needs to set supportsMultipleRequestTypes and supportsMultipleResponseTypes in order to opt into supporting multiple request and response types.

This is required because per generator changes are required in order to support the new function, and a bunch of existing tests depend on the current behaviour, assuming the user only cares about the first request / response type.

Modelling of multiple request/responses

In order to reuse as much existing function as possible, and isolate the required changes, the mechanism used is as follows.

a) If support for multiple request and response types is disabled, no change in behaviour.

b) If the operation being generated doesn't have multiple requests, or multiple responses, there is no change in behaviour.

c) If the operation being generated has multiple requests, then a top level CodgenParameter for the body parameter is generated.

This has a child CodegenParameter for each of the different Content Type for the request. Each child parameter has contentType set.

d) If the operation being generated has multiple responses, then a top level CodegenResponse is generated.

This has a child CodegenResponse for each of the different Content Type for the request. Each child response has contentType set.

In addition to the multiple CodegenRequest/CodegenResponse, an additional set of models are generated. This allows an additional layer of indirection is done to flag which content type is used/will be used. The models in question are flagged with isVariant set to true, and alias the body parameter being used.

Overview of Rust Server generation

Here is a request which either takes a JSON request, or an XML request

    async fn update_pet(
        &self,
        body: swagger::OneOf2<
            models::UpdatePetApplicationSlashJsonRequest,
            models::UpdatePetApplicationSlashXmlRequest>,
        ) -> Result<UpdatePetResponse, ApiError>

Here is a response, which either returns an XML Response or a JSON response

pub enum FindPetsByStatusResponse {
    SuccessfulOperation(
        swagger::OneOf2<
            models::FindPetsByStatus200ApplicationSlashXmlResponse,
            models::FindPetsByStatus200ApplicationSlashJsonResponse
        >
    )
}

In this case, because the responses are defined the same (which is a restriction in OpenAPI V2, but not in OpenAPI V3), the definition for the responses is the same:

pub struct FindPetsByStatus200ApplicationSlashJsonResponse(
    Vec<Pet>
);
pub struct FindPetsByStatus200ApplicationSlashJsonResponse(
    Vec<Pet>
);

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package 
    ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@OpenAPITools/generator-core-team

Rust Technical Committee: @frol @farcaller @paladinzh @jacob-pro

Expect this to need plenty of review.

Support a request / response which can have multiple body content types

e.g.

requestBody:
  content:
    application/json:
      schema:
        type: string
    application/xml:
      schema:
        type: string
responses:
  200:
    content:
      application/json:
        type: string
      application/xml:
        type: string
@wing328
Copy link
Member

wing328 commented Aug 24, 2024

thanks for the PR. please resolve the merge conflicts when you've time

cc @OpenAPITools/generator-core-team

@richardwhiuk
Copy link
Contributor Author

thanks for the PR. please resolve the merge conflicts when you've time

@wing328 I've sorted the merge conflicts - happy to merge, or do you want additional reviews?

@wing328
Copy link
Member

wing328 commented Sep 23, 2024

let me take another tomorrow and will merge if no question from me

@@ -124,6 +124,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
@Getter @Setter
public String arrayModelType;
public boolean isAlias; // Is this effectively an alias of another simple type
public boolean isVariant; // Does this represent a schema variant?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please add a comment showing an example of a schema variant to put everyone on the same page?

*/
@SuppressWarnings("static-method")
public String toVariantName(List<String> names) {
return "oneOf<" + String.join(",", names) + ">";
Copy link
Member

@wing328 wing328 Sep 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think this is for a schema covering all the schema specified in the responses (e.g. 2xx, 3xx, 4xx).

should this be anyOf instead as technically the payload in the response can technically match more than one schema defined in the responses?

for (Map.Entry<String, ApiResponse> ar : op.getResponses().entrySet()) {
ApiResponse a = ModelUtils.getReferencedApiResponse(openAPI, ar.getValue());
Map<String, Schema> responseSchemas = ModelUtils.getSchemasFromResponse(openAPI, a);
if (responseSchemas != null && responseSchemas.size() > 1 && supportsMultipleResponseTypes) {
Copy link
Member

@wing328 wing328 Sep 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about also checking supportsMultipleResponseTypes at line 508?

requestSchemas = ModelUtils.getSchemasFromRequestBody(b);
}
if (requestSchemas != null) {
if (requestSchemas.size() > 1 && supportsMultipleRequestTypes) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about combining the conditions in line 499 and 500 into one?

@wing328
Copy link
Member

wing328 commented Sep 25, 2024

@richardwhiuk when you've time, can you please also PM me via Slack as I've few questions if you don't mind?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants