Repository navigation
fix(http): keep EndpointOptions bindable in trimmed apps that use AddRefitClient or AddKiotaClient - #3267
fix(http): keep EndpointOptions bindable in trimmed apps that use AddRefitClient or AddKiotaClient#3267kazo0 wants to merge 2 commits into
Conversation
| protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | ||
| { | ||
| LastRequestUri = request.RequestUri; | ||
| return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }); |
There was a problem hiding this comment.
False positive: the response is the handler's return value; HttpClient owns and disposes it.
| catch (Exception ex) | ||
| { | ||
| Fail("AddRefitClient", $"{ex.GetType().Name}: {ex.Message}"); | ||
| } |
There was a problem hiding this comment.
Added a specific catch for the expected InvalidOperationException (Refit's "BaseAddress must be set on the HttpClient instance"). The generic fallback stays, so any other exception is reported as a FAIL instead of crashing the run before the remaining checks.
jonpryor
left a comment
There was a problem hiding this comment.
Please avoid .All.
Additionally, what I'd like to know, and what the PR description doesn't provide, is how Kiota & Refit "find" the UseNativeHandler and Url properties. Is it "only" via Reflection, or is there some other mechanism? Do they require properties for Reflection lookup, or Fields as well? Methods? Other?
| public static IServiceCollection AddKiotaClientWithEndpoint< | ||
| [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] | ||
| TClient, | ||
| [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] |
There was a problem hiding this comment.
Use of .All is very problematic; see also: unoplatform/uno@d9dcb1c
The "short and weird" version is that use of .All caused IL2026 warnings around the System.Delegate constructor, Delegate.CreateDelegate, etc.:
ILC : Trim analysis warning IL2026: Uno.Material.WinUI.GlobalStaticResources.ResourceDictionarySingleton__mergedpages_v1_c15678b9f7eb6ae0d4e176be633434fa.Get_9(Object): Using member 'System.Delegate.Delegate(Object,String)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. The target method might be removed.
ILC : Trim analysis warning IL2111: Uno.Material.WinUI.GlobalStaticResources.ResourceDictionarySingleton__mergedpages_v1_c15678b9f7eb6ae0d4e176be633434fa.Get_9(Object): Method 'System.Delegate.Delegate(Type,String)' with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. Trimmer can't guarantee availability of the requirements of the method.
It was very weird, and encountering that scenario only requires that TEndpoint contain a delegate type:
class MyEndpoint
{
public delegate void Whatever();
}
// …
ServiceCollectionExtensions.AddKiotaClientWithEndpoint<…, MyEndpoint>(…);DynamicallyAccessedMemberTypes.All should be avoided if at all possible.
Is there something "less than" .All that can be used? .PublicProperties perhaps?
There was a problem hiding this comment.
Narrowed to PublicParameterlessConstructor | PublicProperties on all four TEndpoints, including both AddClientWithEndpoint overloads in Uno.Extensions.Http. Those had to change too, or the Refit call site would raise IL2091.
On how Url/UseNativeHandler are found: Refit and Kiota never see EndpointOptions. AddClientWithEndpoint binds it with Uno.Extensions.Configuration.Internal.ConfigurationBinder.Get<TEndpoint>, which works only through reflection:
GetConstructorschecks for a public parameterless constructor, thenActivator.CreateInstancecreates the object.GetProperties(Public|NonPublic|Instance|Static|DeclaredOnly)runs on each type up theBaseTypechain. Non-public properties are listed but skipped, becauseBindNonPublicPropertiesis never set. Values are written withPropertyInfo.SetValuethrough public getters and setters.GetInterfaces()runs only to detect collections and dictionaries, which an options type isn't.
No fields, methods, events or nested types are touched. AddClientWithEndpoint then sets HttpClient.BaseAddress from options.Url, and Refit and Kiota read the base address from that HttpClient.
I reproduced your case: with a nested delegate in the endpoint type, All produced IL2026 on Delegate(Object,String) and IL2111. The narrowed flags don't. The trimming test now also covers a derived endpoint type (DerivedEndpointOptions), which fails without the annotation.
| public static IServiceCollection AddRefitClientWithEndpoint< | ||
| [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] | ||
| TInterface, | ||
| [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] |
There was a problem hiding this comment.
See prior comment about the perils of .All. Please find something narrower.
There was a problem hiding this comment.
Done, narrowed the same way here; see the reply above.
…RefitClient or AddKiotaClient AddClientWithEndpoint binds the endpoint section with ConfigurationBinder.Get<TEndpoint> and annotates TEndpoint with DynamicallyAccessedMembers(All), but AddRefitClientWithEndpoint and AddKiotaClientWithEndpoint passed their own unannotated TEndpoint through, so the trimmer could not carry the requirement to EndpointOptions (IL2091, folded into IL2104 for Refit and suppressed by RequiresUnreferencedCode for Kiota). With TrimMode=partial, the iOS Release default, Uno.Extensions.Http is trimmed, the Url and UseNativeHandler setters are removed, the section binds to an empty object, and the client has no BaseAddress: Refit throws 'BaseAddress must be set on the HttpClient instance', Kiota's BaseUrl is null. Annotate TEndpoint on both wrappers, and TInterface on the Refit ones (PublicConstructors, as AddClientWithEndpoint requires). Verified with a trimmed osx-arm64 console app: 8.0.0-dev.135 reproduces both failures; with this change both setters survive and both clients get their base address, each annotation fixing its own client independently. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Sn8GmJ41W3eBgT7866J3jV
Uno.Extensions.Http.TrimmingTests is a console app, not a VSTest assembly: trimming only happens on publish, so CI publishes it trimmed (TrimMode=partial, the iOS and Android Release mode) after the unit tests and runs it. It registers a Refit and a Kiota client from an endpoint configuration section and checks that each gets the configured base address, with a recording primary handler so no request leaves the process. Without the EndpointOptions annotations both checks fail (Refit: 'BaseAddress must be set on the HttpClient instance'; Kiota: BaseUrl null) and the app exits 1; with them both pass. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Sn8GmJ41W3eBgT7866J3jV
5580a56 to
3dc7f2e
Compare
| catch (Exception ex) | ||
| { | ||
| Fail("AddKiotaClient", $"{ex.GetType().Name}: {ex.Message}"); | ||
| } |
| public static IServiceCollection AddKiotaClientWithEndpoint< | ||
| [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] | ||
| TClient, | ||
| [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] |
There was a problem hiding this comment.
Would it be possible to move the expression DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicPropert into a named const? See e.g.
uno.extensions/src/Uno.Extensions.Core/Diagnostics/Annotations.cs
Lines 10 to 13 in d2eaae6
I don't know offhand if this assembly references Uno.Extensions.Core and has access to its internals, but if it does, you could update Annotations with:
partial static class Annotations
{
internal const DynamicallyAccessedMemberTypes EndpointRequirements =
DynamicallyAccessedMemberTypes.PublicParameterlessConstructor
| DynamicallyAccessedMemberTypes.PublicProperties
;
}Then ServiceCollectionExtensions could use [DynamicallyAccessedMembers(Annotations.EndpointRequirements)].
There was a problem hiding this comment.
This is already addressed in the current branch: the TEndpoint generic parameters in the Add*WithEndpoint overloads include DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties), so the trim-safe binding for endpoint options is in place.
|
Tick the box to add this pull request to the merge queue (same as
|
GitHub Issue (If applicable): closes #3266
PR Type
What is the current behavior?
In a trimmed Release build (iOS and Android use
TrimMode=partial, WebAssemblyfull),AddRefitClientandAddKiotaClientlose theUrlfrom their endpoint section. Refit throwsBaseAddress must be set on the HttpClient instance; Kiota'sBaseUrlis null.AddClientWithEndpointbinds the section withConfigurationBinder.Get<TEndpoint>and annotatesTEndpointwith[DynamicallyAccessedMembers], butAddRefitClientWithEndpointandAddKiotaClientWithEndpointpass an unannotatedTEndpointthrough. The trimmer cannot carry the requirement toEndpointOptions, so it removes theUrlandUseNativeHandlersetters fromUno.Extensions.Http(trimmable since it becameIsAotCompatible), and the section binds to an empty object. Details and a standalone repro are in #3266.What is the new behavior?
TEndpointis annotated[DynamicallyAccessedMembers(PublicParameterlessConstructor | PublicProperties)]onAddRefitClientWithEndpointandAddKiotaClientWithEndpoint, andTInterface[DynamicallyAccessedMembers(PublicConstructors)]onAddRefitClientandAddRefitClientWithEndpoint.AddClientWithEndpointoverloads inUno.Extensions.Httpare narrowed fromAllto the samePublicParameterlessConstructor | PublicProperties. That is everything the configuration binder touches. It creates the instance through the public parameterless constructor and binds properties with public getters and setters, walking up theBaseTypechain. It touches no fields, methods, events or nested types.Allalso kept nested types, so an endpoint type that declared a delegate dragged inIL2026/IL2111warnings onDelegate(Object,String)(reproduced; gone with the narrowed flags). Relaxing a generic parameter's requirement is not breaking for callers.src/Uno.Extensions.Http.TrimmingTests: a console app (not a VSTest assembly, since trimming only happens on publish) that registers a Refit and a Kiota client from an endpoint section and checks each gets the configured base address. It also registersAddRefitClientWithEndpointwith a derivedDerivedEndpointOptionsand checks that both the inheritedUrland a property declared on the derived type are bound. The test app itself isIsTrimmable, so that derived type is only kept by the annotation. A recording primary handler answers locally, so nothing goes to the network.stage-build-packages.ymlpublishes it trimmed after the unit tests and runs it; a non-zero exit code fails the job.Verified locally (macOS osx-arm64 for the first two rows, then on Windows win-x64 after narrowing):
main's library codeBaseAddress must be set on the HttpClient instanceBaseUrlnullTEndpointannotation removednull),IL2091backEndpointOptions)UrlPASSBefore the narrowing (with
All), against packages packed from this branch, a separate trimmed repro app passed with only Refit or only Kiota registered, so each annotation fixes its own client; the trimmedUno.Extensions.Http.dllkept both setters. The twoIL2091warnings onAddRefitClientWithEndpointare gone with the narrowed flags too (and come back when the Refit annotation is removed).PR Checklist
Other information
Not in this PR, as follow-ups:
AddRefitClientandAddRefitClientWithEndpointcallAddClientWithEndpoint, which is[RequiresUnreferencedCode]/[RequiresDynamicCode], without carrying those attributes themselves (IL2026inside the assembly), so apps get no warning at their call site, unlikeAddKiotaClient. Adding them, andIsAotCompatibleonUno.Extensions.Http.Refit, is correct but adds warnings in consuming apps.🤖 Generated with Claude Code
https://claude.ai/code/session_01Sn8GmJ41W3eBgT7866J3jV