Пример #1
0
        async Task <bool> ITankGameSession.StartRound(ActorId aUserId)
        {
            try
            {
                GameSessionState state = await this.GetStateAsync <GameSessionState>();

                List <Task> tasks            = new List <Task>();
                int         currentuserround = 0;
                foreach (TankSessionMemberItem i in state.Players)
                {
                    tasks.Add(i.TankId.Proxy <ITank>().ResetAsync());
                    if (i.UserId == aUserId)
                    {
                        i.CurrentRound++;
                        currentuserround = i.CurrentRound;
                    }
                }
                await Task.WhenAll(tasks);

                await this.SetStateAsync(state);


                //And notify
                StartRoundResponse srr = new StartRoundResponse();
                srr.RoundNum = currentuserround;
                srr.Status   = HttpStatusCode.OK;
                srr.UserId   = aUserId.GetGuidId();
                foreach (TankSessionMemberItem i in state.Players)
                {
                    GateResponse gr = new GateResponse((int)RequestProcessorEnum.StartRound, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), srr.Serialize());
                    await i.UserId.Proxy <IUser>().SendGateResponseAsync(gr);
                }

                bool OnSameRound = true;
                for (int i = 0; i < state.Players.Count - 1; i++)
                {
                    if (state.Players[i].CurrentRound != state.Players[i + 1].CurrentRound)
                    {
                        OnSameRound = false;
                    }
                }
                if (OnSameRound)
                {
                    BeginRounResponse brr = new BeginRounResponse(this.Id.GetGuidId(), currentuserround);
                    brr.Status = HttpStatusCode.OK;
                    foreach (TankSessionMemberItem i in state.Players)
                    {
                        GateResponse gr = new GateResponse((int)RequestProcessorEnum.BeginRound, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), brr.Serialize());
                        await i.UserId.Proxy <IUser>().SendGateResponseAsync(gr);
                    }
                }

                return(true);
            }
            catch (Exception E)
            {
                this.Log(E);
                return(false);
            }
        }
Пример #2
0
        public async Task Test()
        {
            var gateResponse = new GateResponse
            {
                StatusCode = 201,
                Headers    = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("Content-Type", "application/json")
                },
                ReasonPhrase = "REASON",
                Content      = Encoding.UTF8.GetBytes("Test")
            };

            var httpContext = new DefaultHttpContext();

            httpContext.Response.Body = new MemoryStream();
            await gateResponse.PopulateHttpResponseAsync(httpContext.Response);

            Assert.AreEqual(gateResponse.StatusCode, httpContext.Response.StatusCode);
            Assert.AreEqual(gateResponse.ReasonPhrase, httpContext.Response.HttpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase);
            Assert.IsTrue(gateResponse.Headers.All(h =>
                                                   httpContext.Response.Headers.ContainsKey(h.Key) &&
                                                   httpContext.Response.Headers[h.Key].Contains(h.Value)));
            var responseBytes = ((MemoryStream)httpContext.Response.Body).ToArray();

            Assert.IsTrue(gateResponse.Content.SequenceEqual(responseBytes));
        }
        public static async Task <GateResponse> ToGateResponseAsync(this HttpResponseMessage httpResponseMessage)
        {
            var gateResponse = new GateResponse
            {
                Content      = await httpResponseMessage.Content.ReadAsByteArrayAsync(),
                StatusCode   = (int)httpResponseMessage.StatusCode,
                ReasonPhrase = httpResponseMessage.ReasonPhrase,
                Headers      = new List <KeyValuePair <string, string> >()
            };

            foreach (var header in httpResponseMessage.Content.Headers)
            {
                gateResponse.Headers.AddRange(header.Value.Select(v => new KeyValuePair <string, string>(header.Key, v)));
            }

            foreach (var header in httpResponseMessage.Headers)
            {
                gateResponse.Headers.AddRange(header.Value.Select(v => new KeyValuePair <string, string>(header.Key, v)));
            }

            // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
            gateResponse.Headers.RemoveAll(kvp => kvp.Key == "transfer-encoding");

            return(gateResponse);
        }
Пример #4
0
        async Task ITankGameSession.NotifyPosition(ActorId TankId, float x, float y, float z, float r)
        {
            try
            {
                GameSessionState state = await this.GetStateAsync <GameSessionState>();

                List <Task> notes = new List <Task>();

                TankPosistionResponse resp = new TankPosistionResponse(TankId.GetGuidId(), x, y, z, r);
                string         serialized  = resp.Serialize();
                List <ActorId> TargetUids  = state.Players.Select(p => p.UserId).Distinct().ToList();
                foreach (TankSessionMemberItem i in state.Players)
                {
                    if (i.TankId != TankId)
                    {
                        GateResponse gr = new GateResponse((int)RequestProcessorEnum.TankPosition, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), serialized);
                        await i.UserId.Proxy <IUser>().SendGateResponseAsync(gr);
                    }
                }
            }
            catch (Exception E)
            {
                this.Log(E);
            }
        }
Пример #5
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);
            }
        }
Пример #6
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();
            }
        }
Пример #7
0
        public async Task <string> pinggw()
        {
            try
            {
                GameFabric.Logging.Logger.Instance.Message($"Called pinggw at{DateTime.UtcNow.ToUniversalTime()} ms: {DateTime.UtcNow.Millisecond}. ");
                ActorId      gwid = new ActorId(1);
                GateResponse r    = await gwid.Proxy <IGate>().Process(new GateRequest());

                return(r.JsonPayload);
            }
            catch (Exception e)
            {
                e.Log();
                return(e.FormatException());
            }
        }
Пример #8
0
        async Task <bool> ITankGameSession.TakeDamage(ActorId TankID, float amount)
        {
            try
            {
                bool             isDead    = false;
                float            newHealth = 0.0f;
                GameSessionState state     = await this.GetStateAsync <GameSessionState>();

                foreach (TankSessionMemberItem i in state.Players)
                {
                    if (i.TankId == TankID)
                    {
                        newHealth = await(i.TankId.Proxy <ITank>().TakeDamageAsync(amount));
                        if (newHealth <= 0)
                        {
                            isDead = true;
                        }
                    }
                }
                await this.SetStateAsync(state);

                //Notify clients
                TakeDamageResponse tdr = new TakeDamageResponse();
                tdr.Status            = System.Net.HttpStatusCode.OK;
                tdr.TankGameSessionId = this.Id.GetGuidId();
                tdr.TankId            = TankID.GetGuidId();
                tdr.Health            = newHealth;
                tdr.isDead            = isDead;

                List <Task> tasks = new List <Task>();
                foreach (TankSessionMemberItem i in state.Players)
                {
                    GateResponse gr = new GateResponse((int)RequestProcessorEnum.TakeDamage, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), tdr.Serialize());
                    tasks.Add(i.UserId.Proxy <IUser>().SendGateResponseAsync(gr));
                }
                await Task.WhenAll(tasks);

                //End notify clients
                return(isDead);
            }
            catch (Exception E)
            {
                this.Log(E);
                return(false);
            }
        }
Пример #9
0
        async Task ITankGameSession.NotifyFireShell(ActorId TankId, string SerializedData)
        {
            try
            {
                GameSessionState state = await this.GetStateAsync <GameSessionState>();

                List <ActorId> TargetUids = state.Players.Select(p => p.UserId).Distinct().ToList();
                foreach (TankSessionMemberItem i in state.Players)
                {
                    GateResponse gr = new GateResponse((int)RequestProcessorEnum.FireShell, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), SerializedData);
                    await i.UserId.Proxy <IUser>().SendGateResponseAsync(gr);
                }
            }
            catch (Exception E)
            {
                this.Log(E);
            }
        }
Пример #10
0
        async Task <bool> IUser.SendGateResponseAsync(GateResponse response)
        {
            try
            {
                UserState state = await this.GetStateAsync <UserState>();

                if (!state.isCreated)
                {
                    return(false);
                }
                var ev = GetEvent <IUserEvent>();
                ev.SendGateResponseAsync(response);
                return(true);
            }
            catch (Exception E)
            {
                this.Log(E);
                return(false);
            }
        }
Пример #11
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();
            }
        }
Пример #12
0
        public static async Task PopulateHttpResponseAsync(this GateResponse gateResponse, HttpResponse httpResponse)
        {
            httpResponse.StatusCode = gateResponse.StatusCode;
            httpResponse.HttpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase = gateResponse.ReasonPhrase;

            if (gateResponse.Headers != null)
            {
                var headerNames = gateResponse.Headers
                                  .Select(h => h.Key)
                                  .Distinct();
                foreach (var headerName in headerNames)
                {
                    var headerValues = gateResponse.Headers
                                       .Where(h => h.Key == headerName)
                                       .Select(h => h.Value)
                                       .ToArray();
                    httpResponse.Headers.Add(headerName, new StringValues(headerValues));
                }
            }

            // RequestAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
            httpResponse.Headers.Remove("transfer-encoding");
            await httpResponse.Body.WriteAsync(gateResponse.Content, CancellationToken.None);
        }
Пример #13
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));
            }
        }
        public async Task <IResponse> Process(IRequest request)
        {
            try
            {
                JoinOrCreateGameSessionRequest  rq       = request as JoinOrCreateGameSessionRequest;
                JoinOrCreateGameSessionResponse response = new JoinOrCreateGameSessionResponse();
                List <ActorId> NotifyList = new List <ActorId>();
                //test if there is a session
                var listproxy = new ActorId(1).Proxy <ITankGameSessionList>();
                if (await listproxy.HasSessionsAsync())
                {
                    GameSessionListItem itm = await listproxy.GetNextSessionAsync();

                    if (itm != null)
                    {
                        response.GameSessionId  = itm.GameSessionId.GetGuidId();
                        response.Status         = HttpStatusCode.OK;
                        response.waitForPlayers = false;
                        response.start          = true;
                        await listproxy.RemoveGameSessionAsync(itm.GameSessionId);

                        var sessionproxy = itm.GameSessionId.Proxy <ITankGameSession>();
                        int sequenceno   = await sessionproxy.JoinAsync(new ActorId(rq.UserId));

                        //Get players
                        List <TankSessionMemberItem> members = await sessionproxy.GetPlayersAsync();

                        foreach (TankSessionMemberItem i in members)
                        {
                            response.SessionPlayers.Add(new GameSessionPlayerItem(i.UserId.GetGuidId(), i.TankId.GetGuidId(), i.Sequence)); NotifyList.Add(i.UserId);
                        }
                    }
                    else
                    {
                        response.Status = HttpStatusCode.InternalServerError;
                        ErrorResponse errorresponse = new ErrorResponse("Failed to create gamesession");
                        return(errorresponse);
                    }
                }
                else
                {
                    Guid    newSessionid   = Guid.NewGuid();
                    ActorId sessionActorId = new ActorId(newSessionid);
                    if (await listproxy.AddGameSessionAsync(sessionActorId))
                    {
                        //Set Session Params
                        var sessionproxy = sessionActorId.Proxy <ITankGameSession>();
                        int sequenceno   = await sessionActorId.Proxy <ITankGameSession>().JoinAsync(new ActorId(rq.UserId));

                        response.GameSessionId  = newSessionid;
                        response.Status         = HttpStatusCode.OK;
                        response.waitForPlayers = true;
                        response.start          = false;
                        //Get players
                        List <TankSessionMemberItem> members = await sessionproxy.GetPlayersAsync();

                        foreach (TankSessionMemberItem i in members)
                        {
                            response.SessionPlayers.Add(new GameSessionPlayerItem(i.UserId.GetGuidId(), i.TankId.GetGuidId(), i.Sequence)); NotifyList.Add(i.UserId);
                        }
                    }
                    else
                    {
                        response.Status = HttpStatusCode.InternalServerError;
                        ErrorResponse errorresponse = new ErrorResponse("Failed to create gamesession");
                        return(errorresponse);
                    }
                }
                response.Status = HttpStatusCode.OK;
                //Notidy participants
                if (NotifyList.Count == 0)
                {
                    NotifyList.Add(new ActorId(rq.UserId));
                }
                foreach (ActorId uid in NotifyList)
                {
                    GateResponse gr = new GateResponse(this.ProcessorId, (int)System.Net.HttpStatusCode.OK, uid.GetGuidId(), response.Serialize());
                    await uid.Proxy <IUser>().SendGateResponseAsync(gr);
                }
                return(await Task.FromResult(response));
            }
            catch (Exception E)
            {
                E.Log();
                ErrorResponse errorresponse = new ErrorResponse(E.Message);
                return(errorresponse);
            }
        }