コード例 #1
0
        IRequestClient <TRequest, TResponse> IRequestClientFactory <TRequest, TResponse> .CreateRequestClient(ConsumeContext consumeContext,
                                                                                                              TimeSpan?timeout, TimeSpan?timeToLive, Action <SendContext <TRequest> > callback)
        {
            Action <SendContext <TRequest> > actualCallback = null;

            if (_callback != null)
            {
                if (callback != null)
                {
                    actualCallback = x =>
                    {
                        _callback(x);
                        callback(x);
                    }
                }
                ;
                else
                {
                    actualCallback = _callback;
                }
            }
            else if (callback != null)
            {
                actualCallback = callback;
            }

            RequestTimeout requestTimeout = timeout ?? RequestTimeout.None;

            var client = _destinationAddress == null
                ? _clientFactory.CreateRequestClient <TRequest>(consumeContext, requestTimeout)
                : _clientFactory.CreateRequestClient <TRequest>(consumeContext, _destinationAddress, requestTimeout);

            return(new MessageRequestClient <TRequest, TResponse>(client, timeToLive ?? _timeToLive, actualCallback));
        }
コード例 #2
0
        public async Task <Guid> DispatchAsync <TCommand>(TCommand command) where TCommand : class, ICommand
        {
            IValidator <TCommand> validator = _context.GetService <IValidator <TCommand> >();

            if (validator.IsNotNull())
            {
                ValidationResult validationResult = await validator.ValidateAsync(command);

                if (!validationResult.IsValid)
                {
                    throw new ValidationException(validationResult.Errors);
                }
            }

            command.CorrelationId = _guidService.New;

            IRequestClient <TCommand> client = _clientFactory.CreateRequestClient <TCommand>(new Uri("queue:commands"), TimeSpan.FromMinutes(10));

            MassTransit.Response <FWTL.Common.Cqrs.Responses.Response> response = await client.GetResponse <FWTL.Common.Cqrs.Responses.Response>(command);

            if (response.Message.StatusCode == HttpStatusCode.BadRequest)
            {
                throw new AppValidationException(response.Message.Errors);
            }

            if (response.Message.StatusCode == HttpStatusCode.InternalServerError)
            {
                throw new InvalidOperationException(response.Message.Id.ToString());
            }

            return(response.Message.Id);
        }
コード例 #3
0
        async Task <IMessageClient> CreateMessageClient <T>(Type messageType, CancellationToken cancellationToken)
            where T : class
        {
            var messageClient = new MessageClient <T>(this);

            var handle = _consumePipeConnector.ConnectInstance(messageClient);

            try
            {
                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Requesting Link to {0} (client-id: {1})", TypeMetadataCache <T> .ShortName, ClientId);
                }

                var request = _clientFactory.CreateRequestClient <Link <T> >().Create(new { ClientId }, cancellationToken);

                var response = await request.GetResponse <Up <T> >().ConfigureAwait(false);

                return(messageClient);
            }
            catch (Exception)
            {
                handle.Disconnect();
                throw;
            }
        }
コード例 #4
0
ファイル: QueryDispatcher.cs プロジェクト: FWTL/Auth
        public async Task <TResult> DispatchAsync <TQuery, TResult>(TQuery query)
            where TQuery : class, IQuery
        {
            //await TraitValidationAsync<TQuery, IPagingTrait>(query);

            var validator = _context.GetService <IValidator <TQuery> >();

            if (validator.IsNotNull())
            {
                var validationResult = await validator.ValidateAsync(query);

                if (!validationResult.IsValid)
                {
                    throw new ValidationException(validationResult.Errors);
                }
            }

            var client   = _clientFactory.CreateRequestClient <TQuery>(new Uri("queue:queries"), TimeSpan.FromMinutes(10));
            var response = await client.GetResponse <Common.Cqrs.Responses.Response <TResult> >(query);

            if (response.Message.StatusCode == HttpStatusCode.BadRequest)
            {
                throw new AppValidationException(response.Message.Errors);
            }

            if (response.Message.StatusCode == HttpStatusCode.InternalServerError)
            {
                throw new InvalidOperationException(response.Message.Id.ToString());
            }

            return(response.Message.Result);
        }
コード例 #5
0
ファイル: Request_Specs.cs プロジェクト: napstar/MassTransit
        public async Task Setup()
        {
            _clientFactory = await Bus.ConnectClientFactory(TestTimeout);

            _requestClient = _clientFactory.CreateRequestClient <PingMessage>(InputQueueAddress, TestTimeout);

            _response = _requestClient.GetResponse <PongMessage>(new PingMessage());
        }
コード例 #6
0
 public MassTransitHubLifetimeManager(IPublishEndpoint publishEndpoint,
                                      IClientFactory clientFactory,
                                      IHubProtocolResolver hubProtocolResolver)
 {
     _publishEndpoint = publishEndpoint;
     _groupManagementRequestClient = clientFactory.CreateRequestClient <GroupManagement <THub> >(TimeSpan.FromSeconds(20));
     _protocols = hubProtocolResolver.AllProtocols;
 }
コード例 #7
0
        public async Task Link(CancellationToken cancellationToken)
        {
            LogContext.Debug?.Log("Linking: {ClientId} {MessageType}", ClientId, TypeMetadataCache <TMessage> .ShortName);

            var client = _clientFactory.CreateRequestClient <Link <TMessage> >();

            var response = await client.GetResponse <Up <TMessage> >(new { ClientId }, cancellationToken).ConfigureAwait(false);

            var serviceAddress = response.Message.Service.ServiceAddress;

            var instance = response.Message.Instance;

            var instanceContext = await _instanceCache.GetOrAdd(instance.InstanceId, instance).ConfigureAwait(false);

            _distribution.Add(instanceContext);

            LogContext.Debug?.Log("Linked: {ClientId} {MessageType} {ServiceAddress}", ClientId, TypeMetadataCache <TMessage> .ShortName, serviceAddress);

            _serviceAddress.TrySetResult(serviceAddress);
        }
コード例 #8
0
        public async Task <CommandResponse> SendAsync <TCommand>(object command, CancellationToken cancellationToken = default)
            where TCommand : class, ICommand
        {
            try
            {
                var client   = _clientFactory.CreateRequestClient <TCommand>(_timeOut);
                var request  = client.Create(command, cancellationToken);
                var response = await request.GetResponse <CommandResponse>();

                return(response.Message);
            }
            catch (RequestTimeoutException ex)
            {
                throw new TimeoutException(
                          string.Format(
                              "The request timed out after {0} seconds.", _timeOut.Seconds), ex);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #9
0
ファイル: QueryDispatcher.cs プロジェクト: FWTL/API
        public async Task <TResult> DispatchAsync <TQuery, TResult>(TQuery command)
            where TQuery : class, IQuery
        {
            var validator = _context.GetService <IValidator <TQuery> >();

            if (validator.IsNotNull())
            {
                var validationResult = validator.Validate(command);
                if (!validationResult.IsValid)
                {
                    throw new ValidationException(validationResult.Errors);
                }
            }

            var client   = _clientFactory.CreateRequestClient <TQuery>(new Uri("queue:queries"), TimeSpan.FromMinutes(10));
            var response = await client.GetResponse <Common.Commands.Response <TResult> >(command);

            if (response.Message.Errors.Any())
            {
                throw new AppValidationException(response.Message.Errors);
            }

            return(response.Message.Result);
        }
コード例 #10
0
        public async Task <Guid> DispatchAsync <TCommand>(TCommand command) where TCommand : class, ICommand
        {
            var validator = _context.GetService <IValidator <TCommand> >();

            if (validator.IsNotNull())
            {
                var validationResult = validator.Validate(command);
                if (!validationResult.IsValid)
                {
                    throw new ValidationException(validationResult.Errors);
                }
            }

            var client =
                _clientFactory.CreateRequestClient <TCommand>(new Uri("queue:commands"), TimeSpan.FromMinutes(10));
            var response = await client.GetResponse <Response>(command);

            if (response.Message.Errors.Any())
            {
                throw new AppValidationException(response.Message.Errors);
            }

            return(response.Message.Id);
        }
コード例 #11
0
        public void ConfigureServices(IServiceCollection services)
        {
            ILogger logger = InitLogger(services);

            IMongoDatabase mongodb = InitMongoDb();

            ConnectionMultiplexer redisMultiplexer = InitRedis();

            IConnection rabbitMqConn = InitRabbitMqConn();

            IBusControl    massTransitBus           = InitMassTransit();
            IClientFactory massTransitClientFactory = massTransitBus.CreateClientFactory();


            #region Various

            //ITokenExtractor
            services.AddTransient(typeof(ITokenExtractor), (serviceProvider) =>
            {
                return(new TokenExtractor(_rTokenConfig, new SymmetricKeyProvider(_rTokenKeyConfig)));
            });

            #endregion

            #region Commands

            //IGenerateRefreshTokenCommand
            services.AddTransient(typeof(IGenerateRefreshTokenCommand), (serviceProvider) =>
            {
                IMongoCollection <AccountRTokenInfo> rtokensRepo = mongodb.GetCollection <AccountRTokenInfo>(_accountRTokensCollectionConfig.Name);

                return(new GenerateRefreshTokenCommand(_rTokenConfig,
                                                       new SymmetricKeyProvider(_rTokenKeyConfig),
                                                       new GuidBasedSecretGenerator(),
                                                       rtokensRepo,
                                                       logger));
            });

            //IGenerateShortTokenCommand
            services.AddTransient(typeof(IGenerateShortTokenCommand), (serviceProvider) =>
            {
                var revokedTokensRedisCollectionConfigs         = new RedisCollectionConfig(_config.GetSection("redis").GetSection("revokedTokensCollection"));
                RedisCachedRepo <string> revokedTokensRedisRepo = new RedisCachedRepo <string>(redisMultiplexer.GetDatabase(), revokedTokensRedisCollectionConfigs.CollectionName, new DefaultSerializer(), logger);

                return(new GenerateShortTokenCommand(new TokenExtractor(_rTokenConfig, new SymmetricKeyProvider(_rTokenKeyConfig)),
                                                     revokedTokensRedisRepo,
                                                     new SymmetricKeyProvider(_sTokenKeyConfig),
                                                     new GuidBasedSecretGenerator(),
                                                     _sTokenConfig,
                                                     logger));
            });

            //IRevokeAllTokensForAccountCommand
            services.AddTransient(typeof(IRevokeAllTokensForAccountCommand), (serviceProvider) =>
            {
                IMongoCollection <AccountRTokenInfo> rtokensRepo = mongodb.GetCollection <AccountRTokenInfo>(_accountRTokensCollectionConfig.Name);

                var revokedTokensRedisCollectionConfigs         = new RedisCollectionConfig(_config.GetSection("redis").GetSection("revokedTokensCollection"));
                RedisCachedRepo <string> revokedTokensRedisRepo = new RedisCachedRepo <string>(redisMultiplexer.GetDatabase(), revokedTokensRedisCollectionConfigs.CollectionName, new DefaultSerializer(), logger);

                var command = new RevokeAllTokensForAccountCommand(rtokensRepo, logger);


                var exchangeConfigs = new RabbitMqExchangeConfigs(_config.GetSection("rabbitMq").GetSection("refreshTokenRevokedEventExchange"));
                command.AddSubsciber(new RabbitMqEventPublisher <RefreshTokenRevokedEvent>(
                                         new RabbitMqProducer <RefreshTokenRevokedEvent>(rabbitMqConn, exchangeConfigs, logger),
                                         logger));

                command.AddSubsciber(new RevokedTokenRedisCacher(revokedTokensRedisRepo, logger));
                return(command);
            });

            //IRevokeTokenCommand
            services.AddTransient(typeof(IRevokeTokenCommand), (serviceProvider) =>
            {
                IMongoCollection <AccountRTokenInfo> rtokensRepo = mongodb.GetCollection <AccountRTokenInfo>(_accountRTokensCollectionConfig.Name);
                var revokedTokensRedisCollectionConfigs          = new RedisCollectionConfig(_config.GetSection("redis").GetSection("revokedTokensCollection"));

                RedisCachedRepo <string> revokedTokensRedisRepo = new RedisCachedRepo <string>(redisMultiplexer.GetDatabase(), revokedTokensRedisCollectionConfigs.CollectionName, new DefaultSerializer(), logger);

                var command = new RevokeTokenCommand(rtokensRepo, logger);

                var exchangeConfigs = new RabbitMqExchangeConfigs(_config.GetSection("rabbitMq").GetSection("refreshTokenRevokedEventExchange"));
                command.AddSubsciber(new RabbitMqEventPublisher <RefreshTokenRevokedEvent>(
                                         new RabbitMqProducer <RefreshTokenRevokedEvent>(rabbitMqConn, exchangeConfigs, logger),
                                         logger));

                command.AddSubsciber(new RevokedTokenRedisCacher(revokedTokensRedisRepo, logger));

                return(command);
            });

            #endregion

            #region Queries

            //IGetAllTokensForAccountQuery
            services.AddTransient(typeof(IGetAllTokensForAccountQuery), (serviceProvider) =>
            {
                IMongoCollection <AccountRTokenInfo> rtokensRepo = mongodb.GetCollection <AccountRTokenInfo>(_accountRTokensCollectionConfig.Name);
                return(new GetAllTokensForAccountQuery(rtokensRepo, logger));
            });

            #endregion

            #region MassTransit

            services.AddTransient(typeof(IRequestClient <UserClaimsRequest>), (serviceProvider) =>
            {
                var massTransitChannelName = _config.GetSection("rabbitMq").GetSection("getUserClaimsMassTransitChannel")["Name"];
                var requestClient          = massTransitClientFactory.CreateRequestClient <UserClaimsMQRequest>(new Uri($"rabbitmq://{_rabbitmqConfigs.Host}/{massTransitChannelName}"));
                return(requestClient);
            });

            services.AddTransient(typeof(IRequestClient <AuthValidationRequest>), (serviceProvider) =>
            {
                var massTransitChannelName = _config.GetSection("rabbitMq").GetSection("validateCredentialsMassTransitChannel")["Name"];
                var requestClient          = massTransitClientFactory.CreateRequestClient <AuthValidationMQRequest>(new Uri($"rabbitmq://{_rabbitmqConfigs.Host}/{massTransitChannelName}"));
                return(requestClient);
            });

            #endregion

            #region Mvc Framework

            var mvcBuilder = services.AddMvc();
            MvcConfigProvider mvcConfigProvider = new MvcConfigProvider();
            mvcBuilder.AddMvcOptions(mvcConfigProvider.GetMvcOptionsConfigurer())
            .AddJsonOptions(mvcConfigProvider.GetJsonOptionsConfigurer());
            services.AddSession();
            #endregion
        }
コード例 #12
0
 public IRequestClient <T> CreateRequestClient <T>(Uri destinationAddress, RequestTimeout timeout)
     where T : class
 {
     return(_clientFactory.CreateRequestClient <T>(destinationAddress, timeout));
 }
 public Task <IRequestClient <T> > GetRequestClient <T>(TimeSpan settingsRequestTimeout)
     where T : class
 {
     return(Task.FromResult(_clientFactory.CreateRequestClient <T>(_targetEndpointAddress, settingsRequestTimeout)));
 }
コード例 #14
0
 public HubLifetimeScope(IPublishEndpoint bus, IClientFactory clientFactory)
 {
     PublishEndpoint = bus;
     RequestClient   = clientFactory.CreateRequestClient <GroupManagement <THub> >();
 }
コード例 #15
0
ファイル: Request_Specs.cs プロジェクト: napstar/MassTransit
        public async Task Setup()
        {
            _clientFactory = await Bus.CreateReplyToClientFactory();

            _requestClient = _clientFactory.CreateRequestClient <PingMessage>(InputQueueAddress, TestTimeout);
        }
コード例 #16
0
 IRequestClient <T> IClientFactory.CreateRequestClient <T>(RequestTimeout timeout)
 {
     return(_clientFactory.CreateRequestClient <T>(timeout));
 }
コード例 #17
0
        public async Task Setup()
        {
            _clientFactory = await Bus.CreateReplyToClientFactory();

            _requestClient = _clientFactory.CreateRequestClient <PingMessage>(InputQueueAddress, TimeSpan.FromSeconds(8));
        }