/// <summary>
        /// Create a connection using an IEndpointResolver.
        /// </summary>
        /// <param name="endpointResolver">
        /// The endpointResolver that returns the endpoints to use for the connection attempt.
        /// </param>
        /// <param name="clientProvidedName">
        /// Application-specific connection name, will be displayed in the management UI
        /// if RabbitMQ server supports it. This value doesn't have to be unique and cannot
        /// be used as a connection identifier, e.g. in HTTP API requests.
        /// This value is supposed to be human-readable.
        /// </param>
        /// <returns>Open connection</returns>
        /// <exception cref="BrokerUnreachableException">
        /// When no hostname was reachable.
        /// </exception>
        public IConnection CreateConnection(IEndpointResolver endpointResolver, string clientProvidedName)
        {
            IConnection conn;

            try
            {
                if (AutomaticRecoveryEnabled)
                {
                    var autorecoveringConnection = new AutorecoveringConnection(this, clientProvidedName);
                    autorecoveringConnection.Init(endpointResolver);
                    conn = autorecoveringConnection;
                }
                else
                {
                    IProtocol protocol = Protocols.DefaultProtocol;
                    conn = protocol.CreateConnection(this, false, endpointResolver.SelectOne(this.CreateFrameHandler), clientProvidedName);
                }
            }
            catch (Exception e)
            {
                throw new BrokerUnreachableException(e);
            }

            return(conn);
        }
Ejemplo n.º 2
0
 internal void SetFallbackResolver(IEndpointResolver fallbackResolver, bool replace = false)
 {
     if (replace || m_FallbackResolver == null)
     {
         m_FallbackResolver = fallbackResolver;
     }
 }
Ejemplo n.º 3
0
        public void Test_ApiOnly_Disabled( )
        {
            Api api = MakeApi("address1", false);
            IEndpointResolver resolver = GetResolver( );

            Assert.Throws <EndpointNotFoundException>(() => resolver.ResolveEndpoint("address1", false));
        }
Ejemplo n.º 4
0
        public void Init(IEndpointResolver endpoints)
        {
            _endpoints = endpoints;
            IFrameHandler fh = endpoints.SelectOne(_factory.CreateFrameHandler);

            Init(fh);
        }
Ejemplo n.º 5
0
        public IActionResult Invoke(IRequestHandler requestHandler, string url)
        {
            IEndpointResolver endpointResolver = requestHandler.GetService <IEndpointResolver>();
            Endpoint          endpoint         = endpointResolver.GetEndpoint(requestHandler, url);

            if (endpoint == null)
            {
                return(null);
            }

            if (endpoint.DisallowAnonymous)
            {
                if (!requestHandler.HttpContext.User.Identity.IsAuthenticated || !this.HasRequiredClaims(requestHandler, endpoint))
                {
                    if (string.IsNullOrEmpty(endpoint.SignInUrl))
                    {
                        throw new HttpException(403, "Access denied.");
                    }

                    return((requestHandler as Controller).Redirect(endpoint.SignInUrl));
                }
            }

            IEndpoint endpointInstance = this.GetEndpointInstance(endpoint);

            if (endpointInstance == null)
            {
                return(null);
            }

            return(endpointInstance.Invoke(requestHandler, endpoint, endpointResolver.GetArguments(endpoint.UrlTemplate, url)));
        }
        public async Task Init(IEndpointResolver endpoints)
        {
            this.endpoints = endpoints;
            var fh = await endpoints.SelectOne(m_factory.CreateFrameHandler);

            this.Init(fh);
        }
Ejemplo n.º 7
0
        public void Init(IEndpointResolver endpoints)
        {
            this.endpoints = endpoints;
            var fh = endpoints.SelectOne(m_factory.CreateFrameHandler);

            this.Init(fh);
        }
Ejemplo n.º 8
0
 public RabbitMqSink(
     RabbitMqSinkOptions options,
     IEndpointResolver endpointResolver,
     Action<ConnectionFactory> connectionFactorySetup,
     ITextFormatter formatter,
     TextToBinaryFormatterOptions formatterOptions = null,
     string clientProviderName = null) : this(options, endpointResolver, connectionFactorySetup,
Ejemplo n.º 9
0
        public static T SelectOne <T>(this IEndpointResolver resolver, Func <AmqpTcpEndpoint, T> selector)
        {
            var       t         = default(T);
            Exception exception = null;

            foreach (var ep in resolver.All())
            {
                try
                {
                    t = selector(ep);
                    if (t.Equals(default(T)) == false)
                    {
                        return(t);
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                }
            }

            if (Object.Equals(t, default(T)) && exception != null)
            {
                throw exception;
            }

            return(t);
        }
Ejemplo n.º 10
0
        public static T SelectOne <T>(this IEndpointResolver resolver, Func <AmqpTcpEndpoint, T> selector)
        {
            var t          = default(T);
            var exceptions = new List <Exception>();

            foreach (AmqpTcpEndpoint ep in resolver.All())
            {
                try
                {
                    t = selector(ep);
                    if (!t.Equals(default(T)))
                    {
                        return(t);
                    }
                }
                catch (Exception e)
                {
                    exceptions.Add(e);
                }
            }

            if (Object.Equals(t, default(T)) && exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }

            return(t);
        }
Ejemplo n.º 11
0
        public void Test_Endpoint_NotFound( )
        {
            Api api = MakeApi("my-api");

            IEndpointResolver resolver = GetResolver( );

            Assert.Throws <EndpointNotFoundException>(() => resolver.ResolveEndpoint("my-api/my-end-point", false));
        }
Ejemplo n.º 12
0
        /// <inheritdoc cref="IRegistration"/>
        public void Create(CqrsEngine cqrsEngine)
        {
            if (m_Resolver == null)
            {
                m_Resolver = cqrsEngine.DependencyResolver.GetService(Dependencies.First()) as IEndpointResolver;
            }

            cqrsEngine.EndpointResolver = m_Resolver;
        }
Ejemplo n.º 13
0
        public void Test_ApiOnly_DuplicateName( )
        {
            Api api  = MakeApi("address1", true);
            Api api2 = MakeApi("address1", true);

            IEndpointResolver resolver = GetResolver( );

            Assert.Throws <ConnectorConfigException>(() => resolver.ResolveEndpoint("address1", false));
        }
Ejemplo n.º 14
0
        public void Test_Empty( )
        {
            IEndpointResolver     resolver = GetResolver( );
            EndpointAddressResult result   = resolver.ResolveEndpoint(new string[] {}, false);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.ApiId, Is.EqualTo(0));
            Assert.That(result.EndpointId, Is.EqualTo(0));
        }
Ejemplo n.º 15
0
        public void Test_Endpoint_CaseMismatch( )
        {
            Api api = MakeApi("my-api");
            ApiResourceEndpoint endpoint = MakeEndpoint(api, "my-eNd-point");

            IEndpointResolver resolver = GetResolver( );

            Assert.Throws <EndpointNotFoundException>(() => resolver.ResolveEndpoint("my-api/my-end-point", false));
        }
Ejemplo n.º 16
0
        public void Test_Endpoint_DuplicateName( )
        {
            Api api = MakeApi("my-api");
            ApiResourceEndpoint endpoint  = MakeEndpoint(api, "my-end-point");
            ApiResourceEndpoint endpoint2 = MakeEndpoint(api, "my-end-point");

            IEndpointResolver resolver = GetResolver( );

            Assert.Throws <ConnectorConfigException>(() => resolver.ResolveEndpoint("my-api/my-end-point", false));
        }
Ejemplo n.º 17
0
 public CqrsEngine(IDependencyResolver dependencyResolver, IMessagingEngine messagingEngine, IEndpointResolver endpointResolver, bool createMissingEndpoints, params IRegistration[] registrations)
 {
     m_Logger.Debug("CqrsEngine instanciating. createMissingEndpoints: " + createMissingEndpoints);
     m_CreateMissingEndpoints = createMissingEndpoints;
     m_DependencyResolver     = dependencyResolver;
     m_Registrations          = registrations;
     m_EndpointResolver       = endpointResolver;
     m_MessagingEngine        = messagingEngine;
     m_BoundedContexts        = new List <BoundedContext>();
     init();
 }
Ejemplo n.º 18
0
        public void Test_ApiOnly_Exists( )
        {
            Api api = MakeApi("address1");

            IEndpointResolver     resolver = GetResolver( );
            EndpointAddressResult result   = resolver.ResolveEndpoint("address1", false);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.ApiId, Is.EqualTo(api.Id));
            Assert.That(result.EndpointId, Is.EqualTo(0));
        }
Ejemplo n.º 19
0
        public void Test_Endpoint_WithSuffix( )
        {
            Api api = MakeApi("my-api");
            ApiResourceEndpoint endpoint = MakeEndpoint(api, "my-end-point");

            IEndpointResolver     resolver = GetResolver( );
            EndpointAddressResult result   = resolver.ResolveEndpoint("my-api/my-end-point/0", false);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.ApiId, Is.EqualTo(api.Id));
            Assert.That(result.EndpointId, Is.EqualTo(endpoint.Id));
        }
        private Endpoint CreateEndpoint(IEndpointResolver endpointResolver, ZipkinTracerOptions options)
        {
            // get defaults
            var defaultEndpoint = endpointResolver.GetEndpoint();

            // overwrite with values from user-supplied options
            return(new Endpoint
            {
                ServiceName = options.ServiceName ?? defaultEndpoint?.ServiceName ?? "Unknown",
                IPAddress = options.ServiceIpAddress ?? defaultEndpoint?.IPAddress ?? IPAddress.Loopback,
                Port = options.ServicePort != 0 ? options.ServicePort : defaultEndpoint?.Port ?? 0
            });
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="innerService">The service that will be wrapped and called by this service.</param>
        /// <param name="endpointResolver">The service that resolve endpoints.</param>
        /// <param name="entityRepository">The service that load entities.</param>
        public ApiKeySecurity(IConnectorService innerService, IEndpointResolver endpointResolver, IEntityRepository entityRepository)
        {
            if (innerService == null)
            {
                throw new ArgumentNullException(nameof(innerService));
            }
            if (endpointResolver == null)
            {
                throw new ArgumentNullException(nameof(endpointResolver));
            }

            _innerService     = innerService;
            _endpointResolver = endpointResolver;
        }
Ejemplo n.º 22
0
        public FluentApi(IEndpointResolver endpointResolver)
        {
            _endpointResolver = endpointResolver;

            ApiEndpointAttribute attribute = typeof(T).GetCustomAttributes(true)
                                             .OfType <ApiEndpointAttribute>()
                                             .FirstOrDefault();

            if (attribute == null)
            {
                throw new ArgumentException(string.Format("The Type {0} cannot be used in this way, it has no ApiEndpointAttribute", typeof(T)));
            }

            _endPointInfo.Uri = attribute.EndpointUri;
        }
Ejemplo n.º 23
0
        public async Task InvokeAsync(HttpContext httpContext, IEndpointResolver endpointResolver)
        {
            Data.Entities.Endpoint endpoint = await endpointResolver.ResolveAsync(httpContext);

            if (endpoint != null)
            {
                if (!endpoint.DisallowAnonymous || (httpContext.User.Identity.IsAuthenticated && endpoint.EndpointPermissions.All(ep => httpContext.User.HasClaim(PlatformusClaimTypes.Permission, ep.Permission.Code))))
                {
                    byte[] responseBody;
                    Func <Task <byte[]> > defaultValueFunc = async() =>
                    {
                        IActionResult actionResult = await this.CreateRequestProcessor(endpoint).ProcessAsync(httpContext, endpoint);

                        if (actionResult == null)
                        {
                            return(null);
                        }

                        return(await this.GetResponseBodyAsync(httpContext, actionResult));
                    };

                    if (string.IsNullOrEmpty(endpoint.ResponseCacheCSharpClassName))
                    {
                        responseBody = await defaultValueFunc();
                    }

                    else
                    {
                        responseBody = await this.CreateResponseCache(endpoint).GetWithDefaultValueAsync(
                            httpContext,
                            defaultValueFunc
                            );
                    }

                    if (responseBody != null)
                    {
                        await httpContext.Response.Body.WriteAsync(responseBody, 0, responseBody.Length);

                        return;
                    }
                }
            }

            await this.next(httpContext);
        }
        /// <summary>
        /// Create a connection using an IEndpointResolver.
        /// </summary>
        /// <param name="endpointResolver">
        /// The endpointResolver that returns the endpoints to use for the connection attempt.
        /// </param>
        /// <param name="clientProvidedName">
        /// Application-specific connection name, will be displayed in the management UI
        /// if RabbitMQ server supports it. This value doesn't have to be unique and cannot
        /// be used as a connection identifier, e.g. in HTTP API requests.
        /// This value is supposed to be human-readable.
        /// </param>
        /// <returns>Open connection</returns>
        /// <exception cref="BrokerUnreachableException">
        /// When no hostname was reachable.
        /// </exception>
        public IConnection CreateConnection(IEndpointResolver endpointResolver, string clientProvidedName)
        {
            ConnectionConfig config = CreateConfig(clientProvidedName);

            try
            {
                if (AutomaticRecoveryEnabled)
                {
                    return(new AutorecoveringConnection(config, endpointResolver));
                }

                return(new Connection(config, endpointResolver.SelectOne(CreateFrameHandler)));
            }
            catch (Exception e)
            {
                throw new BrokerUnreachableException(e);
            }
        }
Ejemplo n.º 25
0
        public static LoggerAuditSinkConfiguration RabbitMq(
            this LoggerAuditSinkConfiguration configuration,
            Action <RabbitMqSinkOptions> optionsSetup,
            IEndpointResolver endpointResolver,
            Action <ConnectionFactory> connectionFactorySetup,
            IBinaryFormatter binaryFormatter,
            LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose,
            LoggingLevelSwitch levelSwitch         = null,
            string clientProviderName = null)
        {
            RabbitMqSinkOptions options = configuration.Create(optionsSetup);

            RabbitMqSink rabbitMqSink = new RabbitMqSink(options, endpointResolver, connectionFactorySetup, binaryFormatter,
                                                         clientProviderName);

            configuration.Sink(rabbitMqSink, restrictedToMinimumLevel, levelSwitch);

            return(configuration);
        }
Ejemplo n.º 26
0
        public ConnectorService(IEndpointResolver endpointResolver, IEntityRepository entityRepository, IComponentContext componentContext)
        {
            if (endpointResolver == null)
            {
                throw new ArgumentNullException("endpointResolver");
            }
            if (entityRepository == null)
            {
                throw new ArgumentNullException("entityRepository");
            }
            if (componentContext == null)
            {
                throw new ArgumentNullException("componentContext");
            }

            _endpointResolver = endpointResolver;
            _entityRepository = entityRepository;
            _componentContext = componentContext;
        }
Ejemplo n.º 27
0
        public AutorecoveringConnection(ConnectionConfig config, IEndpointResolver endpoints)
        {
            _config    = config;
            _endpoints = endpoints;

            IFrameHandler fh = _endpoints.SelectOne(_config.FrameHandlerFactory);

            _innerConnection = new Connection(_config, fh);

            Action <Exception, string> onException =
                (exception, context) =>
                _innerConnection.OnCallbackException(CallbackExceptionEventArgs.Build(exception, context));

            _recoverySucceededWrapper              = new EventingWrapper <EventArgs>("OnConnectionRecovery", onException);
            _connectionRecoveryErrorWrapper        = new EventingWrapper <ConnectionRecoveryErrorEventArgs>("OnConnectionRecoveryError", onException);
            _consumerTagChangeAfterRecoveryWrapper = new EventingWrapper <ConsumerTagChangedAfterRecoveryEventArgs>("OnConsumerRecovery", onException);
            _queueNameChangeAfterRecoveryWrapper   = new EventingWrapper <QueueNameChangedAfterRecoveryEventArgs>("OnQueueRecovery", onException);

            ConnectionShutdown += HandleConnectionShutdown;
        }
Ejemplo n.º 28
0
        public static LoggerSinkConfiguration RabbitMq(
            this LoggerSinkConfiguration configuration,
            Action <RabbitMqSinkOptions> optionsSetup,
            IEndpointResolver endpointResolver,
            Action <ConnectionFactory> connectionFactorySetup,
            LogEventJsonConverterOptions jsonConverterOptions = null,
            LogEventLevel restrictedToMinimumLevel            = LogEventLevel.Verbose,
            LoggingLevelSwitch levelSwitch = null,
            string clientProviderName      = null)
        {
            RabbitMqSinkOptions options = configuration.Create(optionsSetup);

            RabbitMqSink rabbitMqSink = new RabbitMqSink(options, endpointResolver, connectionFactorySetup,
                                                         new JsonToUtf8BytesFormatter(jsonConverterOptions ?? new LogEventJsonConverterOptions()),
                                                         clientProviderName);

            configuration.Sink(rabbitMqSink, restrictedToMinimumLevel, levelSwitch);

            return(configuration);
        }
Ejemplo n.º 29
0
        public void AddSubscribedCommand(Type command, uint priority, IEndpointResolver resolver)
        {
            if (Type == null)
            {
                Type = RouteType.Commands;
            }
            if (Type != RouteType.Commands)
            {
                throw new ApplicationException($"Can not subscribe for commands on events route '{Name}'.");
            }

            var routingKey = new RoutingKey
            {
                LocalContext      = m_Context,
                MessageType       = command,
                Priority          = priority,
                RouteType         = Type.Value,
                CommunicationType = CommunicationType.Subscribe
            };

            m_RouteResolvers[routingKey] = resolver;
        }
Ejemplo n.º 30
0
        public void AddPublishedEvent(Type @event, uint priority, IEndpointResolver resolver)
        {
            if (Type == null)
            {
                Type = RouteType.Events;
            }
            if (Type != RouteType.Events)
            {
                throw new ApplicationException($"Can not publish for events with commands route '{Name}'.");
            }

            var routingKey = new RoutingKey
            {
                LocalContext      = m_Context,
                RouteType         = Type.Value,
                MessageType       = @event,
                Priority          = priority,
                CommunicationType = CommunicationType.Publish
            };

            m_RouteResolvers[routingKey] = resolver;
        }
 public void Init(IEndpointResolver endpoints)
 {
     this.endpoints = endpoints;
     var fh = endpoints.SelectOne(m_factory.CreateFrameHandler);
     this.Init(fh);
 }