openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[BUG] [cpp-ue4] generated code doesn't properly check for connection failures

Open leith-bartrich opened this issue 5 years ago • 6 comments

Bug Report Checklist

  • [x] Have you provided a full/minimal spec to reproduce the issue?
  • [x] Have you validated the input using an OpenAPI validator (example)?
  • [x] Have you tested with the latest master to confirm the issue still exists?
  • [x] Have you searched for related issues/PRs?
  • [x] What's the actual output vs expected output?
  • [ ] [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

The generated code for handling REST requests and responses doesn't properly check for connection failures. Also, when it defaults into a connection failure scenario later on, it erroneously injects a HTTP response code of 408. Unreal's own files say that response means:

		// the server timed out waiting for the request.
		RequestTimeout = 408,

this can be seen at the end of the "HandleResponse" method in the Api object. Quoting the template:

	// By default, assume we failed to establish connection
	InOutResponse.SetHttpResponseCode(EHttpResponseCodes::RequestTimeout);

This code is reached when the HTTPRespone is null, or bSuccess is false. In the case of a connection failure, the server never responded but we got here anyway; and now, the REST protocol layer is pretending that the server sent a response and a code that it never sent. This behavior is very problematic.

For my part, I was trying to catch the 408 response by debugging my server code because of course, an http response code that is reserved for an actual server to send, is being sent by the server right? Nope. Eventually I debugged Django deeply enough to suspect that the connection was being rejected and thought to check for client side code making up the 408 error out of thin air. Perhaps it was Apple's WebKit client? Nope, it was the generated REST code from the template.

What likely should be happening is: before constructing a response, the client should probably check the request for its status.

from the existing template:

void {{classname}}::On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate) const
{
	{{operationIdCamelCase}}Response Response;
	HandleResponse(HttpResponse, bSucceeded, Response);
	Delegate.ExecuteIfBound(Response);
}

The HttpRequest has a GetStatus() method which could be leveraged as such before actually trying to "HandleResponse" when a response actually never happened:

void OrgbuilderApi::OnUpdateLegalEntityResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateLegalEntityDelegate Delegate) const
{
	//handling a response that isn't an actual response would be a problem.
	switch (HttpRequest->GetStatus())
	{
	case EHttpRequestStatus::Failed :
		{
			UpdateLegalEntityResponse Response;
			Response.SetHttpResponseCode(EHttpResponseCodes::Unknown);
			Response.SetResponseString("Client reports request connection failed: " + HttpRequest->GetURL());
			Response.SetSuccessful(false);
			Delegate.ExecuteIfBound(Response);
		}; break ;
	case EHttpRequestStatus::Failed_ConnectionError :
		{
			UpdateLegalEntityResponse Response;
			Response.SetHttpResponseCode(EHttpResponseCodes::Unknown);
			Response.SetResponseString("Client reports request connection failed but could be retried: " + HttpRequest->GetURL());
			Response.SetSuccessful(false);
			Delegate.ExecuteIfBound(Response);
		}; break ;
	default :
		{
			//we likely have an actual response to handle.
			UpdateLegalEntityResponse Response;
			HandleResponse(HttpResponse, bSucceeded, Response);
			Delegate.ExecuteIfBound(Response);
		};
	}
}

I'm not thrilled with this solution. Because we're still technically telling the downstream developer that a response happened. Though I'm much happier at least setting the response to Unknown (0) and passing along a response string that describes this as a client talking about a client connection error.

// status code not set yet
		Unknown = 0,

lastly, we'd likely change the fall through in HandleResponse to something like this, to keep the general structure in place:

	// By default, assume we failed to establish connection
	InOutResponse.SetHttpResponseCode(EHttpResponseCodes::Unknown);
	if (bSucceeded)
	{
		InOutResponse.SetResponseString(TEXT("The client didn't report a connection failure, but it received no response."));
	} else
	{
		InOutResponse.SetResponseString(TEXT("The client didn't report a connection failure, but the request was not succesful."));
	}

But really we probably need a more descriptive interface here where a downstream developer can be informed of client connection failures, as a separate matter from handling server responses.

openapi-generator version

development HEAD

OpenAPI declaration file content or url

any valid file will generate this code.

Generation Details

any cpp-ue4 generated api will generate this code.

Steps to reproduce
  • generate any api with cpp-ue4 to see the code.
  • If trying to create this client-server condition, one might try putting up a firewall, which should reject client connection requests.
Related issues/PRs

none

Suggest a fix

see above.

tagging @Kahncode

leith-bartrich avatar Sep 02 '21 16:09 leith-bartrich

I don't disagree with your analysis, I believe I copied this behavior from one of the other generators, but from my research 408 can be interpreted as both a client-side or server-side error, and if you failed to establish the connection, timeout is about as descriptive as it gets. True, it won't help you diagnose whether it's a client-side or server-side error, but semantically it's not too bad.

Kahncode avatar Sep 02 '21 18:09 Kahncode

Just to be clear, I'm not submitting a pull request for this currently because I'm not sure if the changes I mocked up above are the right course of action or not.

I pointed out that an interface change (which would be breaking) might be a better approach to better communicate a client failure (and a lack of a http response) to the downstream developer. Which could be an additional delegate, or a change to the delegates that exist.

I think a lot of the confusion around 4xx response codes (and I've seen a lot of muddled analysis out there) are that 4xx response codes are for the server to indicate that the client is at fault at an http level. Which implies that it's a http client's mistake that led to the response code. But that doesn't mean a client should emit codes itself. Only a server should assert an http response code that implicates the http client.

Further, the distinction between the two client failure types outlined in the above code is somewhat important. After going through the code for both the Apple and Curl IHttpRequest implementations, I understand a bit more what they mean. Critical to the distinction is that client failures are usually socket level TCP errors or conditions. The distinction between the two types is largely one of determining if the server was potentially processing the request or not. Which is somewhat related to this matter: https://restfulapi.net/rest-put-vs-post/

Meaning: a Failed_ConnectionError connection attempt is one where the client knows the server never got the request. Likely because the connection was actively refused or failed prior even to that. A Failed connection attempt however, is one where the client doesn't know if the server began processing the request or not. This distinction is important to the PUT vs POST issue referenced above, because a decision as to what to do is actually application level at that point. It's not possible for the TCP and HTTP layers to know at that point. And the above referenced doc points out, even the REST layer cannot know for sure, though there are good practices to considered regarding put vs post.

e.g. A Failed_ConnectionError status or a Failed status on a well chosen (update) PUT probably can be resubmitted for a well formed REST API. However, a well chosen (create) POST should probably draw a distinction between the two because it's possible that a Failed POST might have actually been processed. Whereas a Failed_ConnectionError definitely didn't go through. The recovery may be different. But all of that depends on application layer knowledge that only the downstream developer would have. So, they need that information passed to them.

That's why I didn't just submit a pull request. I'm leaning toward the opinion the interface needs to change in a breaking manner.

leith-bartrich avatar Sep 02 '21 21:09 leith-bartrich

Again I agree. I believe the breaking change is the best solution and most likely minor.

I have a hard time seeing a practical scenario for this anyway, a failed connection no matter the cause would be most likely handled in the same way by some retry strategy with backoff, and then go down the failure path.

But ultimately I believe your approach gives more information to the client code to handle the error in case it becomes useful, and would likely not break much production code currently using the generator. I don't know if there is a versioning feature to each generator, but we could also indicate breaking changes by increasing the version numbers appropriately to signal the end users.

Kahncode avatar Sep 02 '21 21:09 Kahncode

A couple of extra observations:

  • The HTTPRetryManager already handles both cases correctly in its retry strategy, and it's the favored way of handling retries with the generated API
  • We could simply remove the opinionated part of the handling of the response: Response::GetHttpResponseCode() should call the HttpResponse's getter, and we can add the HttpRequest pointer to Response as well. The user code now has access to all the information required to handle this.

This might be the most elegant way to handle it and removes all opinions and assumptions from the generated code.

Kahncode avatar Sep 02 '21 21:09 Kahncode

Just FYI for the curious, you can see my progress here: https://github.com/leith-bartrich/openapi-generator/tree/bug-clientConnectionFailure-01

I'm not ready to make a draft pull request yet as I'm still making significant changes. I'm about to revert some redundancies out for example. And also investigate the effect of "canceling" a request on the code (something not discussed above).

When I have it solid enough I'll put together a draft pull request to discuss\test further.

leith-bartrich avatar Sep 04 '21 14:09 leith-bartrich

the bug stands but I won't be submitting a pull request on it.

leith-bartrich avatar Sep 12 '21 15:09 leith-bartrich