Repository navigation
break: add IAsyncEnumerable streaming and opt-in URL, route and JSON serialization modes - #2157
Merged
Merged
Conversation
…serialization modes
- Add IAsyncEnumerable<T> response streaming, auto-detecting a JSON array vs JSON Lines from the content type, via the new IStreamingContentSerializer capability
- Add opt-in RFC 3986 / HttpClient-style URL resolution through RefitSettings.UrlResolution and the UrlResolutionMode enum
- Add opt-in RefitSettings.AllowUnmatchedRouteParameters to leave an unmatched {token} in the URL for a DelegatingHandler to rewrite
- Read numbers from JSON strings by default in the System.Text.Json serializer (NumberHandling = AllowReadingFromString)
- Add SystemTextJsonContentSerializer.GetFastPathJsonSerializerOptions() returning options eligible for the source-generation fast-path
- Add RequestBodySerialization modes (Buffered, Streamed) that serialize request bodies through the source-gen fast-path
- Add tests, benchmarks and README coverage for the above
BREAKING CHANGE: the default System.Text.Json serializer now reads numbers from JSON strings; opt out with NumberHandling = JsonNumberHandling.Strict.
Closes #1299
Closes #1968
Closes #1803
Closes #2022
…eflection request builder - Emit IAsyncEnumerable<T> methods through GeneratedRequestRunner.StreamAsync<T> with the request constructed in source (new ReturnTypeInfo.AsyncEnumerable), avoiding the reflection request-builder on the streaming hot path - Keep the reflection path only as the fallback for shapes that cannot be generated inline (dynamic routes, body/query objects, generic methods) - Add generator and runtime tests covering both the inline and reflection streaming paths
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2157 +/- ##
==========================================
+ Coverage 97.63% 97.65% +0.02%
==========================================
Files 118 118
Lines 5369 5586 +217
Branches 976 1019 +43
==========================================
+ Hits 5242 5455 +213
Misses 33 33
- Partials 94 98 +4 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
ChrisPulman
approved these changes
Jun 22, 2026
- Add source-generated context tests for streaming (array, JSON Lines) and synchronous body serialization (buffered, streamed) to exercise the fast-path JsonTypeInfo branches - Cover JSON Lines reader edge cases: CRLF endings, a whitespace-only line, a line larger than the read buffer, and a final line with no trailing newline - Add reflection-path streaming tests (dynamic route, with and without a cancellation token) and a generator test for the non-inline IAsyncEnumerable fallback
- Add unit tests for GeneratedRequestRunner.BuildRelativeUri (legacy, RFC, missing base address) and extract a testable EnsureResponseContent helper with tests for both arms - Cover the source-generated JsonTypeInfo streaming and body-serialization branches, JSON Lines reader edges (CRLF, whitespace-only line, buffer growth, no trailing newline, missing content type), and early enumerator disposal - Drop the unreachable empty-span guard in the JSON Lines line reader so only the reachable carriage-return branch remains
|
|
Wow, huge PR! fantastic changes, thank you so much :) |
|
This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



What kind of change does this PR introduce?
Feature, several additive, opt-in capabilities, plus one breaking default-behaviour change to the System.Text.Json serializer.
What is the new behavior?
IAsyncEnumerable<T>response streaming. Declare a method returningIAsyncEnumerable<T>and Refit reads the response withResponseHeadersReadand yields items as they arrive. The frame format is auto-detected from the content type:application/jsonl/application/x-ndjson/application/x-jsonlinesis read as JSON Lines, anything else as a single streamed JSON array. Backed by the newIStreamingContentSerializercapability (implemented bySystemTextJsonContentSerializer).HttpClient-style URL resolution.RefitSettings.UrlResolution = UrlResolutionMode.Rfc3986combines the base address and relative path withSystem.Urirules (a leading slash replaces the base path; no leading slash appends) and relaxes the leading-slash requirement. Defaults toRefitLegacy, so existing behaviour is unchanged.RefitSettings.AllowUnmatchedRouteParameters. When set, a route placeholder with no matching argument is left in the URL verbatim (e.g.{version:apiVersion}) for aDelegatingHandlerto rewrite, instead of throwing.RefitSettings.RequestBodySerialization(BufferedorStreamed) serializes JSON bodies synchronously so the System.Text.Json source-generated fast-path engages,Bufferedsends aByteArrayContentwithContent-Length,Streamedwrites through aUtf8JsonWriterfor large uploads.SystemTextJsonContentSerializer.GetFastPathJsonSerializerOptions()returns a fast-path-eligible options set (no converters, noNumberHandling).NumberHandling = AllowReadingFromString), so responses like{"id":"123"}bind to numeric members.What is the current behavior?
Previously Refit had no streaming response support, always required leading-slash relative paths with Refit-style base-address joining, always threw on an unmatched route placeholder, always serialized request bodies asynchronously (which can never use the source-gen fast-path), and used strict number handling on the default serializer.
Closes #1299
Closes #1968
Closes #1803 (and consolidates #1358)
Closes #2022
What might this PR break?
The default
System.Text.Jsonserializer now reads numbers from JSON strings (NumberHandling = AllowReadingFromString). Writing is unchanged. Opt back out with:Everything else is additive and opt-in (defaults preserve current behaviour).
Checklist
mainbranchAdditional information
Why these approaches:
IAsyncEnumerable<T>is generated inline, with no reflection on the hot path. The generator emits a directGeneratedRequestRunner.StreamAsync<T>call with the request constructed in source (newReturnTypeInfo.AsyncEnumerable), the same approach used forTask<T>. The reflection request-builder remains only as the fallback for shapes that cannot be generated inline (dynamic routes, body/query objects, generic methods). This keeps allocations and dispatch cost minimal for streaming, which is the whole point of the feature.DeserializeAsyncEnumerable(topLevelValues: true)for JSON Lines; older TFMs use a pooled UTF-8 line reader.SerializeAsync(Stream)andSerializeAsync(PipeWriter)both use the metadata path; only the synchronous primitives (SerializeToUtf8Bytes,Serialize(Utf8JsonWriter)) hit the generated fast-path. Refit's defaultJsonContentusesSerializeAsync(Stream), so it can never use the fast-path, hence the opt-inBuffered/Streamedmodes and the converter-freeGetFastPathJsonSerializerOptions()(Refit's default converters andNumberHandlingalso disable the fast-path). A benchmark shows the fast-path is roughly 1.8x to 2x faster than the default path.RequestBodySerializationModeenum rather than stacked booleans, because the three states (async default, sync buffered, sync streamed) are mutually exclusive.PublicAPI.Shipped.txt(the project ships continuously).