Ejemplo n.º 1
0
        public async Task End2End()
        {
            var testInstance = new AsyncExpiringLazy <TokenResponse>(async metadata =>
            {
                await Task.Delay(1000);
                return(new ExpirationMetadata <TokenResponse>
                {
                    Result = new TokenResponse
                    {
                        AccessToken = Guid.NewGuid().ToString()
                    }, ValidUntil = DateTimeOffset.UtcNow.AddSeconds(2)
                });
            });

            // 1. check if value is created - shouldn't
            Assert.False(await testInstance.IsValueCreated());

            // 2. fetch lazy expiring value
            var token = await testInstance.Value();

            // 3a. verify it is created now
            Assert.True(await testInstance.IsValueCreated());

            // 3b. verify it is not null
            Assert.NotNull(token.AccessToken);

            // 4. fetch the value again. Since it's lifetime is 2 seconds, it should be still the same
            var token2 = await testInstance.Value();

            Assert.Same(token, token2);

            // 5. sleep for 2 seconds to let the value expire
            await Task.Delay(2000);

            // 6a. verify the value expired
            Assert.False(await testInstance.IsValueCreated());

            // 6b. fetch again
            var token3 = await testInstance.Value();

            // 7. verify we now have a new (recreated) value - as the previous one expired
            Assert.NotSame(token2, token3);

            // 8. invalidate the value manually before it has a chance to expire
            await testInstance.Invalidate();

            // 9. check if value is created - shouldn't anymore
            Assert.False(await testInstance.IsValueCreated());
        }
Ejemplo n.º 2
0
 public static Task <IClientSessionHandle> GetAsync(IMongoClient client, ClientSessionOptions options, double expiringInSeconds, CancellationToken ctok = default)
 {
     _client            = client;
     _options           = options;
     _expiringInSeconds = expiringInSeconds;
     _ctok = ctok;
     return(ExpiringSessionLazy.Value());
 }
        private void CreateBayeuxClient()
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException("Cannot create connection when disposed");
            }

            _logger.LogDebug("Creating {name} ...", nameof(BayeuxClient));

            var accessToken = _tokenResponse.Value().Result;

            // only need the scheme and host, strip out the rest
            var serverUri = new Uri(accessToken.InstanceUrl);
            var endpoint  = $"{serverUri.Scheme}://{serverUri.Host}{_options.CometDUri}";

            var headers = new NameValueCollection {
                { nameof(HttpRequestHeader.Authorization), $"{_options.TokenType} {accessToken.AccessToken}" }
            };

            // Salesforce socket timeout during connection(CometD session) = 110 seconds
            var options = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)
            {
                { ClientTransport.TIMEOUT_OPTION, _options.ReadTimeOut ?? _readTimeOut },
                { ClientTransport.MAX_NETWORK_DELAY_OPTION, _options.ReadTimeOut ?? _readTimeOut }
            };

            _clientTransport = new LongPollingTransport(options, headers);

            _bayeuxClient = new BayeuxClient(endpoint, _clientTransport);

            // adds logging and also raises an event to process reconnection to the server.
            _errorExtension = new ErrorExtension();
            _errorExtension.ConnectionError     += ErrorExtension_ConnectionError;
            _errorExtension.ConnectionException += ErrorExtension_ConnectionException;
            _errorExtension.ConnectionMessage   += ErrorExtension_ConnectionMessage;
            _bayeuxClient.AddExtension(_errorExtension);

            _replayIdExtension = new ReplayExtension();
            _bayeuxClient.AddExtension(_replayIdExtension);

            _logger.LogDebug("{name} was created...", nameof(BayeuxClient));
        }
        public async Task <ClaimsPrincipal> ValidateToken(string token)
        {
            var webkeys = await _asyncExpiringLazy.Value();

            var parameters =
                new TokenValidationParameters
            {
                ValidIssuer       = $"https://{_configuration["Auth0:Domain"]}/",
                ValidAudiences    = new[] { _configuration["Auth0:Audience"] },
                IssuerSigningKeys = webkeys.SigningKeys
            };

            var handler = new JwtSecurityTokenHandler();

            var principal = handler.ValidateToken(token, parameters, out var securityToken);

            _logger.LogDebug("Security Token: {@securityToken}", securityToken);

            return(principal);
        }
        /// <inheritdoc/>
        public async Task <int> CountQueryAsync(
            string queryString,
            bool queryAll = false,
            CancellationToken cancellationToken = default)
        {
            var mContext = new Context
            {
                [_policyContextMethod] = nameof(CountQueryAsync)
            };

            return(await _policy.ExecuteAsync(
                       async (context, token) =>
            {
                var client = _forceClient.Value().Result;
                return await client.CountQuery(queryString, queryAll);
            },
                       mContext,
                       cancellationToken));
        }