refit icon indicating copy to clipboard operation
refit copied to clipboard

Feature Request: Auto-Disposed ApiResponeSnapshot<T> Implementation

Open sdepouw opened this issue 5 months ago • 6 comments

Is your feature request related to a problem? Please describe.

Recently discovered that instances of ApiResponse<T> are, in fact, disposable, and should be treated as such. This would require a scouring of our application to use the proper disposal patterns. (In our case, we never do anything with the HTTP response once it's complete; we just need the content / status / result of the request. So, we'd immediately dispose every single time.)

e.g. transform every case of

ApiRespone<MyObject> foo = myApi.GetFooAsync(ct);

into something like

using ApiRespone<MyObject> foo = myApi.GetFooAsync(ct);

This isn't causing major issues or fires. But it does mean that we're never disposing of HTTP Responses, which could lead to the usual issues surrounding that (leaving sockets open, connection pool exhaustion, etc.)

Describe the solution you'd like

Rather than relying on consumers of the Refit APIs in code to have to dispose everything, being able to instruct Refit to do it for us (with the understanding that the underlying HTTP Response is already disposed) so that we don't have to do it ourselves would be ideal:

public interface IMyRefitApi
{
  // ApiResponseSnapshot<T> takes a snapshot of all the HTTP response data/content/status/error/etc. and immediately disposes of resources.
  [Get("/path/to/some/api")]
  Task<ApiResponseSnapshot<MyObject>> GetFooAsync(CancellationToken ct);
}

Describe alternatives you've considered

A workaround would be to make my own ApiResponseSnapshot<T> that takes in ApiResponse<T>, grabs what I want, and dispose of the response immediately. But this would still require modifying every use of Refit (and we'd have to remember to do this going forward -- which inevitably we'll forget, short of having some static analysis / enforcement in place):

// ToSnapshot() would be an extension method to do the transformation / disposal automatically.
ApiResponeSnapshot<MyObject> foo = myApi.GetFooAsync(ct).ToSnapshot();

We can't just put it on the Refit API interface directly, because anything that isn't IApiResponse or ApiResponse<T> is assumed to be a custom object to deserialize the Response Content. Even implementing IApiResponse is not treated as "hydrate this with the HTTP Response" and instead is treated like any other custom object.

Describe suggestions on how to achieve the feature

Whatever's done in Refit to see ApiRespone<T> and hydrate it with the HTTP Response content, do the same with a hypothetical ApiResponseSnapshot<T> and immediately dispose of the underlying HTTP Response. It could even be an ApiResponse<T> (although that class is sealed), and just try/finally in constructor to dispose the underlying response immediately, potentially.

The cleaner way would be to implement IApiResponse and earmark ApiResponseSnapshot<T> as another special case for "no this isn't a custom object: Give me the HTTP Response."

I'm not super familiar with the underlying source though.

Alternate Possibility (Requires Users of this NuGet to Implement)

Some means of making it so we can provide our own custom ApiResponse<T>'s, whether this means unsealing ApiResponse<T> or making implementations of IApiResponse behave like ApiResponse<T> does, would let us implement our own solutions. Right now this doesn't seem possible, due to any not-(I)ApiResponse object being assumed to be content to deserialize to.

Additional context

I don't know how prevalent our use case is. But across a couple applications now, my usage of Refit APIs is generally "we don't care about the response once we have the data, and it would be nice if we didn't have to manage the disposable nature of it -- just immediately dispose for us please and thank you."

Thanks!

sdepouw avatar Jun 17 '26 11:06 sdepouw

Thanks for the detailed write-up.

Triage: labeled as enhancement, priority: low, area: exceptions (ApiResponse).

Before going further on the feature, one important correction on the premise. For the common case you describe (Task<ApiResponse<MyObject>> where MyObject is a deserialized POCO), you do not actually need to dispose, and you are not leaking sockets.

Here is what happens internally in RequestBuilderImplementation.ExecuteRequestAsync:

  • The request is sent with HttpCompletionOption.ResponseHeadersRead.
  • The body is fully read and deserialized into ApiResponse<T>.Content (buffered into memory), which returns the connection to the pool.
  • ShouldDisposeResponse is computed in RestMethodInfo.DetermineIfResponseMustBeDisposed. It is true for every result type except HttpResponseMessage, HttpContent, and Stream. A POCO body is none of those, so it is true.
  • Because of that, the finally block disposes the underlying HttpResponseMessage (and its content) before the ApiResponse<T> is ever handed back to you.

So ApiResponse<T>.Dispose() for a POCO body just calls HttpResponseMessage.Dispose() a second time. That is idempotent, and ApiResponse<T> also guards it with its own disposed flag, so it is a harmless no-op. The using is not wrong, it is just not buying you anything: the socket is already back in the pool and the content is already in managed memory.

The case where disposal genuinely matters (and where Refit deliberately does NOT dispose for you, leaving the caller to own it) is when you ask for the live stream: return types of HttpResponseMessage, HttpContent, Stream, or ApiResponse<Stream> / ApiResponse<HttpContent> / ApiResponse<HttpResponseMessage>. There ShouldDisposeResponse is false, the body is not buffered, and you must dispose to release the connection. That is the only scenario that can exhaust the pool.

The reason ApiResponse<T> implements IDisposable at all is to cover those streaming cases with a single uniform type. For POCO responses it is effectively already disposed. So CA2000 / the analyzer flagging it is technically correct (it is IDisposable) but in practice a false alarm for the buffered path.

Given that, an ApiResponseSnapshot<T> would not actually change the resource behavior for POCO responses, since the response is already disposed by the time you receive it. If there is still appetite for an explicit "I only want the metadata, not the disposable wrapper" type for ergonomics / analyzer-silencing reasons, that is a reasonable ergonomics request and we can keep this open as low priority for that. But it is worth noting it does not fix a leak, because there is not one in the common case.

If your real scenario is one of the streaming return types above, let us know and we can dig into that specifically.

glennawatson avatar Jun 18 '26 00:06 glennawatson

Oh, interesting, that's good to know! Thanks for the detailed response.

I'd say we're using ApiResponse<SomePOCO> north of 95+% of the time. It's very rare we do otherwise.

Given what you said, it also sounds like if you just do Task<IApiResponse> (since it's not HttpContent or any others where we get the stream back), that also doesn't need disposing?

I'd say since ApiResponse<SomePOCO> auto-disposes, then the need for this goes way down!

sdepouw avatar Jun 18 '26 11:06 sdepouw

Right - IApiResponse follows the same rule. The only return types Refit doesn't auto-dispose are the streaming ones where you're holding the live response: HttpResponseMessage, HttpContent, Stream (and their ApiResponse<> wrappers). That's decided in RestMethodInfoInternal.DetermineIfResponseMustBeDisposed - it's those three types only. Everything else, including a bare IApiResponse, is already disposed in the finally before you get it, so using is harmless but unnecessary.

glennawatson avatar Jun 22 '26 00:06 glennawatson

I'm going to treat this issue more as a documentation issue if you don't mind, and close it with some readme.md updates

glennawatson avatar Jun 22 '26 06:06 glennawatson

I'm going to treat this issue more as a documentation issue if you don't mind, and close it with some readme.md updates

Go for it!

sdepouw avatar Jun 22 '26 12:06 sdepouw

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Jul 07 '26 00:07 github-actions[bot]