Exemple #1
0
        public async Task <bool> CheckUser(string name)
        {
            try
            {
                ActorId           id        = new ActorId(1);
                var               gateproxy = id.Proxy <IGate>();
                GateRequest       request   = new GateRequest();
                UserExistsRequest uer       = new Shared.Requests.UserExistsRequest();
                uer.UserName        = name;
                request.Kind        = 1;
                request.JsonPayload = uer.Serialize();
                GateResponse response = await gateproxy.Process(request);

                if (response.ResultCode == 200)
                {
                    UserExistsResponse r = response.JsonPayload.Deserialize <UserExistsResponse>();
                    return(r.Exists);
                }

                return(false);
            }
            catch (Exception e)
            {
                await Logger.LogMessage(e);

                throw (e);
            }
        }
        public static HttpRequestMessage ToHttpRequestMessage(this GateRequest gateRequest, Uri serviceUri)
        {
            var servicePath            = gateRequest.ServicePath ?? "";
            var requestQuery           = gateRequest.Query ?? "";
            var servicePathAndQueryUri = new Uri(serviceUri, servicePath + requestQuery);
            var httpRequestMessage     = new HttpRequestMessage
            {
                RequestUri = servicePathAndQueryUri,
                Method     = new HttpMethod(gateRequest.Method),
                Content    = ToContent(gateRequest.Content)
            };

            if (gateRequest.Headers != null)
            {
                var headerNames = gateRequest.Headers
                                  .Select(h => h.Key)
                                  .Distinct();
                foreach (var headerName in headerNames)
                {
                    var headerValues = gateRequest.Headers
                                       .Where(h => h.Key == headerName)
                                       .Select(h => h.Value)
                                       .ToList();
                    if (!httpRequestMessage.Headers.TryAddWithoutValidation(headerName, headerValues))
                    {
                        httpRequestMessage.Content?.Headers.TryAddWithoutValidation(headerName, headerValues);
                    }
                }
            }

            httpRequestMessage.Headers.Host = $"{serviceUri.Host}:{serviceUri.Port}";

            return(httpRequestMessage);
        }
Exemple #3
0
        public async Task SendAsync(string serviceName, string topicName, GateRequest gateRequest, CancellationToken cancellationToken)
        {
            var fallbackEndpoint   = new Uri(_sidecarOptions.FallbackUri);
            var httpRequestMessage = gateRequest.ToHttpRequestMessage(fallbackEndpoint);

            httpRequestMessage.Headers.Remove(HttpHeaderNames.XGateServiceName);
            httpRequestMessage.Headers.Add(HttpHeaderNames.XGateServiceName, serviceName);
            httpRequestMessage.Headers.Remove(HttpHeaderNames.XGateTopicName);
            httpRequestMessage.Headers.Add(HttpHeaderNames.XGateTopicName, topicName);
            var httpResponseMessage =
                await _httpClient.SendAsync(httpRequestMessage, cancellationToken);

            httpResponseMessage.EnsureSuccessStatusCode();
        }
Exemple #4
0
        public async Task GateRequest_To_HttpRequestMessage_Test()
        {
            var serviceUri = new Uri("http://service-host/");


            var gateRequest = new GateRequest
            {
                ServicePath = "service-path",
                Query       = "?a=b",
                Method      = "POST",
                Headers     = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("Host", "client-host"),
                    new KeyValuePair <string, string>("Accept", "application/json"),
                    new KeyValuePair <string, string>("Content-Type", "application/json"),
                    new KeyValuePair <string, string>("X-Test", "test1"),
                    new KeyValuePair <string, string>("X-Test", "test2"),
                    new KeyValuePair <string, string>("X-Test", "test3")
                },
                Content = Encoding.UTF8.GetBytes("Test")
            };

            var httpRequestMessage = gateRequest.ToHttpRequestMessage(serviceUri);

            Assert.AreEqual(new Uri(serviceUri, gateRequest.ServicePath + gateRequest.Query), httpRequestMessage.RequestUri);
            Assert.AreEqual(gateRequest.Method, httpRequestMessage.Method.ToString());
            Assert.IsTrue(gateRequest.Content.SequenceEqual(await httpRequestMessage.Content.ReadAsByteArrayAsync()));

            Assert.IsTrue(gateRequest.Headers.Where(h => h.Key != "Host").All(h =>
                                                                              httpRequestMessage.Headers.Any(rmh => rmh.Key == h.Key && rmh.Value.Contains(h.Value)) ||
                                                                              httpRequestMessage.Content.Headers.Any(rmh => rmh.Key == h.Key && rmh.Value.Contains(h.Value))),
                          "Must contains all gateRequest headers");

            Assert.IsTrue(!gateRequest.Headers.Any(h =>
                                                   httpRequestMessage.Headers.Any(rmh => rmh.Key == h.Key && rmh.Value.Contains(h.Value)) &&
                                                   httpRequestMessage.Content.Headers.Any(rmh => rmh.Key == h.Key && rmh.Value.Contains(h.Value))),
                          "Should not contains duplicate headers"
                          );

            Assert.IsTrue(httpRequestMessage.Headers.Any() && httpRequestMessage.Content.Headers.Any(),
                          "Request and request content must contain headers");

            Assert.AreEqual($"{serviceUri.Host}:{serviceUri.Port}", httpRequestMessage.Headers.Host);

            var httpRequestCount = httpRequestMessage.Headers.Count() + httpRequestMessage.Content.Headers.Count();
            var gateRequestCount = gateRequest.Headers.Select(h => h.Key).Distinct().Count();

            Assert.AreEqual(gateRequestCount, httpRequestCount,
                            "Add headers with same key in one header");
        }
Exemple #5
0
        public async Task ExecuteAsync(string s)
        {
            Interlocked.Increment(ref InterfaceHub._NumQues);
            ActorId gatewayId = new ActorId(Context.ConnectionId);

            try
            {
                GateRequest  request  = s.Deserialize <GateRequest>();
                GateResponse response = await gatewayId.Proxy <IGate>().Process(request);
            }
            catch (Exception e)
            {
                e.Log();
            }
        }
Exemple #6
0
        public static async Task <GateRequest> ToGateRequestAsync(this HttpRequest httpRequest, string servicePath)
        {
            var gateRequest = new GateRequest
            {
                Headers     = new List <KeyValuePair <string, string> >(),
                Content     = await httpRequest.Body.ToGateContentAsync(),
                Method      = httpRequest.Method,
                ServicePath = servicePath,
                Query       = httpRequest.QueryString.ToString()
            };

            foreach (var(headerName, headerValues) in httpRequest.Headers)
            {
                var gateHeaders = headerValues
                                  .Select(headerValue => new KeyValuePair <string, string>(headerName, headerValue));
                gateRequest.Headers.AddRange(gateHeaders);
            }

            return(gateRequest);
        }
Exemple #7
0
        public async Task Execute(string s)
        {
            //Use the current connection id (Guid) as the identity of the stateless gateway actor
            ActorId gatewayId = new ActorId(Context.ConnectionId);

            try
            {
                //Increment counter
                Interlocked.Increment(ref InterfaceHub._NumCalls);
                //Deserialize envelope request
                GateRequest request = s.Deserialize <GateRequest>();
                //call ServiceFabric gateway actor and process the request
                GateResponse response = await gatewayId.Proxy <IGate>().Process(request);

                //Return the response to the caller
                await Clients.Caller.Invoke("Exec", response.Serialize());
            }
            catch (Exception e)
            {
                e.Log();
            }
        }
Exemple #8
0
        public async Task SendFallback_Test()
        {
            var serviceName = "service-name";
            var topicName   = "topic-name";
            var gateRequest = new GateRequest
            {
                Method  = "GET",
                Headers = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>(HttpHeaderNames.XGateServiceName, "value")
                }
            };

            _testableHttpMessageHandler.Response = new HttpResponseMessage();
            await _fallbackService.SendAsync(serviceName, topicName, gateRequest, CancellationToken.None);

            Assert.IsTrue(_testableHttpMessageHandler.Request.Headers
                          .Any(h => h.Key == HttpHeaderNames.XGateServiceName && h.Value.Contains(serviceName)));
            Assert.IsTrue(_testableHttpMessageHandler.Request.Headers
                          .Any(h => h.Key == HttpHeaderNames.XGateTopicName && h.Value.Contains(topicName)));
            Assert.AreEqual(1, _testableHttpMessageHandler.Request.Headers.Count(h => h.Key == HttpHeaderNames.XGateServiceName));
            Assert.AreEqual(new Uri(_options.FallbackUri), _testableHttpMessageHandler.Request.RequestUri);
        }
Exemple #9
0
        /// <summary>
        /// Main process request method
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        async Task <GateResponse> IGate.Process(GateRequest Request)
        {
            try
            {
                _LastCall = DateTime.UtcNow;
                //Start a timer to log request processing time etc.
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                //Test for ping
                if (Request.Kind == (int)RequestProcessorEnum._System_PingGw)
                {
                    GateResponse pingResponse = new GateResponse(Request);
                    pingResponse.JsonPayload = new GameFabric.Shared.Responses.EmptyResponse().Serialize();
                    pingResponse.ResultCode  = (int)System.Net.HttpStatusCode.OK;
                    return(pingResponse);
                }
                //retrieve a processor for the call
                IRequestProcessor processor = ProcessorHelper.GetProcessor(Request.Kind);
                //Just test for authentication
                if (processor.Authenticated && !_isAuthenticated)
                {
                    GateResponse errorResponse = new GateResponse(Request);
                    errorResponse.ResultCode = (int)HttpStatusCode.Forbidden;
                    _ForbiddenCount++;
                    _LastForbiddenCall = DateTime.UtcNow;
                    return(await Task.FromResult(errorResponse));
                }
                //Deserialize request
                string Payload = Request.JsonPayload;
                //Check for compression and decompress if needed
                if (Request.isCompressed)
                {
                    Payload = Payload.Decompress();
                }
                //Then deserialize

                IRequest embeddedRequest = (IRequest)Payload.Deserialize(ProcessorHelper.ResolveRequestProcessorRequestType(Request.Kind));

                //Execute processor
                IResponse result = await processor.Process(embeddedRequest);

                // Create response
                GateResponse response = new GateResponse(Request);
                //Set the response data and compress if needed
                response.JsonPayload = result.Serialize();
                long uncompsize = response.JsonPayload.Length;
                if (response.JsonPayload.Length > 512)
                {
                    response.JsonPayload = response.JsonPayload.Compress(); response.isCompressed = true;
                }
                long compressedsize = response.JsonPayload.Length;
                //Stop timer and write stats
                sw.Stop();
                //Write stats
                if (!_StatDict.ContainsKey(Request.Kind))
                {
                    _StatDict.Add(Request.Kind, new RequestStats(Request.Kind));
                }
                _StatDict[Request.Kind].NumCalls++;
                _StatDict[Request.Kind].TotalTime      += sw.ElapsedMilliseconds;
                _StatDict[Request.Kind].CompressedSize += compressedsize;
                _StatDict[Request.Kind].TotalSize      += uncompsize;
                //Finalize response
                response.TimeTaken = sw.ElapsedMilliseconds;
                //Set response code
                response.ResultCode = (int)System.Net.HttpStatusCode.OK;
                this.ApplicationName.LogDebug(processor.ProcessorId.ToString(), sw.ElapsedMilliseconds.ToString());
                return(response);
            }
            catch (Exception E)
            {
                this.Log(E);
                GateResponse errorResponse = new GateResponse(Request);
                errorResponse.ResultCode = (int)HttpStatusCode.InternalServerError;
                return(await Task.FromResult(errorResponse));
            }
        }