respawnsive / apizr Goto Github PK
View Code? Open in Web Editor NEWRefit based web api client management, but resilient (retry, connectivity, cache, auth, log, priority, etc...)
Home Page: https://www.apizr.net
License: Apache License 2.0
Refit based web api client management, but resilient (retry, connectivity, cache, auth, log, priority, etc...)
Home Page: https://www.apizr.net
License: Apache License 2.0
Apizr v4-p1 may throw an exception when no connectivity handler has been provided
Hi,JeremyBP !
I used apizr for production builds in my xamarin ,when linker setting: "AndroidLinkMode = SdkOnly" , an error occurred at runtime。
called ArgumentException --> services.UseApizrFor();
System.ArgumentException: 'Your Apizr manager class must inherit from IApizrManager generic interface or derived'
I think the apizr assembly should be removed by linker,do you provide preserve attribute , or falseflag to solve the issue ?
I have setup Caching as follows:
[Post("/site/SRConsAPI?method=getSingleSignOnToken"), Cache(CacheMode.GetOrFetch, "00:30:00")]
Task<singleSignOnTokenResult> GetSingleSignOnTokenAsync(
[AliasAs("cons_id"), CacheKey] string constituentId);
Issue is when the constituentId parameter changes, the cached value based on the previous constituentId is returned.
I think the issue may arise here:
where this code returns without considering the [CacheKey].
// Did we ask for it already ?
if (_cachingMethodsSet.TryGetValue(methodToCacheData, out var methodCacheDetails))
{
// Yes we did so get saved specific details
cacheAttribute = methodCacheDetails.cacheAttribute;
cacheKey = methodCacheDetails.cacheKey;
return cacheAttribute != null && !string.IsNullOrWhiteSpace(cacheKey);
}
Here is a some client pseudo-code that will fail:
var singleSignOnTokenResult1 =
await _apizrManager.ExecuteAsync(api => api.GetSingleSignOnTokenAsync("blah1"));
var singleSignOnTokenResult2 =
await _apizrManager.ExecuteAsync(api => api.GetSingleSignOnTokenAsync("blah2"));
singleSignOnTokenResult2 equals singleSignOnTokenResult1 as its not considering the passed in argument and hence pulls the cached value from the first call.
Here is a PR which may fix the issue: #21, but consider getting rid of _cachingMethodsSet too.
I did myself my fork of the "insane" pack, but I must say you did a terrific job here and I would like to stop using my fork and start using your implementation :)
The only thing I couldn't find in the docs is the possibility to invalidate the cache of a request. In my fork I added a Boolean on each request to invalidate the cache (force a remote fetch).
This particularly important when you are doing a pull 2 refresh on mobile.
So, am I missing something or are you accepting PRs :) ?
Shiny v2.0 removed built in caching feature. It also introduced a reshaped logging feature relying on Microsoft.Extensions.Logging.
Workaround: Don't call .UseWhatever(...) from Shiny intergration package anymore but .AddWhatever(...) instead and set options fluently like caching and logging providers.
Fix: I'm working on a new release relying on Microsoft.Extensions.Logging.Abstraction to get things less specific/more generic, just like Shiny does. Caching feature should now be activated fluently with the provider of your choice (e.g. MonkeyCache or Akavache).
Caching was setup with multiple [CacheKey] as follows:
[Get("/site/CRTeamraiserAPI?method=getParticipantProgress"), Cache(CacheMode.GetOrFetch, "00:05:00")]
Task<getParticipantProgressResult> GetParticipantProgressAsync(
[AliasAs("cons_id"), CacheKey] string constituentId,
[AliasAs("fr_id"), CacheKey] string eventId);
So I anticipated that this would yield as result a cache key similar to:
GetParticipantProgressAsync(cons_id:{value}, eventId:{value})
instead it yielded a cache key that ignored the second CacheKey.
GetParticipantProgressAsync(cons_id:{value})
After panicking a bit, I figured out that the "fix" was to not use [CacheKey] at all.
I see from the code that it purposefully only gets the first CacheKey:
// There's a specific cache key with a target field!
var cacheKeyField = extractedArgument
.Value
.GetType()
.GetRuntimeFields()
.FirstOrDefault(x => x.Name.Equals(cacheKeyAttribute.PropertyName));
Having said all this I can see a use case for specifying [CacheKey]'s for a subset of the arguments in a call, like for example:
TheCall(
[CacheKey] string arg1,
[CacheKey] string arg2,
string nonChangingArgWithLongNastyValueThatWeDontWantToInfluenceTheCacheKey
);
If I've misunderstood the usage of [CacheKey], please LKM, thx.
When we call registration methods like AddApizrFor or AddApizrFor(typeof(TWebApi)) with WithMediation and/or WithOptionalMediation options, MediatR handlers as Optional handlers are not registered.
No problem with assembly scanning registration.
The following code:
services.AddApizrManagerFor<IBlackbaudSrApi>(optionsBuilder =>
optionsBuilder
.WithRefitSettings(new RefitSettings { ContentSerializer = new XmlContentSerializer() })
.WithBaseAddress(sp =>
{
var config = sp.GetService<BlackbaudConfiguration>();
return new UriBuilder(config.Header.RootUrl).Uri;
})
.AddDelegatingHandler<BlackbaudMessageSrHandler>(sp => sp.GetService<BlackbaudMessageSrHandler>())
// .WithAkavacheCacheHandler()
.WithCacheHandler<DistributedCacheHandler<string>>()
.WithLogging());
services.AddDistributedMemoryCache();
results in the following exception:
System.ArgumentNullException : Value cannot be null. (Parameter 'content')
at System.ArgumentNullException.Throw(String paramName)
at System.ArgumentNullException.ThrowIfNull(Object argument, String paramName)
at System.Net.Http.StringContent.GetContentByteArray(String content, Encoding encoding)
at System.Net.Http.StringContent..ctor(String content, Encoding encoding, String mediaType)
at Apizr.SerializationExtensions.FromJsonStringAsync[T](String str, IHttpContentSerializer contentSerializer, CancellationToken cancellationToken)
at Apizr.DistributedCacheHandler`1.GetAsync[TData](String key, CancellationToken cancellationToken)
at Apizr.ApizrManager`1.ExecuteAsync[TApiData](Expression`1 executeApiMethod, Action`1 optionsBuilder)
I think the fix is:
internal static async Task<T> FromJsonStringAsync<T>(this string str, IHttpContentSerializer contentSerializer, CancellationToken cancellationToken = default)
{
//todo: add this null protection
if (str == null)
{
return default;
}
var content = new StringContent(str, Encoding.UTF8, "application/json");
return await contentSerializer.FromHttpContentAsync<T>(content, cancellationToken);
}
Hi,
we are getting spontaneous crashes on iOS if we are using our custom DelegatingHandler. Sometimes the app is working for couple of minutes/api calls without crash and then it crashes. There is not relevant exception for this, just a SIGABRT Crash from iOS. If we hard-code our api key in the delegatinghandler, the app is working fine. Is there some misconfiguration on our side? Or is there better way to do this? Thanks.
Versions:
Maui: 8.0.40 (happens in every Maui 8> version)
Apizr: 5.4.0
Shiny.Framework: 4.1.0
Prism.DryIoc.Maui: 9.0.401-pre
Registration in Maui:
builder.Services.AddApizr(apizrRegistry => apizrRegistry .AddManagerFor<IImpressumApi>() apizrExtendedCommonOptionsBuilder => apizrExtendedCommonOptionsBuilder .WithBaseAddress(builder.Configuration.GetValue<Uri>("BaseUrl")) .AddDelegatingHandler((provider) => new XApiKeyAuthenticationHandler(provider.GetRequiredService<ISecureStorage>())) .WithAkavacheCacheHandler() .WithExCatching(OnException, letThrowOnExceptionWithEmptyCache: false) .WithLogging( #if DEBUG HttpTracerMode.Everything, HttpMessageParts.All, LogLevel.Trace, LogLevel.Information, LogLevel.Critical #else HttpTracerMode.ExceptionsOnly, HttpMessageParts.ResponseAll, Microsoft.Extensions.Logging.LogLevel.Trace, Microsoft.Extensions.Logging.LogLevel.Information, Microsoft.Extensions.Logging.LogLevel.Critical #endif ) .WithConnectivityHandler<IConnectivity>(connectivity => connectivity.NetworkAccess == NetworkAccess.Internet));
DelegatingHandler:
`public class XApiKeyAuthenticationHandler : DelegatingHandler
{
public XApiKeyAuthenticationHandler(ISecureStorage secureStorage) : this(secureStorage, new HttpClientHandler())
{
}
public XApiKeyAuthenticationHandler(ISecureStorage secureStorage, HttpMessageHandler innerHandler) : base(innerHandler)
{
SecureStorage = secureStorage;
}
protected ISecureStorage SecureStorage { get; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var identityKey = await SecureStorage.GetAsync(AppConstants.IdentityKey);
if (!string.IsNullOrWhiteSpace(identityKey))
{
request.Headers.Add("X-Identity-Key", identityKey);
}
return await base.SendAsync(request, cancellationToken);
}
}`
Hello,
I have an API that is called every few seconds and the log is full of these messages:
[Apizr - AuthenticationHandler`2: Authorization required with scheme Bearer]
[Apizr - AuthenticationHandler`2: Saved token will be used]
[Apizr - AuthenticationHandler`2: Authorization header has been set]
[Apizr - AuthenticationHandler`2: Sending request with authorization header...]
[Apizr - AuthenticationHandler`2: Token saved]
Can the spots where the logger is called at least be guarded by if (apizrVerbosity >= ApizrLogLevel.Low)
?
thanks
Hi, @JeremyBP ,I use Apizr 1.9.0,I have an API request "GetPermissionRecordSettingAsync",when I try to send the same content twice (in case of timeout or similar), I get an "ObjectDisposedException" as follows:
[Get("/auth/user/permission/{userId}")] Task<APIResult<IList<PermissionRecordQuery>>> GetPermissionRecordSettingAsync([CacheKey] int store, int userId, CancellationToken calToken = default);
"exception": { "type": "Apizr.ApizrException
1[[DCMS.Client.Services.APIResult1[[System.Collections.Generic.IList
1[[DCMS.Client.Models.Users.PermissionRecordQuery, DCMS.Client, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], DCMS.Client, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null]]",
"message": "Cannot access a disposed object.\nObject name: 'System.Net.Http.HttpConnection+HttpConnectionResponseContent'.",
"stackTrace": " at Apizr.ApizrManager1[TWebApi].ExecuteAsync[TResult] (System.Linq.Expressions.Expression
1[TDelegate] executeApiMethod, System.Threading.CancellationToken cancellationToken, Fusillade.Priority priority) [0x005e4] in :0 \n at DCMS.Client.Services.UserService.GetPermissionRecordSettingAsync (System.Action1[T] action, System.Threading.CancellationTokenSource cts) [0x0013c] in <c6379d2ab81547ef80e263b722f90018>:0 ", "innerExceptions": [ { "type": "System.ObjectDisposedException", "message": "Cannot access a disposed object.\nObject name: 'System.Net.Http.HttpConnection+HttpConnectionResponseContent'.", "stackTrace": " at System.Net.Http.HttpContent.CheckDisposed () [0x00013] in <92d3ef97a77047c9ab125ae979975a02>:0 \n at System.Net.Http.HttpContent.ReadAsStreamAsync () [0x00000] in <92d3ef97a77047c9ab125ae979975a02>:0 \n at Refit.NewtonsoftJsonContentSerializer.DeserializeAsync[T] (System.Net.Http.HttpContent content) [0x00027] in <ea3d892ff3f046868a691cc71dcbabbf>:0 \n at Refit.RequestBuilderImplementation.DeserializeContentAsync[T] (System.Net.Http.HttpResponseMessage resp, System.Net.Http.HttpContent content) [0x002d5] in <ea3d892ff3f046868a691cc71dcbabbf>:0 \n at Refit.RequestBuilderImplementation+<>c__DisplayClass14_0
2[T,TBody].b__0 (System.Net.Http.HttpClient client, System.Threading.CancellationToken ct, System.Object[] paramList) [0x003a5] in :0 \n at Apizr.ApizrManager1[TWebApi].ExecuteAsync[TResult] (System.Linq.Expressions.Expression
1[TDelegate] executeApiMethod, System.Threading.CancellationToken cancellationToken, Fusillade.Priority priority) [0x00528] in :0 ",
"wrapperSdkName": "appcenter.xamarin"
}
],
"wrapperSdkName": "appcenter.xamarin"
}`
Exception:
Apizr may throw this exception when using Prism.Magician with Fusillade priority management activated: The 'InnerHandler' property must be null. 'DelegatingHandler' instances provided to 'HttpMessageHandlerBuilder' must not be reused or cached.
Handler: 'Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler'
Workaround
Turn it off with the WebApi attribute while waiting for a fix or if you do need/want to play with it, change from Prism.Magician to the Prism.Container.Extensions approach.
Actually, I'm thinking about outsourcing Fusillade and Polly from Apizr core package to Apizr.Integrations packages to get something fully modular.
I have defined three interfaces, as follows:
[Policy("TransientHttpError")]
[WebApi(GlobalSettings.BaseEndpoint + "api/v3/dcms/news", isAutoRegistrable: false), Trace]
public interface INewsApi
{
[Get("/topnews/0/6")]
[Headers("Authorization: Bearer")]
Task<APIResult<IList>> GetTopNewsAsync([CacheKey] int storeId, CancellationToken calToken = default);
}
[WebApi(GlobalSettings.BaseEndpoint + "api/v3/dcms/auth/user", isAutoRegistrable: false), Trace]
public interface IAuthorizationApi
{
[Get("/bearer/{store}/{userid}")]
[Headers("Authorization: Bearer")]
Task AuthBearerAsync(int store, int userid);
}
Register as follows in Startup : PrismStartup
//(1)
services.UseApizrFor(ob => ob
.WithHttpTracing(HttpTracer.HttpMessageParts.All)
.WithCacheHandler()
.WithAuthenticationHandler(settings => settings.Token, OnRefreshToken));
//(2)
services.UseApizrFor(ob => ob
.WithHttpTracing(HttpTracer.HttpMessageParts.All)
.WithCacheHandler()
.WithAuthenticationHandler(settings => settings.Token, OnRefreshToken));
Test case as follows:
//Test
var newsServie = Shiny.ShinyHost.Resolve<IApizrManager>();
var news = await newsServie.ExecuteAsync((ct, api) => api.GetTopNewsAsync(Settings.StoreId, ct), CancellationToken.None);
// 401 Unauthorized!!
var _httpBinManager = Shiny.ShinyHost.Resolve<IApizrManager>();
var response = await _httpBinManager?.ExecuteAsync(api => api.AuthBearerAsync(Settings.StoreId, Settings.UserId)) as HttpResponseMessage;
// 200 Ok!!
When I change the order of 1 and 2, the 1 available request succeeds and 2 fails
//Test
var newsServie = Shiny.ShinyHost.Resolve<IApizrManager>();
var news = await newsServie.ExecuteAsync((ct, api) => api.GetTopNewsAsync(Settings.StoreId, ct), CancellationToken.None);
// 200 Ok!!
var _httpBinManager = Shiny.ShinyHost.Resolve<IApizrManager>();
var response = await _httpBinManager?.ExecuteAsync(api => api.AuthBearerAsync(Settings.StoreId, Settings.UserId)) as HttpResponseMessage;
// 401 Unauthorized!!
????? I need your help. Thank you very much!!!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.