Ejemplo n.º 1
0
 public static void Start(string[] args)
 {
     var bootServices = Management.GetClassesByInterface<IServiceDefinition>();
     if (!bootServices.Any()) return;
     Service = bootServices[0].CreateInstance<IServiceDefinition>();
     Main(args);
 }
Ejemplo n.º 2
0
        public void CopyFrom(IServiceDefinition copyFrom)
        {
            if (copyFrom == null) { return; }

            var svcDef = copyFrom as ServiceDefinition;
            if (svcDef != null)
            {
                Entities.AddRange(svcDef.Entities);
                Operations.AddRange(svcDef.Operations);
                return;
            }

            Entities.AddRange(
                copyFrom.Enums
                    .SelectMany(x => x)
                    .Select(x => new EnumDefinition(x))
                );

            Entities.AddRange(
                copyFrom.Models
                    .SelectMany(x => x)
                    .Select(x => new ModelDefinition(x))
                );

            Operations.AddRange(
                copyFrom.ResourceOperations
                    .SelectMany(x => x)
                    .Select(x => new OperationDefinition(x))
                );
        }
        private IConfiguration ComposeConfiguration(IServiceDefinition serviceDefinition, PrimitiveType primitiveType, string sectionName, bool forceExternal)
        {
            var sections = new List <IConfigurationSection>(6);

            var serviceCategory = forceExternal || serviceDefinition.Type == ServiceType.External ? ServiceCategory.External : ServiceCategory.Local;

            // [base]
            var key = new ConfigurationSectionKey
            {
                SectionName = sectionName
            };

            if (TryGetSection(key, out var section))
            {
                sections.Add(section);
            }

            // [primitive type]
            key.PrimitiveType = primitiveType;
            if (TryGetSection(key, out section))
            {
                sections.Add(section);
            }

            // [service category]
            key.PrimitiveType   = PrimitiveType.Any;
            key.ServiceCategory = serviceCategory;
            if (TryGetSection(key, out section))
            {
                sections.Add(section);
            }

            // [service category + primitive type]
            key.PrimitiveType = primitiveType;
            if (TryGetSection(key, out section))
            {
                sections.Add(section);
            }

            // [service]
            key.ServiceCategory = ServiceCategory.Any;
            key.PrimitiveType   = PrimitiveType.Any;
            key.ServiceName     = serviceDefinition.Name;
            if (TryGetSection(key, out section))
            {
                sections.Add(section);
            }

            // [service + primitive type]
            key.PrimitiveType = primitiveType;
            if (TryGetSection(key, out section))
            {
                sections.Add(section);
            }

            return(CombineSections(sections));
        }
        private ConfigOverrideLevels GetOverrideLevels(IServiceDefinition serviceDefinition, PrimitiveType primitiveType, string sectionName, bool forceExternal)
        {
            var result = ConfigOverrideLevels.None;

            var serviceCategory = forceExternal || serviceDefinition.Type == ServiceType.External ? ServiceCategory.External : ServiceCategory.Local;

            // [base]
            var key = new ConfigurationSectionKey
            {
                SectionName = sectionName
            };

            if (TryGetSection(key, out _))
            {
                result |= ConfigOverrideLevels.Base;
            }

            // [primitive type]
            key.PrimitiveType = primitiveType;
            if (TryGetSection(key, out _))
            {
                result |= ConfigOverrideLevels.BasePrimitives;
            }

            // [service category]
            key.PrimitiveType   = PrimitiveType.Any;
            key.ServiceCategory = serviceCategory;
            if (TryGetSection(key, out _))
            {
                result |= ConfigOverrideLevels.ServiceType;
            }

            // [service category + primitive type]
            key.PrimitiveType = primitiveType;
            if (TryGetSection(key, out _))
            {
                result |= ConfigOverrideLevels.ServiceTypePrimitives;
            }

            // [service]
            key.ServiceCategory = ServiceCategory.Any;
            key.PrimitiveType   = PrimitiveType.Any;
            key.ServiceName     = serviceDefinition.Name;
            if (TryGetSection(key, out _))
            {
                result |= ConfigOverrideLevels.Service;
            }

            // [service + primitive type]
            key.PrimitiveType = primitiveType;
            if (TryGetSection(key, out _))
            {
                result |= ConfigOverrideLevels.Primitive;
            }

            return(result);
        }
        public async Task Register(IServiceDefinition service)
        {
            var registration = new AgentServiceRegistration()
            {
                Name = service.Name()
            };

            await _client.Agent.ServiceRegister(registration);
        }
Ejemplo n.º 6
0
        public async Task <IEnumerable <IMessageListener> > StartListeningAsync(
            IConfiguration configuration,
            IServiceDefinition serviceDefinition,
            IDictionary <IMethodDefinition, IConfiguration> methodConfigMap,
            CancellationToken ct)
        {
            await _sinleListener.StartAsync(ct);

            return(new[] { _sinleListener });
        }
Ejemplo n.º 7
0
        private async Task StartListeningEventsAsync(
            string communicationType,
            IServiceDefinition serviceDefinition,
            IConfiguration configuration,
            Dictionary <IEventDefinition, IConfiguration> eventConfigMap,
            CancellationToken ct)
        {
            var method    = GetListeningMethod(communicationType);
            var listeners = await method.StartListeningAsync(configuration, serviceDefinition, eventConfigMap, ct);

            // TODO: keep referene to the listerner
        }
        private void EnumerateThroughPrimitiveType(
            IConfigurationSection parentSection, ConfigurationSectionKey serviceKey,
            PrimitiveType type, IServiceDefinition serviceDefinition,
            Dictionary <ConfigurationSectionKey, IConfigurationSection> map)
        {
            foreach (var section in parentSection.GetChildren())
            {
                if (section.Key.Equals("_all", StringComparison.OrdinalIgnoreCase))
                {
                    var allPrimitivesKey = serviceKey;
                    allPrimitivesKey.PrimitiveType = type;
                    map[allPrimitivesKey]          = section;
                }
                else if (type == PrimitiveType.Command || type == PrimitiveType.Query)
                {
                    var methodType = type;
                    var methodName = section.Key;

                    if (serviceDefinition != null && _methodResolver.TryResolve(serviceDefinition,
                                                                                new MethodId {
                        Name = methodName
                    }, out var methodReference))
                    {
                        methodType = methodReference.Definition.IsQuery ? PrimitiveType.Query : PrimitiveType.Command;
                        methodName = methodReference.Definition.Name;
                    }

                    var methodKey = serviceKey;
                    methodKey.PrimitiveType = methodType;
                    methodKey.PrimitiveName = methodName;

                    map[methodKey] = section;
                }
                else if (type == PrimitiveType.Event)
                {
                    var eventName = section.Key;

                    if (serviceDefinition != null && _eventResolver.TryResolve(serviceDefinition,
                                                                               new EventId {
                        Name = eventName
                    }, out var eventReference))
                    {
                        eventName = eventReference.Definition.Name;
                    }

                    var eventKey = serviceKey;
                    eventKey.PrimitiveType = type;
                    eventKey.PrimitiveName = eventName;

                    map[eventKey] = section;
                }
            }
        }
Ejemplo n.º 9
0
        private IResolver CreateResolverByExpression
            (IServiceDefinition definition, Expression <Func <ServiceRequest, object> > expression)
        {
            if (expression.Body is NewExpression nex)
            {
                expression = _configuration.Options.ExpressionBuilder
                             .CreateResolutionExpressionFromConstructorExpression(nex);
            }
            var resolver = new ExpressionResolver(definition, expression, InstanceType);

            return(BuildUp(resolver, definition, true));
        }
Ejemplo n.º 10
0
 public DepsCatalog(ServiceWrapperConf conf, IServiceDefinition def, Type implType)
 {
     Prefix            = conf.Prefix ?? "PayQueue";
     MiddlewareCommand = conf.MiddlewareCommand ?? (() => new DefaultMiddleware());
     MiddlewareEvent   = conf.MiddlewareEvent ?? (() => new DefaultMiddleware());
     Logger            = LoggerFactory.Create(builder =>
     {
         builder.AddConsole();
         builder.SetMinimumLevel(LogLevel.Debug);
     })
                         .CreateLogger(PrepareCategory(def, implType));
 }
Ejemplo n.º 11
0
        private MethodCommunicationSettings ComposeMethodCommunicationSettings(IServiceDefinition serviceDefinition, IMethodDefinition methodDefinition)
        {
            var settings = new MethodCommunicationSettings();

            if (methodDefinition != null)
            {
                if (methodDefinition.IsQuery)
                {
                    settings.RunInPlace        = true;
                    settings.IgnoreTransaction = true;
                }
                else
                {
                    settings.Deduplicate   = true;
                    settings.Resilient     = true;
                    settings.Persistent    = true;
                    settings.Transactional = true;
                }

                var configuration = _communicationModelConfiguration.GetMethodConfiguration(methodDefinition);

                configuration.Bind(settings);

                settings.CommunicationType =
                    _communicationModelConfiguration
                    .GetMethodConfiguration(methodDefinition, CommunicationSectionName)
                    .GetSection("type").Value;

                settings.PersistenceType =
                    _communicationModelConfiguration
                    .GetMethodConfiguration(methodDefinition, PersistenceSectionName)
                    .GetSection("type").Value;
            }
            else
            {
                var configuration = _communicationModelConfiguration.GetServiceConfiguration(serviceDefinition);

                configuration.Bind(settings);

                settings.CommunicationType =
                    _communicationModelConfiguration
                    .GetServiceConfiguration(serviceDefinition, CommunicationSectionName)
                    .GetSection("type").Value;

                settings.PersistenceType =
                    _communicationModelConfiguration
                    .GetServiceConfiguration(serviceDefinition, PersistenceSectionName)
                    .GetSection("type").Value;
            }

            return(settings);
        }
        public void SaveServiceDefinition_UnitTest()
        {
            IServiceDefinition serviceDefinition = default(IServiceDefinition);

            ExecuteMethod(
                () => { return((IILocationService)GetInstance()); },
                instance =>
            {
                serviceDefinition = ServiceDefinitionImpl_UnitTests.GetInstance();
                SaveServiceDefinition_PreCondition(instance, ref serviceDefinition);
            },
                instance => { instance.SaveServiceDefinition(serviceDefinition); },
                instance => { SaveServiceDefinition_PostValidate(instance, serviceDefinition); });
        }
Ejemplo n.º 13
0
        private async Task LoadServiceDefinitionAsync(CancellationToken cancelToken)
        {
            var getServiceDefinitionResponse = await m_client.ServiceMethods.GetServiceDefinition(
                new ServiceDefinitionResponseSections[] { ServiceDefinitionResponseSections.Platform },
                cancelToken);

            ConfigurationEntry[] entires = getServiceDefinitionResponse.Platform.ConfigurationEntries;

            ConfigurationEntry liveIdAuthPolicyConfig = entires.FirstOrDefault(configEntry => configEntry.Key.Equals("liveIdAuthPolicy"));

            m_serviceDefinition = new ServiceDefinitionProxy {
                LiveIdAuthPolicy = liveIdAuthPolicyConfig.Value
            };
        }
Ejemplo n.º 14
0
        public PlatformHttpClient(
            IServiceDefinition serviceDefinition,
            ISerializerFactorySelector serializerFactorySelector,
            IServiceHttpConfigurator serviceHttpConfigurator)
        {
            _serviceDefinition         = serviceDefinition;
            _serializerFactorySelector = serializerFactorySelector;
            _serviceHttpConfigurator   = serviceHttpConfigurator;

            _httpClient = new HttpClient();
            serviceHttpConfigurator.ConfigureBase(_httpClient, _serviceDefinition);

            _dasyncJsonSerializer = serializerFactorySelector.Select("dasync+json").Create();
        }
 /// <summary>
 /// Register service to builder.
 /// </summary>
 /// <param name="builder">Container builder.</param>
 /// <param name="service">Service definition.</param>
 private void RegisterServiceToBuilder(ContainerBuilder builder, IServiceDefinition service)
 {
     if (service.ImplementFactory != null)
     {
         this.RegisterServiceWithFactoryToBuilder(builder, service);
     }
     else if (service.ImplementInstance != null)
     {
         this.RegisterServiceWithInstanceToBuilder(builder, service);
     }
     else
     {
         this.RegisterServiceWithImplementToBuilder(builder, service);
     }
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Register scoped service.
 /// </summary>
 /// <param name="definition">Service definition.</param>
 private void RegisterScopedService(IServiceDefinition definition)
 {
     if (definition.ImplementInstance != null)
     {
         this._servicesCollection.AddScoped(definition.ServiceType, definition.ImplementInstance.GetType());
     }
     else if (definition.ImplementFactory != null)
     {
         this._servicesCollection.AddScoped(definition.ServiceType, definition.ImplementFactory);
     }
     else if (definition.ImplementType != null)
     {
         this._servicesCollection.AddScoped(definition.ServiceType, definition.ImplementType);
     }
 }
Ejemplo n.º 17
0
        private IResolver CreateResolverByType(IServiceDefinition definition, Type implementationType)
        {
            var constructor = _configuration.Options.ConstructorSelector.SelectConstructor
                                  (implementationType, _configuration);

            if (constructor == null)
            {
                return(new NonResolver(InstanceType));
            }
            var expression =
                _configuration.Options.ExpressionBuilder.CreateResolutionExpressionFromDefaultConstructor(constructor);
            var isTracked = typeof(IDisposable).IsAssignableFrom(implementationType);
            var resolver  = new ExpressionResolver(definition, expression, InstanceType);

            return(BuildUp(resolver, definition, isTracked));
        }
Ejemplo n.º 18
0
        public bool TryResolve(IServiceDefinition serviceDefinition, EventId eventId, out IEventReference eventReference)
        {
            var eventDefinition = serviceDefinition.FindEvent(eventId.Name);

            if (eventDefinition == null || eventDefinition.IsIgnored)
            {
                eventReference = null;
                return(false);
            }

            var delegateMethodInfo = eventDefinition.EventInfo.EventHandlerType.GetMethod("Invoke");
            var invoker            = _methodInvokerFactory.Create(delegateMethodInfo);

            eventReference = new EventReference(eventId, eventDefinition, invoker);
            return(true);
        }
Ejemplo n.º 19
0
        private IResolver BuildUp(IResolver resolver, IServiceDefinition definition, bool isTracked)
        {
            /*
             * IMPORTANT:
             *
             * Resplvers must be decorated in the following order:
             *
             *  1. Instance resolver / Expression resolver
             *  2. Decorator resolver
             *  3. Service tracker resolver
             *  4. Service cache resolver
             *  5. Conditional resolver
             *  6. Enumerable resolver / Selector resolver
             */

            IResolver built = resolver;

            var interceptorType = typeof(IInterceptor <>).MakeGenericType(InstanceType);

            if (_configuration.CanResolve(interceptorType))
            {
                var interceptorResolverType
                      = typeof(InterceptorResolver <>).MakeGenericType(InstanceType);
                built = (IResolver)Activator.CreateInstance
                            (interceptorResolverType, built, _configuration);
            }

            if (isTracked && definition.Lifecycle.Tracked)
            {
                built = new ServiceTrackerResolver(definition, built);
            }

            if (resolver is ExpressionResolver exr && definition.Lifecycle.Cached)
            {
                built = new ServiceCacheResolver(definition, built, exr.Key);
            }

            if (definition.Precondition != null)
            {
                built = new ConditionalResolver(definition, built);
            }

            return(built);
        }
Ejemplo n.º 20
0
        public bool TryResolve(IServiceDefinition serviceDefinition, MethodId methodId, out IMethodReference methodReference)
        {
            var methodDefinition = serviceDefinition.FindMethod(methodId.Name);

            if (methodDefinition == null || methodDefinition.IsIgnored)
            {
                methodReference = null;
                return(false);
            }

            // WARNING: Need to know exact interface used by caller to select the right MethodInfo.
            // This can be an issue only if two or more interfaces have a method with exactly the same signature.
            var interfaceMappedMethodInfo = methodDefinition.InterfaceMethods?.FirstOrDefault();

            var invoker = _methodInvokerFactory.Create(methodDefinition.MethodInfo, interfaceMappedMethodInfo);

            methodReference = new MethodReference(methodId, methodDefinition, invoker);
            return(true);
        }
Ejemplo n.º 21
0
        private async void RunRoutineInBackground(IServiceDefinition serviceDefinition, ExecuteRoutineIntent intent)
        {
            try
            {
                var serviceInstance = _domainServiceProvider.GetService(serviceDefinition.Implementation);
                var routineMethod   = _routineMethodResolver.Resolve(serviceDefinition, intent.MethodId);
                var methodInvoker   = _methodInvokerFactory.Create(routineMethod);

                foreach (var postAction in _transitionActions)
                {
                    await postAction.OnRoutineStartAsync(serviceDefinition, intent.ServiceId, intent.MethodId, intent.Id);
                }

                Task task;
                try
                {
                    task = methodInvoker.Invoke(serviceInstance, intent.Parameters);
                    if (routineMethod.ReturnType != typeof(void))
                    {
                        try { await task; } catch { }
                    }
                }
                catch (Exception ex)
                {
                    if (ex is TargetInvocationException)
                    {
                        ex = ex.InnerException;
                    }
                    task = Task.FromException(ex);
                }
                var taskResult = task?.ToTaskResult() ?? new TaskResult();

                foreach (var postAction in _transitionActions)
                {
                    await postAction.OnRoutineCompleteAsync(serviceDefinition, intent.ServiceId, intent.MethodId, intent.Id, taskResult);
                }

                _routineCompletionSink.OnRoutineCompleted(intent.Id, taskResult);
            }
            catch
            {
            }
        }
Ejemplo n.º 22
0
        private async Task HandleEventSubsciptionAsync(IServiceDefinition serviceDefinition, string eventName, HttpContext context, CancellationToken ct)
        {
            if (context.Request.Method != "PUT" && context.Request.Method != "POST")
            {
                context.Response.StatusCode  = 405; // Method Not Allowed
                context.Response.ContentType = "text/plain";
                await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes("To subscribe to an event, use one of these HTTP verbs: GET, POST, PUT"));

                return;
            }

            var serviceName = (context.Request.Query.TryGetValue("service", out var serviceValues) && serviceValues.Count == 1) ? serviceValues[0] : null;

            if (string.IsNullOrWhiteSpace(serviceName))
            {
                context.Response.StatusCode  = 404;
                context.Response.ContentType = "text/plain";
                await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes("Missing 'service=xxx' in the URL query."));

                return;
            }

            var proxyName = (context.Request.Query.TryGetValue("proxy", out var proxyValues) && proxyValues.Count == 1) ? proxyValues[0] : null;

            var subscriberServiceId = new ServiceId {
                ServiceName = serviceName, ProxyName = proxyName
            };

            var eventId = new EventId {
                EventName = eventName
            };
            var publisherServiceId = new ServiceId {
                ServiceName = serviceDefinition.Name
            };
            var eventDesc = new EventDescriptor {
                ServiceId = publisherServiceId, EventId = eventId
            };

            _eventDispatcher.OnSubscriberAdded(eventDesc, subscriberServiceId);

            context.Response.StatusCode = 200;
        }
        /// <summary>
        /// Register service with service implement type to builder.
        /// </summary>
        /// <param name="builder">Container builder.</param>
        /// <param name="service">Service definition.</param>
        private void RegisterServiceWithImplementToBuilder(ContainerBuilder builder, IServiceDefinition service)
        {
            var step1 = builder.RegisterType(service.ImplementType);
            var step2 = step1.As(service.ServiceType);

            switch (service.LifeTime)
            {
            case ServiceLifeTime.Singleton:
                step2.SingleInstance();
                break;

            case ServiceLifeTime.Transient:
                step2.InstancePerDependency();
                break;

            case ServiceLifeTime.Scope:
            default:
                step2.InstancePerLifetimeScope();
                break;
            }
        }
        public IPlatformHttpClient GetClient(IServiceDefinition serviceDefinition)
        {
            lock (_clients)
            {
                if (_clients.TryGetValue(serviceDefinition.Name, out var connector))
                {
                    return(connector);
                }
            }

            lock (_clients)
            {
                var connector = new PlatformHttpClient(
                    serviceDefinition,
                    _serializerFactorySelector,
                    _serviceHttpConfigurator);

                _clients.Add(serviceDefinition.Name, connector);
                return(connector);
            }
        }
Ejemplo n.º 25
0
        private async void SubscribePeriodicallyInBackground(
            EventDescriptor eventDesc,
            ServiceId subscriber,
            IServiceDefinition publisherServiceDefinition)
        {
            var subscriberServiceDefinition = GetServiceDefinition(subscriber);

            while (true)
            {
                var client = _platformHttpClientProvider.GetClient(publisherServiceDefinition);

                try
                {
                    await client.SubscribeToEvent(eventDesc, subscriber, publisherServiceDefinition);

                    await Task.Delay(TimeSpan.FromMinutes(2));
                }
                catch
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }
        }
Ejemplo n.º 26
0
        public async Task PublishEvent(RaiseEventIntent intent, IServiceDefinition subscriberServiceDefinition, NameValueCollection context)
        {
            var uri = string.Concat(_serviceHttpConfigurator.GetUrl(subscriberServiceDefinition), "?react&event=", intent.EventId.EventName, "&service=", intent.ServiceId.ServiceName);

            var json = _dasyncJsonSerializer.SerializeToString(intent);

            var content = new StringContent(json);

            content.Headers.ContentType = new MediaTypeHeaderValue("application/dasync+json");

            if (context?.Count > 0)
            {
                content.Headers.TryAddWithoutValidation(DasyncHttpHeaders.Context, context.Serialize());
            }

            var response = await _httpClient.PutAsync(uri, content);

            var statusCode = (int)response.StatusCode;

            if (statusCode != DasyncHttpCodes.Succeeded && statusCode != DasyncHttpCodes.Scheduled)
            {
                throw new InvalidOperationException($"Unexpected HTTP {statusCode} response:\r\n{await response.Content.ReadAsStringAsync()}");
            }
        }
Ejemplo n.º 27
0
        private IResolver CreateResolverByInstance(IServiceDefinition definition, object implementation)
        {
            var resolver = new InstanceResolver(definition, implementation);

            return(BuildUp(resolver, definition, implementation is IDisposable));
        }
 partial void ToolType_SetCondition(ref IServiceDefinition instance, ref String setValue);
 partial void RemoveLocationMapping_PreCondition(IServiceDefinition instance, ref IAccessMapping accessMapping);
 partial void RemoveLocationMapping_PostValidate(IServiceDefinition instance, IAccessMapping accessMapping);
 partial void RelativeToSetting_SetCondition(ref IServiceDefinition instance, ref IRelativeToSetting setValue);
 partial void RelativePath_SetCondition(ref IServiceDefinition instance, ref String setValue);
Ejemplo n.º 33
0
        private async Task LoadServiceDefinitionAsync(CancellationToken cancelToken)
        {
            var getServiceDefinitionResponse = await m_client.ServiceMethods.GetServiceDefinition(
                new ServiceDefinitionResponseSections[] { ServiceDefinitionResponseSections.Platform },
                cancelToken);

            ConfigurationEntry[] entires = getServiceDefinitionResponse.Platform.ConfigurationEntries;

            ConfigurationEntry liveIdAuthPolicyConfig = entires.FirstOrDefault(configEntry => configEntry.Key.Equals("liveIdAuthPolicy"));

            m_serviceDefinition = new ServiceDefinitionProxy {LiveIdAuthPolicy = liveIdAuthPolicyConfig.Value};
        }
Ejemplo n.º 34
0
 public ServiceDefinition(IServiceDefinition copyFrom)
     : this()
 {
     CopyFrom(copyFrom);
 }