Skip to content

break: add IAsyncEnumerable streaming and opt-in URL, route and JSON serialization modes - #2157

Merged
glennawatson merged 4 commits into
mainfrom
glennawatson/iasyncenumeerable
Jun 23, 2026
Merged

glennawatson merged 4 commits into
mainfrom
glennawatson/iasyncenumeerable

Conversation

@glennawatson

@glennawatson glennawatson commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

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 returning IAsyncEnumerable<T> and Refit reads the response with ResponseHeadersRead and yields items as they arrive. The frame format is auto-detected from the content type: application/jsonl / application/x-ndjson / application/x-jsonlines is read as JSON Lines, anything else as a single streamed JSON array. Backed by the new IStreamingContentSerializer capability (implemented by SystemTextJsonContentSerializer).
  • Opt-in RFC 3986 / HttpClient-style URL resolution. RefitSettings.UrlResolution = UrlResolutionMode.Rfc3986 combines the base address and relative path with System.Uri rules (a leading slash replaces the base path; no leading slash appends) and relaxes the leading-slash requirement. Defaults to RefitLegacy, so existing behaviour is unchanged.
  • Opt-in RefitSettings.AllowUnmatchedRouteParameters. When set, a route placeholder with no matching argument is left in the URL verbatim (e.g. {version:apiVersion}) for a DelegatingHandler to rewrite, instead of throwing.
  • Fast-path JSON serialization for request bodies. RefitSettings.RequestBodySerialization (Buffered or Streamed) serializes JSON bodies synchronously so the System.Text.Json source-generated fast-path engages, Buffered sends a ByteArrayContent with Content-Length, Streamed writes through a Utf8JsonWriter for large uploads. SystemTextJsonContentSerializer.GetFastPathJsonSerializerOptions() returns a fast-path-eligible options set (no converters, no NumberHandling).
  • Numbers can be read from JSON strings by default (NumberHandling = AllowReadingFromString), so responses like {"id":"123"} bind to numeric members.
  • Tests, BenchmarkDotNet benchmarks (including EventPipe CPU/alloc profiles) and README sections were added for all of the above.

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.Json serializer now reads numbers from JSON strings (NumberHandling = AllowReadingFromString). Writing is unchanged. Opt back out with:

var options = SystemTextJsonContentSerializer.GetDefaultJsonSerializerOptions();
options.NumberHandling = JsonNumberHandling.Strict;
var settings = new RefitSettings(new SystemTextJsonContentSerializer(options));

Everything else is additive and opt-in (defaults preserve current behaviour).

Checklist

  • I have read the Contribute guide
  • Tests have been added or updated (for bug fixes / features)
  • Docs have been added or updated (for bug fixes / features)
  • Changes target the main branch
  • PR title follows Conventional Commits

Additional information

Why these approaches:

  • IAsyncEnumerable<T> is generated inline, with no reflection on the hot path. The generator emits a direct GeneratedRequestRunner.StreamAsync<T> call with the request constructed in source (new ReturnTypeInfo.AsyncEnumerable), the same approach used for Task<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.
  • Streaming format is auto-detected rather than configured, so it "just works" for both standard JSON arrays and JSON Lines APIs. Per-TFM, .NET 9+ uses DeserializeAsyncEnumerable(topLevelValues: true) for JSON Lines; older TFMs use a pooled UTF-8 line reader.
  • The fast-path is synchronous-only. We verified empirically (including on .NET 9) that SerializeAsync(Stream) and SerializeAsync(PipeWriter) both use the metadata path; only the synchronous primitives (SerializeToUtf8Bytes, Serialize(Utf8JsonWriter)) hit the generated fast-path. Refit's default JsonContent uses SerializeAsync(Stream), so it can never use the fast-path, hence the opt-in Buffered/Streamed modes and the converter-free GetFastPathJsonSerializerOptions() (Refit's default converters and NumberHandling also disable the fast-path). A benchmark shows the fast-path is roughly 1.8x to 2x faster than the default path.
  • A single RequestBodySerializationMode enum rather than stacked booleans, because the three states (async default, sync buffered, sync streamed) are mutually exclusive.
  • RFC resolution and unmatched route parameters are opt-in enums/flags so existing consumers are unaffected; the URL joining was centralized into one helper used by both the reflection and generated request paths.
  • New public API is added to PublicAPI.Shipped.txt (the project ships continuously).

…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

codecov Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.95082% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.65%. Comparing base (8b70ca1) to head (91a6ba4).

Files with missing lines Patch % Lines
src/Refit/RequestExecutionHelpers.cs 94.87% 0 Missing and 2 partials ⚠️
src/Refit/GeneratedRequestRunner.cs 95.23% 0 Missing and 1 partial ⚠️
...rc/Refit/RequestBuilderImplementation.Execution.cs 94.11% 0 Missing and 1 partial ⚠️
src/Refit/SystemTextJsonContentSerializer.cs 98.95% 0 Missing and 1 partial ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

- 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
@sonarqubecloud

Copy link
Copy Markdown

@glennawatson
glennawatson merged commit 3881cc6 into main Jun 23, 2026
13 checks passed
@glennawatson
glennawatson deleted the glennawatson/iasyncenumeerable branch June 23, 2026 00:52
@Trimatix

Copy link
Copy Markdown

Wow, huge PR! fantastic changes, thank you so much :)

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

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.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Jul 9, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

3 participants