public Emitter Emit(string eventString, IAck ack, params object[] args)
        {
            var log = LogManager.GetLogger(Global.CallerName());

            if (Events.Contains(eventString))
            {
                base.Emit(eventString, args);
                return(this);
            }

            var _args = new List <object> {
                eventString
            };

            _args.AddRange(args);

            var jsonArgs = Parser.Packet.Args2JArray(_args);

            var parserType = HasBinaryData.HasBinary(jsonArgs) ? Parser.Parser.BINARY_EVENT : Parser.Parser.EVENT;
            var packet     = new Packet(parserType, jsonArgs);

            log.Info(string.Format("emitting packet with ack id {0}", Ids));
            Acks      = Acks.Add(Ids, ack);
            packet.Id = Ids++;

            if (Connected)
            {
                Packet(packet);
            }
            else
            {
                SendBuffer = SendBuffer.Enqueue(packet);
            }
            return(this);
        }
Exemplo n.º 2
0
 public static IObservable<IAck<T>> ByMax<T, TResult>(this IObservable<IAck<T>> observable,
     Func<T, TResult> selector, Action<IAck<T>> complete)
 {
     return Observable.Create<IAck<T>>(obs =>
     {
         IAck<T> current = null;
         return observable.Subscribe(p =>
             {
                 if (current == null)
                 {
                     current = p;
                 }
                 else
                 {
                     if (Comparer<TResult>.Default.Compare(selector(current.Value), selector(p.Value)) > 0)
                     {
                         complete(p);
                     }
                     else
                     {
                         complete(current);
                         current = p;
                     }
                 }
             }, obs.OnError,
             () =>
             {
                 if (current != null)
                     obs.OnNext(current);
                 obs.OnCompleted();
             }
         );
     });
 }
Exemplo n.º 3
0
        public void OnUpdateGameSession(string rawUpdateGameSession, IAck ack)
        {
            log.DebugFormat("ServerState got the updateGameSession signal. rawGameSession : {0}", rawUpdateGameSession);

            if (!processReady)
            {
                log.Debug("Got an updated game session on inactive process. Sending false ack.");
                ack.Call(false);
                return;
            }
            log.Debug("Sending true ack.");
            ack.Call(true);

            Task.Run(() =>
            {
                Com.Amazon.Whitewater.Auxproxy.Pbuffer.UpdateGameSession updateGameSession =
                    JsonConvert.DeserializeObject <Com.Amazon.Whitewater.Auxproxy.Pbuffer.UpdateGameSession>(rawUpdateGameSession);
                GameSession gameSession   = GameSession.ParseFromBufferedGameSession(updateGameSession.GameSession);
                gameSessionId             = gameSession.GameSessionId;
                UpdateReason updateReason = UpdateReasonMapper.GetUpdateReasonForName(updateGameSession.UpdateReason);

                processParameters.OnUpdateGameSession(
                    new UpdateGameSession(gameSession, updateReason, updateGameSession.BackfillTicketId));
            });
        }
Exemplo n.º 4
0
        /// <summary>
        /// Подтверждение получения сообщения и прохождения ФЛК
        /// </summary>
        /// <param name="ackMessage"></param>
        public override IMessageStatus Ack(IAck ackMessage)
        {
            var ack = new AckTargetMessage()
            {
                Id       = ReferenceName,
                Accepted = ackMessage.IsValid,
                Value    = ackMessage.MessageId.ToString()
            };

            var signedMessage = CryptoProNetHelper.SignSmevObject(ack, ReferenceName, DefaultNamespace, SerialNumber);

            MessageStatus status = null;

            Execute(delegate
            {
                SmevService.Ack(ack, signedMessage);

                status = new MessageStatus()
                {
                    MessageId = ackMessage.MessageId,
                    Status    = ackMessage.IsValid ? Status.ФЛК_прошел_успешно : Status.Ошибки_ФЛК
                };
            }, ackMessage.MessageId);

            return(status);
        }
Exemplo n.º 5
0
        public static void TraceAckReceived(this ILogger log, IConnection con, IAck ack)
        {
            if (!IsTracePacketsEnabled)
            {
                return;
            }

            log.Info($"{con}: Ack for #{ack.PacketReceived} received");
        }
Exemplo n.º 6
0
        private void OnAck(Packet packet)
        {
            LogManager.GetLogger(Global.CallerName("", 0, ""))
            .Info(string.Format("calling ack {0} with {1}", (object)packet.Id, packet.Data));
            IAck ack = this.Acks[packet.Id];

            this.Acks = this.Acks.Remove(packet.Id);
            List <object> dataAsList = packet.GetDataAsList();

            ack.Call(dataAsList.ToArray());
        }
        T EmitEvent <T>(IMessage message, IAck ackFunction, TaskCompletionSource <T> future, T error) where T : GenericOutcome
        {
            log.DebugFormat("Emitting event for message {0}", message);
            lock (emitLock)
            {
                socket.Emit(message.Tag, ackFunction, ToByteArray(message));
            }
            if (!future.Task.Wait(TimeSpan.FromSeconds(30)))
            {
                future.TrySetResult(error);
            }

            return(future.Task.Result);
        }
Exemplo n.º 8
0
        protected async Task ProcessAck(string encryptedToken)
        {
            Ack ack = await base.DecryptAndInstantiateHandshakeToken <Ack>(encryptedToken);

            VerifyHandshakeTokenIDOwnership(ack);

            if (_tokenCryptoService.VerifySignature(ack))
            {
                Ack = ack;
                GenerateAndSendSynAck(ack);
            }
            else
            {
                throw new SignatureDoesntMatchException("The signature was not " +
                                                        "generated by the given " +
                                                        "public Key");
            }
        }
        public void OnStartGameSession(string rawGameSession, IAck ack)
        {
            log.DebugFormat("ServerState got the startGameSession signal. rawGameSession : {0}", rawGameSession);
            if (!processReady)
            {
                log.Debug("Got a game session on inactive process. Sending false ack.");
                ack.Call(false);
                return;
            }
            log.Debug("OnStartGameSession: Sending true ack.");
            ack.Call(true);

            Task.Run(() =>
            {
                GameSession gameSession = GameSessionParser.Parse(rawGameSession);
                gameSessionId           = gameSession.GameSessionId;
                processParameters.OnStartGameSession(gameSession);
            });
        }
Exemplo n.º 10
0
        public Emitter Emit(string eventString, IAck ack, params object[] args)
        {
            LogManager    logger     = LogManager.GetLogger(Global.CallerName("", 0, ""));
            List <object> objectList = new List <object>()
            {
                (object)eventString
            };

            if (args != null)
            {
                objectList.AddRange((IEnumerable <object>)args);
            }
            Packet packet = new Packet(2, (object)new JArray((object)objectList));

            logger.Info(string.Format("emitting packet with ack id {0}", (object)this.Ids));
            this.Acks = this.Acks.Add(this.Ids, ack);
            packet.Id = this.Ids++;
            this.Packet_method(packet);
            return((Emitter)this);
        }
Exemplo n.º 11
0
        public Emitter Emit(string eventString, IAck ack, params object[] args)
        {
            var log = LogManager.GetLogger(Global.CallerName());

            var _args = new List <object> {
                eventString
            };

            if (args != null)
            {
                _args.AddRange(args);
            }

            var jarray = new JArray(_args);
            var packet = new Packet(Parser.Parser.EVENT, jarray);

            log.Info(string.Format("emitting packet with ack id {0}", Ids));
            Acks      = Acks.Add(Ids, ack);
            packet.Id = Ids++;

            Packet(packet);
            return(this);
        }
        public void OnUpdateGameSession(string rawUpdateGameSession, IAck ack)
        {
            log.DebugFormat("ServerState got the updateGameSession.  rawGameSessionUpdate : {0}", rawUpdateGameSession);
            if (!processReady)
            {
                log.Debug("Got a update game session call on inactive process. Sending false ack.");
                ack.Call(false);
                return;
            }
            log.Debug("OnUpdateGameSession: Sending true ack.");
            ack.Call(true);

            Task.Run(() =>
            {
                Protobuf.UpdateGameSession updateGameSession =
                    JsonConvert.DeserializeObject <Protobuf.UpdateGameSession>(rawUpdateGameSession);
                GameSession gameSession   = GameSession.ParseFromBufferedGameSession(updateGameSession.GameSession);
                UpdateReason updateReason = UpdateReasonMapper.GetUpdateReasonForName(updateGameSession.UpdateReason);

                processParameters.OnUpdateGameSession(
                    new UpdateGameSession(gameSession, updateReason, updateGameSession.BackfillTicketId));
            });
        }
Exemplo n.º 13
0
        public bool TryGetResult(IAck ack, out IGetStateResult result)
        {
            using (var client = new PaymentPortsTypeAsyncClient(_binding, _remoteAddress)) {
                client.Endpoint.EndpointBehaviors.Add(new MyEndpointBehavior());

                if (!_config.IsPPAK)
                {
                    client.ClientCredentials.UserName.UserName = Constants.UserAuth.Name;
                    client.ClientCredentials.UserName.Password = Constants.UserAuth.Passwd;
                }

                if (!_config.UseTunnel)
                {
                    client.ClientCredentials.ClientCertificate.SetCertificate(
                        StoreLocation.CurrentUser,
                        StoreName.My,
                        X509FindType.FindByThumbprint,
                        base._config.CertificateThumbprint);
                }

                var responce = client.getState(new getStateRequest1 {
                    RequestHeader   = RequestHelper.Create <RequestHeader>(_config.OrgPPAGUID, _config.Role),
                    getStateRequest = new getStateRequest {
                        MessageGUID = ack.MessageGUID
                    }
                });

                if (responce.getStateResult.RequestState == 3)
                {
                    result = responce.getStateResult;
                    return(true);
                }

                result = null;
                return(false);
            }
        }
Exemplo n.º 14
0
#pragma warning restore AMNF0001 // Asynchronous method name is not ending with 'Async'
            #endregion           // Completion

            #region ConsumingAsync

            /// <summary>
            /// Handles consuming of single event.
            /// </summary>
            /// <param name="arg">The argument.</param>
            /// <param name="ack">
            /// The acknowledge callback which will prevent message from
            /// being re-fetch from same consumer group.</param>
            /// <returns></returns>
            private async ValueTask ConsumingAsync(
                Announcement arg,
                IAck ack)
            {
                CancellationToken cancellation = _plan.Cancellation;
                Metadata          meta         = arg.Metadata;

                #region Increment & Validation Max Messages Limit

                long count = Interlocked.Increment(ref _consumeCounter);
                if (_maxMessages != 0 && _maxMessages < count)
                {
                    await DisposeAsync();

                    throw new OperationCanceledException(); // make sure it not auto ack;
                }

                #endregion // Increment & Validation Max Messages Limit

                var consumerMeta = new ConsumerMetadata(meta, cancellation);
                T   instance     = _factory(consumerMeta);
                #region Validation

                if (instance == null)
                {
                    throw new NullReferenceException("_factory(consumerMeta)");
                }

                #endregion // Validation

                var logger = _plan.Logger;
                logger.LogDebug("Consuming event: {0}", meta.Key());

                #region Validation

                if (instance == null)
                {
                    var ex = new ArgumentNullException("Cannot create instance");
                    _plan.Logger?.LogWarning(ex, "Consumer fail to create instance");
                    throw ex;
                }

                #endregion // Validation

                #region _plan.Interceptors.InterceptAsync(...)

                Bucket interceptionBucket = arg.InterceptorsData;
                foreach (var interceptor in _plan.Interceptors)
                {
                    if (!interceptionBucket.TryGetValue(
                            interceptor.InterceptorName,
                            out ReadOnlyMemory <byte> interceptedData))
                    {
                        interceptedData = ReadOnlyMemory <byte> .Empty;
                    }
                    await interceptor.InterceptAsync(meta, interceptedData);
                }

                #endregion // _plan.Interceptors.InterceptAsync(...)

                #region MethodInfo? method = type.GetMethod(operation)

                string     operation = arg.Metadata.Operation;
                Type       type      = instance.GetType();
                var        binding   = BindingFlags.Public | BindingFlags.Instance;
                MethodInfo?method    = type.GetMethod(operation, binding);
                #region Validation

                if (method == null)
                {
                    var ex = new ArgumentNullException("Cannot get method");
                    _plan.Logger?.LogWarning(ex, "Consumer fail to get method");
                    throw ex;
                }

                #endregion // Validation

                #endregion // MethodInfo? method = type.GetMethod(operation)

                ParameterInfo[] parameters = method.GetParameters();

                #region object[] arguments = ... unclassify

                object[] arguments = new object[parameters.Length];
                for (int i = 0; i < parameters.Length; i++)
                {
                    #region Unclassify(segmentations)

                    ParameterInfo?parameter  = parameters[i];
                    MethodInfo?   unclassify = this.GetType().GetMethod(nameof(UnclassifyAsync), BindingFlags.NonPublic | BindingFlags.Instance);
                    unclassify = unclassify?.MakeGenericMethod(parameter.ParameterType);

                    #region Validation

                    if (unclassify == null)
                    {
                        throw new ArgumentNullException(nameof(unclassify));
                    }

                    #endregion // Validation

                    var prm = parameter?.Name ?? throw new NullReferenceException();
                    ValueTask <object>?args = (ValueTask <object>?)unclassify.Invoke(
                        this, new object[] { arg, prm });
                    arguments[i] = await(args ?? throw new NullReferenceException());

                    #endregion // Unclassify(segmentations)
                }

                #endregion // object[] arguments = ... unclassify

                try
                {
                    await using (Ack.Set(ack))
                    {
                        await _plan.ResiliencePolicy.ExecuteAsync(async() => {
                            var res = method.Invoke(instance, arguments);
                            if (res is ValueTask vtsk)
                            {
                                await vtsk;
                            }
                            if (res is Task tsk)
                            {
                                await tsk;
                            }
                        });
                    }
                    logger.LogDebug("Consumed event: {0}", meta.Key());

                    var behavior = _plan.Options.AckBehavior;
                    if (behavior == AckBehavior.OnSucceed)
                    {
                        await ack.AckAsync();
                    }
                }
                #region Exception Handling

                catch (OperationCanceledException)
                {
                    logger.LogWarning("Canceled event: {0}", meta.Key());
                    if (_plan.Options.AckBehavior != AckBehavior.OnFinally)
                    {
                        await ack.CancelAsync();

                        throw;
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "event: {0}", meta.Key());
                    if (_plan.Options.AckBehavior != AckBehavior.OnFinally)
                    {
                        await ack.CancelAsync();

                        throw;
                    }
                }

                #endregion // Exception Handling
                finally
                {
                    if (_plan.Options.AckBehavior == AckBehavior.OnFinally)
                    {
                        await ack.AckAsync();
                    }

                    #region Validation Max Messages Limit

                    if (_maxMessages != 0 && _maxMessages <= count)
                    {
                        await DisposeAsync();
                    }

                    #endregion // Validation Max Messages Limit
                }
            }
Exemplo n.º 15
0
 public static void Nack <T>(this IAck <T> ack) => ack.SetResult(Acknowledge.Nack);
Exemplo n.º 16
0
 public static void Requeue <T>(this IAck <T> ack) => ack.SetResult(Acknowledge.Requeue);
Exemplo n.º 17
0
        public Emitter Emit(string eventString, IAck ack, params object[] args)
        {
            var log = LogManager.GetLogger(Global.CallerName());

            var _args = new List<object> { eventString };
            if (args != null)
            {
                _args.AddRange(args);                
            }

            var jarray = new JArray(_args);
            var packet = new Packet(Parser.Parser.EVENT, jarray);

            log.Info(string.Format("emitting packet with ack id {0}", Ids));
            Acks.TryAdd(Ids, ack);
            packet.Id = Ids++;

            Packet(packet);
            return this;
        }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="ack">The ack.</param>
 public Scope(IAck ack)
 {
     _context.Value = ack;
 }
Exemplo n.º 19
0
 /// <summary>
 /// Sets ack.
 /// </summary>
 /// <param name="ack"></param>
 /// <returns></returns>
 public static IAsyncDisposable Set(IAck ack)
 {
     return(new Scope(ack));
 }