Esempio n. 1
0
        public async Task <T> AuthorizeAndExecute <T>(Func <SwiftAuthData, Task <T> > func) where T : SwiftBaseResponse, new()
        {
            T resp = new T();

            var retrier = RetryPolicy <string> .Create()
                          .WithSteps(AuthManager.GetEndpoints())
                          .WithCount(_retryCount)
                          .WithCountPerStep(_retryPerEndpointCount);

            var isSuccessful = await retrier.DoAsync(async (endpoint) =>
            {
                var auth = await GetOrSetAuthentication(endpoint).ConfigureAwait(false);

                if (auth == null)
                {
                    // dead proxy node maybe? try with next
                    return(false);
                }

                resp = await func(auth).ConfigureAwait(false);

                // authenticate again on same proxy node
                if (resp.StatusCode == HttpStatusCode.Unauthorized)
                {
                    if (_logger != null)
                    {
                        _logger.LogUnauthorizedError(auth.AuthToken, endpoint);
                    }

                    auth = await SetAuthentication(endpoint).ConfigureAwait(false);

                    resp = await func(auth).ConfigureAwait(false);
                }

                // try next proxy node
                if (resp.StatusCode == HttpStatusCode.BadRequest)
                {
                    return(false);
                }

                if (IsSuccessStatusCode(resp.StatusCode))
                {
                    return(true);
                }

                // unknown status code => try next proxy node
                return(false);
            }).ConfigureAwait(false);

            resp.IsSuccess = isSuccessful;

            // cache new endpoints order
            AuthManager.SetEndpoints(retrier.GetSteps());

            return(resp);
        }