public void ShouldNotCallDispatcherIfOrderDoesNotValidate()
        {
            var processor = new IncomingMessageProcessor(ordereRepositoryMock, outgoingQueueMock, dateServiceMock, orderDispatcherMock, serializer);

            var invalidLimitOrder = new LimitOrderDto();

            invalidLimitOrder.Reeset();

            var messageBytes = serializer.Serialize(new ClientToServerMessageQueueItem
            {
                Message = new ClientToServerMessage
                {
                    ClientId    = 1,
                    LimitOrder  = invalidLimitOrder,
                    MessageType = ClientToServerMessageTypeEnum.PlaceLimitOrder
                },
            });

            var queueItem = new RingbufferByteArray();

            queueItem.Set(messageBytes);

            processor.OnNext(queueItem, 1, true);

            orderDispatcherMock.AssertWasNotCalled(a => a.HandleAddLimitOrder(Arg <ILimitOrder> .Is.Anything));
            outgoingQueueMock.AssertWasNotCalled(a => a.EnqueueAddedLimitOrder(Arg <ILimitOrder> .Is.Anything));
        }
        public ResponseXsd GetXsd(int requestCode)
        {
            log.Debug("Запуск");
            log.Debug($"requestCode: {requestCode}");
            log.Debug($"Token: {GetTokenValue()}");
            if (!AuthorizeHelpers.IsAuthorized(_dbContext, GetTokenValue(), requestCode, out ResponseXsd response, out var externalSystem))
            {
                log.Error($"Авторизация не пройдена. Причина: {response.Error}");
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Forbidden, response));
            }

            log.Debug("Авторизация пройдена");
            var imp = new IncomingMessageProcessor(_dbContext, externalSystem);

            response = imp.GetXsd(requestCode);
            log.Debug($"Результат:\r\n{response}");

            if (response.IsError)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, response));
            }

            log.Debug("Звершение");
            return(response);
        }
        public void ShouldCallDispatcherWhenLimitOrderValidates()
        {
            var processor = new IncomingMessageProcessor(ordereRepositoryMock, outgoingQueueMock, dateServiceMock, orderDispatcherMock, serializer);

            var limitOrder = new LimitOrderDto();

            limitOrder.Reeset();
            limitOrder.Symbol   = "QQQ";
            limitOrder.Price    = 30;
            limitOrder.Quantity = 10;
            limitOrder.ClientId = 1;
            limitOrder.Way      = WayEnum.Sell;

            var messageBytes = serializer.Serialize(new ClientToServerMessageQueueItem
            {
                Message =

                    new ClientToServerMessage
                {
                    ClientId    = 1,
                    LimitOrder  = limitOrder,
                    MessageType = ClientToServerMessageTypeEnum.PlaceLimitOrder
                }
            });

            var queueItem = new RingbufferByteArray();

            queueItem.Set(messageBytes);

            processor.OnNext(queueItem, 1, true);

            orderDispatcherMock.AssertWasCalled(a => a.HandleAddLimitOrder(Arg <ILimitOrder> .Is.Equal(limitOrder)));
        }
Ejemplo n.º 4
0
        public Response GetResponse(Guid requestId)
        {
            log.Debug("Запуск");
            log.Debug($"Сообщение:\r\n{OperationContext.Current.RequestContext.RequestMessage}");
            log.Debug($"requestId: {requestId}");
            log.Debug($"Token: {WebOperationContext.Current.IncomingRequest.Headers["Token"]}");
            if (!AuthorizeHelpers.IsAuthorized(_dbContext,
                                               WebOperationContext.Current.IncomingRequest.Headers["Token"],
                                               requestId,
                                               out Response response,
                                               out var externalSystem))
            {
                log.Error($"Авторизация не пройдена. Причина: {response.Error}");
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden;
                return(response);
            }

            log.Debug("Авторизация пройдена");
            IncomingMessageProcessor imp = new IncomingMessageProcessor(_dbContext, externalSystem);

            response = imp.GetResponse(requestId);
            log.Debug($"Результат:\r\n{response}");
            log.Debug("Звершение");
            return(response);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting...");


            ILogger           logger           = new SerilogLogger();
            ISerializer       serializer       = new ProtobufSerializer();
            IMessagePublisher messagePublisher = new MessagePublisher(logger, serializer);
            IOutgoingQueue    outgoingQueue    = new OutgoingQueue(logger, messagePublisher);

            messagePublisher.Start(9193);
            outgoingQueue.Start();

            IOrderRepository          orderRepository          = new OrderRepository();
            IOrderDispatcher          orderDispatcher          = new OrderDispatcher(outgoingQueue, logger, new DateService(), orderRepository);
            IIncomingMessageProcessor incomingMessageProcessor = new IncomingMessageProcessor(orderRepository, outgoingQueue, new DateService(), orderDispatcher, new ProtobufSerializer());
            IPerformanceRecorder      performanceRecorder      = new PerformanceRecorderDirectConsoleOutput(new DateService());
            IIncomingMessageQueue     incomingMessageQueue     = new IncomingMessageQueue(logger, incomingMessageProcessor, performanceRecorder);
            IClientMessagePuller      clientMessagePuller      = new ClientMessagePuller(logger, new ProtobufSerializer(), incomingMessageQueue);

            incomingMessageQueue.Start();
            clientMessagePuller.Start(9192);

            Console.WriteLine("Started. Hit any key to quit.");
            Console.ReadKey();

            Console.WriteLine("Stopping...");

            clientMessagePuller.Stop();
            incomingMessageQueue.Stop();
            outgoingQueue.Stop();
            messagePublisher.Stop();

            Console.WriteLine("Stopped");
        }
        public void ShouldNotCallDispatcherWhenLimitOrderIsInvalidOnCancelOrder()
        {
            var processor = new IncomingMessageProcessor(ordereRepositoryMock.Object, outgoingQueueMock.Object, dateServiceMock.Object, orderDispatcherMock.Object, serializer);

            var limitOrder = new LimitOrderDto();

            limitOrder.Reeset();

            var messageBytes = serializer.Serialize(new ClientToServerMessageQueueItem
            {
                Message =
                    new ClientToServerMessage
                {
                    ClientId    = 1,
                    LimitOrder  = limitOrder,
                    MessageType = ClientToServerMessageTypeEnum.CancelLimitOrder
                }
            });

            var queueItem = new RingbufferByteArray();

            queueItem.Set(messageBytes);

            processor.OnEvent(queueItem, 1, true);

            orderDispatcherMock.Verify(a => a.HandleAddLimitOrder(It.IsAny <ILimitOrder>()), Times.Never());
        }
Ejemplo n.º 7
0
 public GameCore(
     ZoneClientNetPeer zoneClientNetPeer,
     IncomingMessageProcessor incomingMessageProcessor,
     IServiceProvider serviceProvider)
     : base(windowTitle: "Sinalia")
 {
     this.zoneClientNetPeer        = zoneClientNetPeer;
     this.incomingMessageProcessor = incomingMessageProcessor;
     this.serviceProvider          = serviceProvider;
 }
Ejemplo n.º 8
0
 public ZoneClient(
     IServiceProvider serviceProvider,
     IncomingMessageProcessor incomingMessageProcessor,
     ILoggingService loggingService,
     ZoneClientNetPeer zoneClientNetPeer)
 {
     this.serviceProvider          = serviceProvider;
     this.incomingMessageProcessor = incomingMessageProcessor;
     this.loggingService           = loggingService;
     this.zoneClientNetPeer        = zoneClientNetPeer;
 }
        public ResponseId ExecuteRequestAsync([FromBody] Request request)
        {
            log.Debug("Запуск");
            log.Debug($"request:\r\n{request}");
            log.Debug($"Token: {GetTokenValue()}");
            if (!AuthorizeHelpers.IsAuthorized(_dbContext, GetTokenValue(), request.Code, out ResponseId response, out var externalSystem))
            {
                log.Error($"Авторизация не пройдена. Причина: {response.Error}");
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Forbidden, response));
            }

            log.Debug("Авторизация пройдена");
            IncomingMessageProcessor imp = new IncomingMessageProcessor(_dbContext, externalSystem);

            response = imp.ExecuteAsync(request);
            log.Debug($"Результат:\r\n{response}");
            log.Debug("Звершение");
            return(response);
        }
        public void ShouldCallDispatcherWhenLimitOrderValidates()
        {
            var processor = new IncomingMessageProcessor(ordereRepositoryMock.Object, outgoingQueueMock.Object, dateServiceMock.Object, orderDispatcherMock.Object, serializer);

            var limitOrder = new LimitOrderDto();

            limitOrder.Reeset();
            limitOrder.Symbol   = "QQQ";
            limitOrder.Price    = 30;
            limitOrder.Quantity = 10;
            limitOrder.ClientId = 1;
            limitOrder.Way      = WayEnum.Sell;

            var messageBytes = serializer.Serialize(new ClientToServerMessageQueueItem
            {
                Message =

                    new ClientToServerMessage
                {
                    ClientId    = 1,
                    LimitOrder  = limitOrder,
                    MessageType = ClientToServerMessageTypeEnum.PlaceLimitOrder
                }
            });

            var queueItem = new RingbufferByteArray();

            queueItem.Set(messageBytes);

            processor.OnEvent(queueItem, 1, true);

            orderDispatcherMock.Verify(a => a.HandleAddLimitOrder(It.Is <ILimitOrder>(order =>
                                                                                      order.Symbol == limitOrder.Symbol &&
                                                                                      order.Price == limitOrder.Price &&
                                                                                      order.Quantity == limitOrder.Quantity &&
                                                                                      order.ClientId == limitOrder.ClientId &&
                                                                                      order.Way == limitOrder.Way

                                                                                      )), Times.Once);
        }
        public async Task <Response> FileUpload()
        {
            log.Debug("Запуск");
            log.Debug($"Token: {GetTokenValue()}");

            var isMimeMultipartContent = Request.Content.IsMimeMultipartContent();

            log.Debug($"isMimeMultipartContent: {isMimeMultipartContent}");

            if (!isMimeMultipartContent)
            {
                var errorResponse = new ResponseId
                {
                    IsError = true,
                    Error   = "Некорректный Content-Type, ожидаем на вход MimeMultipart"
                };
                log.Error(errorResponse);

                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, errorResponse));
            }

            var provider = new MultipartMemoryStreamProvider();

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new ResponseId
                {
                    IsError = true,
                    Error   = ex.Message
                }));
            }

            log.Debug($"Contents count: {provider.Contents.Count}");

            if (provider.Contents.Count != 2)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new ResponseId
                {
                    IsError = true,
                    Error   = "Тело запроса должно состоять из файла и json-объекта"
                }));
            }

            HttpContent json = provider.Contents.FirstOrDefault(c => c.Headers.ContentType.MediaType == "application/json");

            if (json == null)
            {
                var errorResponse = new Response
                {
                    IsError = true,
                    Error   = "В теле запроса нет части с Content-type: application/json"
                };
                log.Error(errorResponse);

                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, errorResponse));
            }

            UploadFileRequest fileInfo = null;

            try
            {
                log.Debug("Чтение json объекта с метаданными загружаемого файла");
                byte[] jsonAsArray = json.ReadAsByteArrayAsync().Result;
                using (var stream = new MemoryStream(jsonAsArray))
                {
                    var sr         = new StreamReader(stream);
                    var rawJsonStr = sr.ReadToEnd();
                    log.Debug($"Raw JSON string: {rawJsonStr}");
                    fileInfo = JsonConvert.DeserializeObject <UploadFileRequest>(rawJsonStr);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new ResponseId
                {
                    IsError = true,
                    Error   = ex.Message
                }));
            }

            if (!AuthorizeHelpers.IsAuthorized(_dbContext, GetTokenValue(), fileInfo.RequestCode, out Response response,
                                               out var externalSystem))
            {
                log.Error($"Авторизация не пройдена. Причина: {response.Error}");
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Forbidden, response));
            }

            log.Debug("Авторизация пройдена");
            HttpContent file = provider.Contents.FirstOrDefault(c => c.Headers.ContentType.MediaType != "application/json");

            if (file == null)
            {
                var errorResponse = new ResponseId
                {
                    IsError = true,
                    Error   = "В теле запроса нет части с файлом"
                };
                log.Error(errorResponse);
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, errorResponse));
            }

            string fileName = file.Headers.ContentDisposition.FileName.Replace("\"", "");

            log.Debug($"fileName: {fileName}");
            UploadFileRequest.ValidateFileName(fileName, Request);


            byte[] fileAsArray = file.ReadAsByteArrayAsync().Result;
            try
            {
                var imp = new IncomingMessageProcessor(_dbContext, externalSystem);
                response = imp.FileUpload(fileInfo, fileName, fileAsArray);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new ResponseId
                {
                    IsError = true,
                    Error   = ex.Message
                }));
            }
            log.Debug($"Результат:\r\n{response}");
            log.Debug("Завершение");
            return(response);
        }